user1726343
user1726343

Reputation:

Why doesn't VB.Net type inference work in class fields?

If I were to type the following into a method body:

Dim myInt = 1

the Visual Studio IDE (and therefore, I am guessing, the compiler) infers the type of myInt to be Integer.

EDIT

Apparently using a literal was a bad choice here, since I've become embroiled in a lengthy debate that has nothing to do with the question. If you take issue with the fact that the expression 1 might be interpreted as an instance of different numeric types, pretend I had written:

Dim myInstance = New MyClass()

END EDIT

However, when I put a field declaration with the exact same code at the top of a class, the type of myList is not inferred:

Public Class Foo
    Dim myInt = 1
End Class

On mouseover, it mentions the absence of an As clause, and says a type of Object has been assumed. I cannot pass myInt as an argument to a function or sub that expects an Integer argument, without explicitly adding an As clause or casting to Integer.

Is there a discrepancy between how the IDE and compiler deal with type inference? If, on the other hand, the compiler can't infer type in this situation either, why the discrepancy between method variables and class fields?

Upvotes: 3

Views: 416

Answers (1)

tinstaafl
tinstaafl

Reputation: 6958

What you've found is that way on purpose. here is the MSDN expalanation.

Local type inference applies at procedure level. It cannot be used to declare variables at module level (within a class, structure, module, or interface but not within a procedure or block). If num2 in the previous example were a field of a class instead of a local variable in a procedure, the declaration would cause an error with Option Strict on, and would classify num2 as an Object with Option Strict off. Similarly, local type inference does not apply to procedure level variables declared as Static.

Upvotes: 3

Related Questions