views:

63

answers:

3

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
}
+6  A: 

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.

Nate Bross
+1  A: 

C# is a strongly typed language, the addition of anonymous types didn't alter that.

You could of course pass a variable of type object (or an object array) to the function,

private void MyFunction(object items)
{
  //Typecast to whatever you like here....But frankly this is a "code smell"
}

Perhaps you could tell us what you are trying to achieve, maybe there is a better design.

Tim Jarvis
+1  A: 

Strictly saying, you can pass anonymous type as argument, but you can't access it members in strongly typed way. Use generic type argument inferring:

public static int Foo<T>(T obj)
{
    return obj.GetHashCode();
}

public static void Main()
{
   var anonymousType = new { Id = 2, Name = "Second" };
   var value = Foo(anonymousType);
}
STO