I know we cannot do this at class level but at method level we can always do this.
var myList=new List<string> // or something else like this
This question came to my mind since wherever we declare variable like this. We always provide the type information at the RHS of the expression. So compiler doesn't need to do type guessing. (correct me if i am wrong).
so question remains WHY NOT at class level while its allowed at method level
var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function. var cannot be used on fields at class scope.
Var is used to declare Implicitly typed variable where the compiler identifies the type automatically. var can hold any type of data. String is an explicit declaration for holding string data only.
By using “var”, you are giving full control of how a variable will be defined to someone else. You are depending on the C# compiler to determine the datatype of your local variable – not you. You are depending on the code inside the compiler – someone else's code outside of your code to determine your data type.
There are technical issues with implementing this feature. The common cases seem simple but the tougher cases (e.g., fields referencing other fields in chains or cycles, expressions which contain anonymous types) are not.
See Eric Lippert's blog for an in-depth explanation: Why no var on fields?
The compiler guys just didn't implement the support.
It's entirely compiler magic, and the compiler doesn't actually put something into IL that says "figure out the type at runtime", it knows the type and builds it in, so it could've done that for members as well.
It just doesn't.
I'm pretty sure that if you asked an actual compiler guy on the C# compiler team, you'd get something official, but there's no magic happening here and it should be possible to do the same for members fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With