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 'prop' would be of type Guid through inference.
var prop = RegisterProperty<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.
@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.
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).
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
If VB is infering the type as Object, you need to turn Option Strict On at the top of your class file at least. Once you do that, you should see that class fields do not support type inferencing. The following raises the compiler error "Option Strict On requires all variable declarations to have an As clause".
如果VB將類型推斷為Object,則至少需要在類文件的頂部打開Option Strict On。執行此操作后,您應該看到類字段不支持類型推斷。以下引發了編譯器錯誤“Option Strict On要求所有變量聲明都有一個As子句”。
Public Shared foo = "Test"
In general, you should use Dim inside of methods and Public/Private/Friend on the class/module level fields.
通常,您應該在方法和類/模塊級別字段中使用方法中的Dim和Public / Private / Friend。