Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I pass an anonymous type as a parameter to a function?

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
}
like image 369
Abe Miessler Avatar asked Dec 29 '22 11:12

Abe Miessler


1 Answers

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.

Source.

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.

like image 62
Nate Avatar answered Feb 22 '23 22:02

Nate