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/
Author by
Michael
Updated on September 14, 2021Comments
-
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 over 11 yearsWith
((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 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) accessMember
ofvariable
first; 2) then castMember
toTypeWichCastTo
. -
Dennis over 11 years1) 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 VBCType
operator; 2) The second option has unnecessary brackets, see answer to your comment below. So, down-voted, especially foras
negligent usage. -
Jeppe Stig Nielsen almost 11 yearsAs Dennis said, don't use
as
in cases like this. It might lead to a non-informativeNullReferenceException
. -
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 over 6 years
CType
does not cast an object, it converts it.DirectCast
orTryCast
are the casting operations. For example,Dim i As Integer = CType("1", Integer)
is valid, butDim i As Integer = DirectCast("1", Integer)
is not