-2

I have this code in VB.Net:

Dim c As Control

For Each c In Me.Controls

    If TypeOf (c) is PictureBox Then
    CType(c, PictureBox).Image = My.Resources.available
    End If

Next

What is appropriate code in C#?

qutie
  • 1
  • 2
  • 1
    The VB code is bad to begin with. If you use `For Each pb In Me.Controls.OfType(Of PictureBox)()` then you don't need an `If` statement or an additional cast. That code translates directly to C# as `foreach (var pb in this.Controls.OfType)()`. – jmcilhinney May 17 '21 at 06:53
  • 1
    @jmcilhinney slight typo correction: `foreach (var pb in this.Controls.OfType())`. C# would probably drop the `this` too – Caius Jard May 17 '21 at 10:58
  • 1
    @CaiusJard, thanks for the correction. As for using `this`, I'd certainly drop that myself but it is the direct translation of the `Me` used in the original VB so I chose to include it for that reason. – jmcilhinney May 17 '21 at 11:17

1 Answers1

1

It is

((PictureBox)c).Image = ...

See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions

You cast c to PictureBox

Note that you can also do

if (c is PictureBox picbox)
{
   picbox.Image = ...
}

This way you test that c is a PictureBox and (if so) immediately cast and store in that picbox variable.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111