Why can't I pass an anonymous type as a parameter to a function?
Someone asked on Stack Overflow:
I was trying to do something like below but it doesn’t work. Why won’t .NET let me do this?
private void MyFunction(var items) { //whatever }
I posted the following answer, which was chosen as the accepted answer and received 7 upvotes:
Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
In otherwords, var keyword is only allowed for locally scoped variables.
A little bit more info here. Basically, when using var you must also initialize the variable to a value on the same line so that the compiler knows what type it is.
Notable comments
Nate (1 upvotes): @VincentVancalbergh I think that dynamic would provide for the use that OP was after.
Originally posted on Stack Overflow — 7 upvotes (accepted answer). Licensed under CC BY-SA.