0

I would like to determine if an object has a property specified. The value of the property can be null or any value, I just need the key to be there. My attempts so far have been using reflection, but this didn't help:

var t = typeof(MyObject);
PropertyInfo p = t.GetProperty("myProperty");
if (p == null)
{
    //property does not exist
    return false;
}
return true;

The problem here is that the value of the field is null, it returns false to me. I just want to be able to detect that the property is present. Thank you!

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Crista23
  • 3,203
  • 9
  • 47
  • 60
  • 5
    "The problem here is that the value of the field is null, it returns false to me" - no it won't. We can't really tell what's wrong, but the code you've got should be able to find a property fine. Please provide a [mcve] so we can reproduce the problem. Note that there's a difference between a field and a property - if you're actually trying to find a field, you should use `GetField`. – Jon Skeet Aug 04 '16 at 02:16
  • There is no value of the field because you don't even have an instance of `MyObject` – djv Aug 04 '16 at 02:20
  • Wow, 1st time I saw the legend of Stack Overflow respond in near real-time. It's 3:40 AM in London, what are you doing up so late @JonSkeet ? :) – Shiva Aug 04 '16 at 02:40
  • 1
    @Shiva: You're assuming I'm in London... I'm actually in Sydney for NDC Sydney :) – Jon Skeet Aug 04 '16 at 02:48
  • @JonSkeet Oh, ok. Glad to see you are "normal" like the rest of us :) – Shiva Aug 04 '16 at 06:23

0 Answers0