https://dotnetfiddle.net/446j0U link to reproduce (failed on .net 4.7.2 not on .net core)
public class TEST {
static public void Main(string[] args)
{
var test = new { Text = "test", Slab = "slab"};
Console.WriteLine(test.Text); //outputs test
Console.WriteLine(TEST.TestMethod(test)); //outputs slab
}
static public string TestMethod(dynamic obj)
{
return obj.Slab;
}
}
access to anonymous object in the same function is working OK but when I try to pass it in the function I'm getting exception
Run-time exception (line 14): Attempt by method 'DynamicClass.CallSite.Target(System.Runtime.CompilerServices.Closure, System.Runtime.CompilerServices.CallSite, System.Object)' to access type '<>f__AnonymousType0`2' failed.
Stack Trace:
[System.TypeAccessException: Attempt by method 'DynamicClass.CallSite.Target(System.Runtime.CompilerServices.Closure, System.Runtime.CompilerServices.CallSite, System.Object)' to access type '<>f__AnonymousType0`2' failed.] at CallSite.Target(Closure , CallSite , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0) at TEST.TestMethod(Object obj) :line 14 at TEST.Main(String[] args) :line 9
Edit by @RandRandom:
Since the bounty period is almost over, I decided to edit this question.
The given answers so far all fail to actually answer the problem at hand and only give ways to avoid the error.
OP clearly stated (in comments) that he is aware of workarounds and is currently using a workaround.
Those questions still remain
To recap here are OP's Information so far:
As C# documentation says:
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.
There are two obvious ways:
1) Replace anonymous type with pre-defined:
public class Container {
public string Test { get; set; }
public string Slab { get; set; }
}
public static void Main(string[] args) {
var test = new Container { Text = "test", Slab = "slab"};
Console.WriteLine(test.Text); //outputs test
Console.WriteLine(TestMethod(test)); //outputs slab
}
public static string TestMethod(dynamic obj) {
return obj.Slab;
}
This way restricts you not to use an anonymous type. But it will work fine.
2) or if you like anonymous types, use casting with ExpandoObject.
Documentation: https://docs.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?redirectedfrom=MSDN&view=netframework-4.8
Sample: https://sebnilsson.com/blog/convert-c-anonymous-or-any-types-into-dynamic-expandoobject/
This should work,
static public string TestMethod(dynamic obj) {
return obj.GetType().GetProperty("Slab").GetValue(obj).ToString();
}
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