tags:

views:

438

answers:

3

I'm coming from a C# background and I really like the type inference that C# 3.0 has. I'm trying to do similar things in VB.NET (some of which appear possible), but in some cases the compiler seems to be not nearly as good at inferring the type.

For example, I have a method that returns an object of type System.Guid. In C# I'd do this and the variable 'i' would be of type Guid through inference.

var prop = RegisterProperty(Of Guid)(...);

However, if I do a similar thing in VB.NET:

Dim prop = RegisterProperty(Of Guid(...)

I get prop as type System.Object. I've played with some of the VB.NET project settings but the only thing it changes is whether I get a warning that the object is of type Object when I use it later as a Guid.

Any ideas? I'm thinking the use of generics should allow the compiler to tell beyond a doubt what type prop should be.

+1  A: 

I'm assuming by "played with the VB.NET project settings" you mean you already did this: Type Inference in VB.NET

If not, may help

J Cooper
A: 

@J Cooper: ok, I did have that setting turned on, but I just re-read the documentation for that compiler option and it reads "Specifies whether to allow local type inference in variable declarations". I believe the reason it's not working for me is that I'm declaring static fields in my class. I guess even though they are initialized when declared, the compiler doesn't support type inference at that point. Bummer.

Jeremy Wiebe
you can't use the var keyword to define non-locals. What's so hard about typing "Guid" anyhow? It's one letter longer.
TheSoftwareJedi
Actually, using type inference would make it alot shorter. Example: "Dim a as PropertyInfo(Of Guid) = CreatePropertyInfo(Of Guid)(...)" Compared to this: "Dim a = CreatePropertyInfo(Of Guid)(...)"Based on the way we're using these properties, it's not confusing at all
Jeremy Wiebe
A: 

You mention below that you're trying to do this in a static variable declaration. That won't work in C#, and will give you Object in VB.NET (for instance and statics).

TheSoftwareJedi
Yes, I do realize Guid is only 4 keystrokes. My question was simplified from my code where the classes are between 10 and 15 chars. Since I'm using VB.NET there's extra characters with the generics for all of the "(Of ...)" stuff. Thanks for pointing out the static field... that was my problem.
Jeremy Wiebe
sweet... so I got the answer right, and was awarded a -2. At least throw the correct answer my way!
TheSoftwareJedi
I wasn't the one who down-voted you, by the way. But you did answer my question. Thanks.
Jeremy Wiebe