Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we declare var a = new List<string> at class level?

Tags:

c#

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

like image 874
Prerak K Avatar asked Oct 01 '08 19:10

Prerak K


People also ask

Can you use VAR in class?

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.

What is the difference between VAR and string?

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.

Why do we use var in C#?

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.


2 Answers

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?

like image 117
Brian Avatar answered Oct 05 '22 12:10

Brian


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.

like image 30
Lasse V. Karlsen Avatar answered Oct 05 '22 13:10

Lasse V. Karlsen