Search code examples
c#anonymous-typesanonymous-objects

Access anonymous object property from static class c#


I have a static class with multiple anonymous objects. Each object, has a different amount of properties, but each property is always a object of created class.

static public class Fields{
    static public Object FieldInfo1 = new {
        Customer = new FieldInformation("value1","value2")        
    } 

    static public Object FieldInfo2 = new {
        Customer = new FieldInformation("value1","value2"),
        Company = new FieldInformation("value1","value2"),        
    } 
}

I try to access Fields.FieldInfo1.Customer in second class (Program.cs, its a console application) but it isn't working, I only get Fields.FieldInfo1. What am I doing wrong?


Solution

  • You need to cast it to the type of the object. Because you have non (at compile time) cast as dynamic:

    var obj = Fields.FieldInfo1 as dynamic;
    var value = obj.Customer.Prop1; // "value1"
    

    But I don't see why you need to do it this way. This is not C# like, which is a strongly typed language. In my opinion you should rethink your design.

    This might give you a starting point for when it is right to use anonymous types