1

I have the following classes:

[Msg(Value = "YaaY")]
public class PersonContainer<T>  where T : new()
{
   ...
}


public class HappyPerson
{
   ...
}

[Msg(Value = "NaaY")]
public class SadPerson
{
   ...
}

Using the following method I can get the attributes of the "PersonContainer":

public void GetMsgVals(object personContainer)
{
    var info = personContainer.GetType();

    var attributes = (MsgAttribute[])info.GetCustomAttributes(typeof(MsgAttribute), false);
    var vals= attributes.Select(a => a.Value).ToArray();        
}

However I only get the attribute of "PersonContainer" (which is "YaaY") how can I get the atrributes of T (HappyPerson [if any] or SadPerson["NaaY"]) at runtime without knowing what T is?

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
MaYaN
  • 6,683
  • 12
  • 57
  • 109
  • possible duplicate of [Reflection - Getting the generic parameters from a System.Type instance](http://stackoverflow.com/questions/293905/reflection-getting-the-generic-parameters-from-a-system-type-instance) – CodeCaster Mar 17 '14 at 16:09

2 Answers2

5

You need to get generic argument's type and then it's attributes:

var info = personContainer.GetType();

if (info.IsGenericType)
{
     var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
                      .GetCustomAttributes(typeof(MsgAttribute), false);
}

Edit: GetGenericArguments returns a Type array so my first call to GetType was unnecessary and I remove it.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

You need to loop through the generic type arguments to get their attributes:

var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
    // gta.GetCustomAttributes(...)
}
Jason Goemaat
  • 28,692
  • 15
  • 86
  • 113