Wednesday, March 5, 2008

[.NET] VB - C# Type Conversion Differences

There are some basic differences between VB.NET and C# when it comes to type conversion.

In both VB and C# widening conversions are implicit. Widening means that the destination type can represent all the possible values of the source type:


' VB sample
Dim myInteger As Integer = 1
Dim d As
myDouble = 1.007
myDouble = myInteger

'Helluva Implicit conversion allowed

// C# sample
int myInteger = 1;
double myDouble = 1.0001;
myDouble = myInteger;

//Implicit Conversion
//allowed


For narrowing conversion - let's say assigning a double to an int, when the destination type cannot represent all possible values of the source type - things change: you need to explicitly cast in C# while in VB the conversion keeps being implicit (don't come asking for an example plz... ).
If you want VB to behave as C# in case of narrowing conversions you have two options: either write at the very top of the code Option Strict On to enable the option at page level, or set the same Options Strict from the project properties to enable it at project level.

This difference reflects VB's wannabe-user-friendly attitude that often ends up messing-up things for people who's learning; but since every .NET developer is called once in a while to do some quick and dirty job using VB (there's a whole lot of frightening VB code out there) we certainly gotta deal with it.

That's all - Kick ass.

6 comments:

Francy said...

We offers conversion from various file formats and media to other. With our extensive technical expertise in this area, we are almost certain to cater to any of your complex data
conversion
requirements, be it in any format, file types or media.

Johnny Idol said...

This comment is too ridiculous for us to delete it. Let's keep it as an example of how SEO scam infest the internet.

Scuffia said...

cite:
"With our extensive technical expertise in this area"
... sure You are not one of them!!
LOL :D

Sam said...

I learn more from blogs than I do from my 10+ computer books stacked around.

I can convert your files, too--send me stock options :)

Johnny Idol said...

What about the start: "We offerS (...) ", this is too fucked-up to be real

Anonymous said...

Hey, it's plural, isn't it? I offer, you offer, we offers :)