Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 736
dev.Manderson Avatar asked Dec 05 '25 07:12

dev.Manderson


1 Answers

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

like image 92
Gilad Green Avatar answered Dec 08 '25 07:12

Gilad Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!