3

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?

  • 1
    .net is a type safe language so your code needs to be type aware, you can't access a property on a variable of type `object` because object does not contain a property called `FieldInfo1`. Anonymous types are probably a bad idea here, what are you trying to do and why? – Charleh Aug 24 '16 at 07:46
  • It will never work since Fields.FieldInfo1 does not contain a Company property, only Customer. – Murray Foxcroft Aug 24 '16 at 07:47
  • @MurrayFoxcroft sorry my bad, I mean Customer – dev.Manderson Aug 24 '16 at 07:53

1 Answers1

4

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

Community
  • 1
  • 1
Gilad Green
  • 36,708
  • 7
  • 61
  • 95