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

I tried to do something like below, but this does not work. Why doesn't .NET allow me to do this?

private void MyFunction(var items) { //whatever } 
+4
source share
3 answers

Starting with Visual C # 3.0, variables declared in a method scope can be of the imp type var. An implicitly typed local variable is strongly typed in the same way as if you declared the type yourself, but the compiler determines the type. The following two declarations are functionally equivalent:

 var i = 10; // implicitly typed int i = 10; //explicitly typed 

In other words, the var keyword is only allowed for locally restricted variables.

Source

A bit more here . Basically, when using var you should also initialize the variable to a value on the same line so that the compiler knows what type it is.

+7
source

Strictly speaking, you can pass an anonymous type as an argument, but you cannot access its members in a strongly typed way. Use the generic type argument:

 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); } 
+2
source

C # is a strongly typed language; adding anonymous types has not changed this.

Of course, you can pass a variable like an object (or an array of objects) into a 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, perhaps there is a better design.

+1
source

Source: https://habr.com/ru/post/1315004/


All Articles