Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an anonymous object as an argument in C#

I have a problem with passing an anonymous object as an argument in a method. I want to pass the object like in JavaScript. Example:

function Test(obj) {
    return obj.txt;
}
console.log(Test({ txt: "test"}));

But in C#, it throws many exceptions:

class Test
{
    public static string TestMethod(IEnumerable<dynamic> obj)
    {
        return obj.txt;
    }
}
Console.WriteLine(Test.TestMethod(new { txt = "test" }));

Exceptions:

  1. Argument 1: cannot convert from 'AnonymousType#1' to 'System.Collections.Generic.IEnumerable'
  2. The best overloaded method match for 'ConsoleApplication1.Test.TestMethod(System.Collections.Generic.IEnumerable)' has some invalid arguments
  3. 'System.Collections.Generic.IEnumerable' does not contain a definition for 'txt' and no extension method 'txt' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)
like image 511
user1091156 Avatar asked May 30 '12 18:05

user1091156


People also ask

Why is it impossible to use an anonymous type with a function parameter?

Anonymous type does not have an associated type identifier. So, it is impossible to use an anonymous type with a function parameter.

How do I make an anonymous object?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

What is an anonymous object?

An anonymous object is basically a value that has been created but has no name. Since they have no name, there's no other way to refer to them beyond the point where they are created. Consequently, they have “expression scope,” meaning they are created, evaluated, and destroyed everything within a single expression.


2 Answers

It looks like you want:

class Test
{
    public static string TestMethod(dynamic obj)
    {
        return obj.txt;
    }
}

You're using it as if it's a single value, not a sequence. Do you really want a sequence?

like image 81
Servy Avatar answered Oct 21 '22 05:10

Servy


This should do it...

class Program
{
    static void Main(string[] args)
    {
        var test = new { Text = "test", Slab = "slab"};
        Console.WriteLine(test.Text); //outputs test
        Console.WriteLine(TestMethod(test));  //outputs test
    }

    static string TestMethod(dynamic obj)
    {
        return obj.Text;
    }
}
like image 30
GrayFox374 Avatar answered Oct 21 '22 05:10

GrayFox374