0

I have this basic class with one custom Attribute

public class Foo
{
    [MyAttribute]
    public DateTime CurrentDate {get;set;}
}

I'm using reflection to see if CurrentDate has a MyAttribute on it.

I create a new instance of Foo:

var foo = new Foo();

I reflect on foo:

foo.GetType().GetProperty("CurrentDate").GetCustomAttributes(true);

this gives me my custom attributes.

However, if I reflect like this:

foo.CurrentDate.GetType().GetCustomAttributes(true);

it returns what seems to be native attributes and mine is not in there.

So my question is, why is it doing that?

dbc
  • 104,963
  • 20
  • 228
  • 340
JohanP
  • 5,252
  • 2
  • 24
  • 34

1 Answers1

3

foo.CurrentDate.GetType() will return typeof(DateTime). That's because foo.CurrentDate is declared as a DateTime. GetType() returns information about the type of the value you give it, not information about the property that the value came from.

Do you mean to do something like foo.GetType().GetProperty(nameof(foo.CurrentDate)).GetCustomAttributes()?

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • The use case is I have a custom JsonConverter that returns `true` in `CanConvert(Type objectType)` if `objectType == typeOf(DateTime)` and that `objectType` has a custom `Attribute` – JohanP May 07 '18 at 02:20
  • @JohanP: JsonConverters fulfill a different use case from the one you mention. You can do what you're talking about using a custom Contract Resolver that watches for custom attributes on properties. See https://stackoverflow.com/q/41088492/120955 for a description of the difference between the two. – StriplingWarrior May 07 '18 at 02:58
  • @JohanP - *The use case is I have a custom JsonConverter* -- in that case this may be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Since this answers the question you asked, I'd go ahead and ask a new question that describes your real problem. – dbc May 07 '18 at 03:08
  • @StriplingWarrior It seems I need a contract resolver for attributes then. I have the JsonConverter because I do need custom deserialization for DateTime so I thought I could get away with just having the converter. – JohanP May 07 '18 at 03:21
  • 1
    @JohanP - sounds like you might want something like this then: [Access custom attributes of .NET class inside custom json converter](https://stackoverflow.com/q/49991050/3744182). – dbc May 07 '18 at 03:32