Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it isn't possible to declare a method parameter as var type

Tags:

c#

.net

I wonder why it is not possible a method parameter as var type like

private void myMethod(var myValue) {
   // do something
}
like image 939
wonde Avatar asked Nov 27 '22 00:11

wonde


1 Answers

You can only use var for variables inside the method body. Also the variable must be assigned at declaration and it must be possible to deduce the type unambiguously from the expression on the right-hand side.

In all other places you must specify a type, even if a type could in theory be deduced.

The reason is due to the way that the compiler is designed. A simplified description is that it first parses everything except method bodies and then makes a full analysis of the static types of every class, member, etc. It then uses this information when parsing the method bodies, and in particular for deducing the type of local variables declared as var. If var were allowed anywhere then it would require a large change to the way the compiler works.

You can read Eric Lippert's article on this subject for more details:

  • Why no var on fields?
like image 106
Mark Byers Avatar answered Dec 18 '22 06:12

Mark Byers