How do I translate VB.NET's CType() to C#?

47,998

Solution 1

In VB.Net CType(object, type) casts an object to a specific type.

There are two ways to accomplish this in C#:

Bitmap image = pbImageHolder.Image as Bitmap;
image.SetPixel(curPoint.X, curPoint.Y, Color.Purple);

or

Bitmap image = (Bitmap)(pbImageHolder.Image);
image.SetPixel(curPoint.X, curPoint.Y, Color.Purple);

Solution 2

((Bitmap)pbImageHolder.Image).SetPixel(curPoint.X, curPoint.Y, Color.Purple)

Solution 3

Hi this is the code after conversion VB to C# code:

((Bitmap)pbImageHolder.Image).SetPixel(curPoint.X, curPoint.Y, Color.Purple);

And if you want code conversion from VB to C# and vice verse go through the following link: http://www.developerfusion.com/tools/convert/vb-to-csharp/

Share:
47,998
Michael
Author by

Michael

Updated on September 14, 2021

Comments

  • Michael
    Michael over 2 years

    I have this code segment in VB.NET:

    CType(pbImageHolder.Image, Bitmap).SetPixel(curPoint.X, curPoint.Y, Color.Purple)
    

    What is appropriate code in C#?

  • Dennis Traub
    Dennis Traub over 11 years
    With ((Bitmap)pbImageHolder.Image) your trying to cast pbImageHolder to Bitmap, which probably won't work. The following will cast the image: (Bitmap)(pbImageHolder.Image)
  • Dennis
    Dennis over 11 years
    @DennisTraub: you're wrong, see C# language specification, section 7.3.1 "Operator precedence and associativity" (go.microsoft.com/fwlink/?LinkId=199552). Member access operator "." has precedence over cast operator, so, expressions like (TypeWichCastTo)variable.Member will evaluate this way: 1) access Member of variable first; 2) then cast Member to TypeWichCastTo.
  • Dennis
    Dennis over 11 years
    1) First option you provided strongly requires null-checking; as isn't intended for use cases without null-checking of result and can't be positioned as direct equivalent of VB CType operator; 2) The second option has unnecessary brackets, see answer to your comment below. So, down-voted, especially for as negligent usage.
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen almost 11 years
    As Dennis said, don't use as in cases like this. It might lead to a non-informative NullReferenceException.
  • SysDragon
    SysDragon almost 8 years
    @Dennis is a good advice but you don't need to downvote only because of that. The answer is still useful
  • SSS
    SSS over 6 years
    CType does not cast an object, it converts it. DirectCast or TryCast are the casting operations. For example, Dim i As Integer = CType("1", Integer) is valid, but Dim i As Integer = DirectCast("1", Integer) is not