Constraints In Using Var Keyword In Class Fields In C#

I am here to talk about the var keyword constraint, when using it in the class level fields in C#. Today, I got a question in my mind that why can't I use var keyword when initializing the class level fields.
 
Let's have a look at the code snippet, given below: 
  1. class A  
  2. {  
  3.  var x; //error  
  4.  int y; //ok  
  5. }   
The above declaration of x is not right as var is not allowed to be used in the class level declaration and this is the reason, it throws the following error.
 
The contextual keyword 'var' may only appear within a local variable declaration or in script code".
 
Clearly var is not something that can replace the data types.
 
But why so?
 
This is because the compiler is designed in a way that it assumes that all the class level initialization will have their type defined already.
 
If you are interested in the detailed answer, you may want to read the post from Eric Lippert at the link, given below:
 
If you have gone through the link, mentioned above, you can understand that in order to support the var in the class fields, re-write of the compiler is required and this would be a huge change.
 
Until that happens, keep using the var inside the methods, where it can infer the datatype at the compile time.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now