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:
Anonymous type does not have an associated type identifier. So, it is impossible to use an anonymous type with a function parameter.
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 .
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.
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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With