Home >Backend Development >C++ >How Can I Cast an Anonymous Type in C# to Access Its Properties?
Cast Anonymous Type to Access Properties
Casting an anonymous type back to its original type can be problematic when accessing its properties. To solve this, one can utilize a trick to infer the correct type.
Tricking the Compiler
The method Cast
private static T Cast<T>(T typeHolder, Object x) { // typeHolder above is just for compiler magic // to infer the type to cast x to return (T)x; }
Usage:
var a = new { Id = 1, Name = "Bob" }; TestMethod(a); ... private static void TestMethod(Object x) { // This is a dummy value, just to get 'a' to be of the right type var a = new { Id = 0, Name = "" }; a = Cast(a, x); Console.Out.WriteLine(a.Id + ": " + a.Name); }
Alternative Casting Method
An alternative method is to create an extension method CastTo
private static T CastTo<T>(this Object value, T targetType) { // targetType above is just for compiler magic // to infer the type to cast value to return (T)value; }
Usage:
var value = x.CastTo(a);
Recommendation
While these techniques allow for casting anonymous types, it is recommended to use real types for clarity and ease of use.
The above is the detailed content of How Can I Cast an Anonymous Type in C# to Access Its Properties?. For more information, please follow other related articles on the PHP Chinese website!