user1091156
user1091156

Reputation: 249

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?)

Upvotes: 18

Views: 34517

Answers (3)

GrayFox374
GrayFox374

Reputation: 1782

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;
    }
}

Upvotes: 13

Rookian
Rookian

Reputation: 20569

This works fine :)

public class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(Test.TestMethod(new[] {new {txt = "test"}}));
        Console.ReadLine();
    }
}

public class Test
{
    public static string TestMethod(IEnumerable<dynamic> obj)
    {
        return obj.Select(o => o.txt).FirstOrDefault();
    }
}

Upvotes: 3

Servy
Servy

Reputation: 203812

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?

Upvotes: 36

Related Questions