Why can't the var keyword in C-sharp be used in fields?

for fields, there is no difference except for storage location, life cycle, and initialization. Since the type of local variable can be inferred, the field should also be inferred.

Jul.11,2021

var is a new type that defines variables. It weakens the definition of types. VAR can replace any type. The compiler will determine what type you want to use according to the context. When you use VAR, I think you are not sure what type you are going to use. But at present, basically there are certain character types behind the keywords of var before they can be applied to fields. I think this is because the current compiler is not intelligent enough to fully judge your field type according to the context. And the variables applied by the Var keyword are initially assigned an initial value and are local, but most of the fields in our table are applied globally rather than locally, and there is no need to assign an initial value or the system will automatically have an initial value of 0. So just the Var keyword cannot be applied to the field, and it needs to be combined with the corresponding data type, because it only weakens the definition, not does not define it.

Menu