title: Access child class object in base abstract class method using Generics
body: <p>My Existing class structure.</p>
  
  <p>AbstractTradeBaseClass - > AbstractTradeClass -> ConcreteTradeClass.</p>
  
  <p>Am using DataAnnotations and IDataErrorInfo to validate my Model in my WPF application.
  I have moved the IDataErrorInfo methods to the AbstractTradeBaseClass so that i can be used by all the classes that inherit from the base class.</p>
  
  <p>This is done by reading the attributes dynamically using Linq.</p>
  
  <p><strong>AbstractTradeBaseClass.cs</strong></p>
  
  <pre><code> public abstract class TradeBaseModel&lt;T&gt; : INotifyPropertyChanged, IDataErrorInfo
  {
      #region INotifyPropertyChanged Members
  
      public event PropertyChangedEventHandler PropertyChanged;
  
      public void OnPropertyChanged( string propertyName )
      {
          if ( PropertyChanged != null )
          {
              PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
          }
      }
  
      #endregion
  
      # region Getter/Validator members for Annotations
      private static readonly Dictionary&lt;string, Func&lt;T, object&gt;&gt;
          propertyGetters = typeof( T ).GetProperties()
                            .Where( p =&gt; GetValidations( p ).Length != 0 )
                            .ToDictionary( p =&gt; p.Name, p =&gt; GetValueGetter( p ) );
  
      private static readonly Dictionary&lt;string, ValidationAttribute[]&gt; validators =
          typeof( T ).GetProperties()
          .Where( p =&gt; GetValidations( p ).Length != 0 )
          .ToDictionary( p =&gt; p.Name, p =&gt; GetValidations( p ) );
  
      private static ValidationAttribute[] GetValidations( PropertyInfo property )
      {
          return ( ValidationAttribute[] )property.GetCustomAttributes( typeof( ValidationAttribute ), true );
      }
  
      private static Func&lt;T, object&gt; GetValueGetter( PropertyInfo property )
      {
          var instance = Expression.Parameter( typeof( T ), "i" );
          var cast = Expression.TypeAs( Expression.Property( instance, property ), typeof( object ) );
          return ( Func&lt;T, object&gt; )Expression.Lambda( cast, instance ).Compile();
      }
      # endregion
  
      #region IDataErrorInfo Members
  
      public string Error
      {
          get
          {
              var errors = from i in validators
                           from v in i.Value
                           where !v.IsValid( propertyGetters[i.Key]( **( T )ModelToValidate()** ) )
                           select v.ErrorMessage;
              return string.Join( Environment.NewLine, errors.ToArray() );
          }
      }
  
      protected Dictionary&lt;string, string&gt; _errors = new Dictionary&lt;string, string&gt;();
      public IDictionary&lt;string, string&gt; Errors
      {
          get { return _errors; }
      }
  
      public string this[string columnName]
      {
          get
          {
              string errorMessage = string.Empty;
              this.Errors.Remove( columnName );
  
              //string errorMessage = string.Empty;
              //switch(columnName)
              //{
              //    case "Range":
              //        if ( Range &gt; 15 )
              //        {
              //            errorMessage = "Out of Range, should be less than 15";
              //        }
              //        break;
              //}
  
              //return errorMessage;
  
              if ( propertyGetters.ContainsKey( columnName ) )
              {
                  var value = propertyGetters[columnName]( **( T )ModelToValidate()** );
                  var errors = validators[columnName].Where( v =&gt; !v.IsValid( value ) )
                      .Select( v =&gt; v.ErrorMessage ).ToArray();
  
                  string error = string.Join( Environment.NewLine, errors );
                  this.OnPropertyChanged( "Error" );
  
                  if ( !string.IsNullOrEmpty( error ) )
                  {
                      this.Errors.Add( columnName, error );
                  }
  
                  return error;
              }
  
              return string.Empty;
  
          }
      }
  
      public abstract object ModelToValidate(); -- ***Gets the child object here, overridden in the child class to return the child object, -- is there a better way to do this using Generics ??***
  
      #endregion
  }
  </code></pre>
  
  <p><strong>AbstractTradeClass</strong></p>
  
  <pre><code> public abstract class TradeClassBase&lt;T&gt; : TradeBaseModel&lt;T&gt;
  {
      public string EmptyString
      {
          get { return string.Empty; }
      }
  }
  </code></pre>
  
  <p><strong>ConcreteTradeClass</strong></p>
  
  <pre><code>public class CashFlowTrade : TradeClassBase&lt;CashFlowTrade&gt;
  {
      private int range;
      [RangeAttribute(0,10, ErrorMessage="Out of Range, Range should be less than 15")]
      public int Range
      {
          get
          {
              return this.range;
          }
          set
          {
              if ( this.range != value )
              {
                  this.range = value;
                  this.OnPropertyChanged( "Range" );
              }
          }
      }
  
      public override object ModelToValidate()
      {
          return this;
      }
  
  }
  </code></pre>
  
  <p>Is there a better way of doing this instead of using an abstract method and overriding it in the child class to pass the actual child class object and casting it to type T.
  Usage indicated in above code in BOLD.</p>
  
  <p>If there is a way I can pass the child class object down to the base class, i can then use the actual child class object itself to perform the validation operations.</p>
  
  <hr>
  
  <p><strong>Updated Working Code</strong>
  Constraint T with class and use the type casting operator as below.</p>
  
  <pre><code>    public abstract class TradeBaseModel&lt;T&gt; : INotifyPropertyChanged, IDataErrorInfo
      where T : class
  </code></pre>
  
  <p>replace call to the abstract method with the type cast.</p>
  
  <pre><code> if ( propertyGetters.ContainsKey( columnName ) )
              {
                  var value = propertyGetters[columnName]( this as T );
  </code></pre>