Friday, February 11, 2011

Can I use a the value of a variable as the name of property in c#?

How do all!

I want to be able to access a value in a class using the variable passed to a procedure.

e.g. _results.projection[2].Current.FundDC to become something like

_results.projection[2].termId.varName

where termId can be Current, Future or Percent

and varName can be a large list :)

Any suggestions?

Answers on a postcard please :)

  • You can do this with reflection using Type.GetProperty to get a PropertyInfo and then PropertyInfo.GetValue to get the value.

    Alternatively you could just switch on the name passed to you... both are somewhat icky, to be honest. Is the only way of receiving this information as a string? What's the bigger picture here?

    Ivor : The big picture here is that I am testing the values being returned by application that are contained in three rather large classes. Each class contains over 100 entries. I am using NUnit/NBehave to write the tests, basically defining a reusable syntax for other testers to specify their tests as well. e.g. I want to be able to say, If the value in Funds is not the expected one, the test fails. I am contructing it in such a way that tester can say, if I have this much and do this with it, I expect to have this amount, but if I don't I'm in trouble. Does that help?
    Jon Skeet : So this is *only* for test purposes, and not for your production code? I'm still not sure that passing property names in strings is a great idea... it's not refactoring-friendly, for example. Why can't the test code use the property in a normal way?
    Ivor : Oh and yes, I would prefer to use a string value, because I want the tester to be able to specify the test in as clear a language as possible. The reason the work is being done on the app, is cos the guy who wrote it was the only one who understood it and it was obfuscated all to hell and back. As he is no longer with us, we want to make the maint as easy as possible into the future, or at least until 2012...
    Ivor : Probably two good reason. 1. I am a newbie at C#, grew up with COBOL, Basic and self taught on other stuff. 2. I really want the testers to be able to code their tests as naturally as possible.
    Ivor : Oh yes one more thing, I did use a switch statement to reduce the line count from a couple of hundred to just over a hundred. Probably trying to be too smart now and want to make it a wee bit leaner...
    From Jon Skeet
  • Check out C# 4.0 (coming with VS2010), DynamicObject, and some more magic... read this blog post.

    Jon Skeet : C# 4 still wouldn't let you access it like that directly. It lets you bind compile-time names at execution-time, but it doesn't provide for names known only at execution-time. The DLR does, of course, but you'd have to do a bit more work.
    From Marcel J.

0 comments:

Post a Comment