RuntimeBinderException of C# anonymous type
Anonymous types are more convenient to use in some scenarios. For example, a certain type will only be used once. At this time, it is meaningless to define a Class. It can be solved by using anonymous types, but when used across projects , still need to pay attention to avoid
RuntimeBinderException
problems
Problem Description
For example, we have a class library project of type netstandard2.0
, which contains a method like this:
public static class StandardClass
{
public static dynamic Get()
{
return new { prop1 = "hello", prop2 = 12 };
}
}
Then add the following example code in a console project of type net6.0
using ClassLibrary1;
try
{
var test = StandardClass. Get();
var prop1 = test.prop1;
}
catch (Exception e)
{
Console. WriteLine(e);
throw;
}
At this time, when we try to run this console project to get the prop1
value, at this time, we will like to mention RuntimeBinderException
Solution
Because anonymous types default to Internal access level. This means that if the anonymous object is accessed through the Dynamic type in the same assembly, there is no problem, but if it crosses assemblies, RuntimeBinder will not be able to recognize this type, thus throwing a RuntimeBinderException exception. There are 2 ways to solve this problem:
- Modify the return type to strong type and cancel the anonymous type
- Add the InternalsVisibleTo attribute to expose the Internal level objects to the outside world (as shown in the figure below)
Related references
- C#‘dynamic’cannot access properties from anonymous types declared in another assembly