6

I have this code:

object test = new {a = "3", b = "4"};
Console.WriteLine(test); //I put a breakpoint here

How can I access a property of test object? When I put a breakpoint, visual studio can see the variables of this object... Why can't I? I really need to access those.

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
ojek
  • 9,680
  • 21
  • 71
  • 110

2 Answers2

6

If you want the compiler support, then you should use a var and not object. It should recognize that you have an object with properties a and b. You are downcasting to an object in the above code, so the compiler will only have object properties

var test = new {a = "3", b = "4"};
Console.WriteLine(test.a); //I put a breakpoint here

If you cannot use var for whatever reason, then you can look into dynamic or this grotty hack for passing anonymous types from Skeet

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
  • Okay, but I cannot use `var` here, because in reality, `test` is declared inside of my class, and it needs to be an object. – ojek Dec 06 '13 at 15:23
  • 2
    Then perhaps you should not be using an anonymous type. – Emil Lundin Dec 06 '13 at 15:25
  • It doesn't matter what the type is, as soon as you assign something to an object via `object test = new AnyClass();` you ONLY have access to the methods available to System.Object. Unless of course you cast the `object` instance back to a particular type but you can't do that with anonymous types – nvuono Dec 06 '13 at 15:26
  • @ojek Yah, you should probably just create the type then. Anonymous types are not built to be passed around. I did update my answer to give you alternatives, though – Justin Pihony Dec 06 '13 at 15:28
2

If you cannot use static typing for your anonymous class, you can use dynamic, like this:

static object MakeAnonymous() {
    return new {a = "3", b = "4"};
}
static void Main(string[] args) {
    dynamic test = MakeAnonymous();
    Console.WriteLine("{0} {1}", test.a, test.b);
}

The downside to this approach is that the compiler is not going to help you detect situations when a property is not defined. For example, you could write this

Console.WriteLine("{0} {1}", test.abc, test.xyz); // <<== Runtime error

and it would compile, but it would crash at runtime.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Well, the thing is, I need the access to those variables, only to check if `test.c` exists... So I suppose this won't help me here? Anyway, nice solution, thank you! – ojek Dec 06 '13 at 15:28
  • @ojek You can use [this answer](http://stackoverflow.com/a/9956981/335858) then, it will help you check if a property exists. – Sergey Kalinichenko Dec 06 '13 at 15:32