var keyword constraints as class fields in C#

Hello friends. Hope you are doing well!!

Wish you happy new year!!

I am here to talk about the var keyword constraint, when using it in the class level fields in C#. Sometimes , we get a question that why can’t we use var keyword in 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:

 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.

Hope you liked the post. Look forward to your comments.

Leave a Reply

Your email address will not be published. Required fields are marked *