What about using var? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What about using var?

Couldn't you just use var as parameter type? The compiler would decide the appropriate type then.

27th Dec 2016, 9:16 PM
Lord Dunkin
Lord Dunkin - avatar
3 Answers
+ 6
the compiler does not allow this because there is no context clues for the computer to figure out the actual data type of the parameter, which is required for you to use it in the function. that is why compilers require that you initialize var variables on the same line. if you really want to use a variable that could have any data type, just pass an object variable as the parameter. then you can cast it to call class specific methods and fields, or you could use the new c# 7.0 features to find the data type https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
10th Jan 2017, 8:58 PM
Akinni James
Akinni James - avatar
+ 1
Because you can't use var as a valid data type as a parameter in the method signature. public void Swap<T>(ref T a, ref T b) => Valid public void Swap( ref var a, ref var b) => Invalid
21st Feb 2017, 2:59 PM
Elfren Authorlee
Elfren Authorlee - avatar
- 1
variable
9th Jan 2017, 8:05 PM
Win Htut
Win Htut - avatar