title: Extension Method for Custom Attributes
body: <p>I am working an ASP.net MVC4 website and have model &amp; view model layer. <em>Because of certain reasons</em> I have different names for few properties in Model and ViewModel</p>
  
  <p><strong>Model</strong></p>
  
  <pre><code>public partial class Project
  {
     public string Desc {get; set;}
  }
  </code></pre>
  
  <p><strong>View Model</strong></p>
  
  <pre><code>public class ProjectViewModel
  {
     public string Description { get; set; }
  }
  </code></pre>
  
  <p>Now at model layer, I need to use ViewModel name of a property if it is different. I was thinking of creating a custom attribute so that I can have something like this in models:</p>
  
  <pre><code>public partial class Project
  {
      [ViewModelPropertyName("Description")]
      public string Desc {get;set;}
  }
  </code></pre>
  
  <p>and use it at model layer as </p>
  
  <pre><code>string.Format("ViewModel Property Name is {0}", this.Desc.ViewModelPropertyName())
  </code></pre>
  
  <p>I want this to generic so that if there is no <code>ViewModelPropertyName</code> attribute on a property then it should return the same property name i.e. if <code>Desc</code> property has no attribute then it should return <code>"Desc"</code> only.</p>
  
  <p><strong>Here is what I tried</strong></p>
  
  <pre><code>public class ViewModelPropertyNameAttribute : System.Attribute
  {
      #region Fields
  
      string viewModelPropertyName;
  
      #endregion
  
      #region Properties
  
      public string GetViewModelPropertyName()
      {
          return viewModelPropertyName;
      }
  
      #endregion
  
      #region Constructor
  
      public ViewModelPropertyNameAttribute(string propertyName)
      {
          this.viewModelPropertyName = propertyName;
      }
  
      #endregion
  }
  </code></pre>
  
  <p>Need help for how to access custom attribute</p>
  
  <p><strong>Current state</strong></p>
  
  <pre><code>    public static class ModelExtensionMethods
  {
      public static string ViewModelPropertyName(this Object obj)
      {
          // ERROR: Cannot convert from 'object' to 'System.Reflect.Assembly'
          System.Attribute[] attrs = System.Attribute.GetCustomAttributes(obj);
  
          foreach (System.Attribute attr in attrs)
          {
              if (attr is ViewModelPropertyNameAttribute)
              {
                  return ((ViewModelPropertyNameAttribute)attr).GetViewModelPropertyName();
              }
          }
  
          return string.Empty;
      }
  }
  </code></pre>
  
  <p>But this has compile time error: </p>