title: Get attribute of derived C# class passed as base class to generic method
body: <p>I'm trying to determine the value of an attribute on a derived class, when it's been passed into a method through a base class parameter.</p>
  
  <p>For example, complete code sample below: </p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          DerivedClass DC = new DerivedClass();
          ProcessMessage(DC);
      }
  
      private static void ProcessMessage(BaseClass baseClass)
      {
          Console.WriteLine(GetTargetSystemFromAttribute(baseClass));
          Console.ReadLine();
      }
  
      private static string GetTargetSystemFromAttribute&lt;T&gt;(T msg)
      {
          TargetSystemAttribute TSAttribute = (TargetSystemAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(TargetSystemAttribute));
  
          if (TSAttribute == null)
              throw new Exception(string.Format("Message type {0} has no TargetSystem attribute and/or the TargetSystemType property was not set.", typeof(T).ToString()));
  
          return TSAttribute.TargetSystemType;
      }
  }
  
  public class BaseClass
  {}
  
  [TargetSystem(TargetSystemType="OPSYS")]
  public class DerivedClass : BaseClass
  {}
  
  [AttributeUsage(AttributeTargets.Class)]
  public sealed class TargetSystemAttribute : Attribute
  {
      public string TargetSystemType { get; set; }
  }
  </code></pre>
  
  <p>So, in the above example, I had intended that the generic <em>GetTargetSystemFromAttribute</em> method returns "OPSYS". </p>
  
  <p>But, because the DerivedClass instance has been passed to <em>ProcessMessage</em> as the base class, <em>Attribute.GetAttribute</em> is not finding anything because it's treating the DerivedClass as the Base Class, which does not have the attribute or the value I'm interested in.</p>
  
  <p>In the real-world there are dozens of Derived Classes, so I was hoping to avoid lots of:</p>
  
  <pre><code>if (baseClass is DerivedClass)
  </code></pre>
  
  <p>...which is suggested as the answer in the question <a href="https://stackoverflow.com/questions/7587667/how-to-access-the-properties-of-an-instance-of-a-derived-class-which-is-passed-a">How to access the properties of an instance of a derived class which is passed as a parameter in the form of the base class</a> (which relates to a similar issue, but with properties). I was hoping because I'm interested in Attributes there's a nicer way of doing it, especially as I have dozens of derived classes.</p>
  
  <p>So, here's the question. Is there any way I can obtain the TargetSystemType value of the TargetSystem Attribute on my derived classes in a low-maintenance way? </p>