Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8214923
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T11:36:59+00:00 2026-06-07T11:36:59+00:00

My Existing class structure. AbstractTradeBaseClass – > AbstractTradeClass -> ConcreteTradeClass. Am using DataAnnotations and

  • 0

My Existing class structure.

AbstractTradeBaseClass – > AbstractTradeClass -> ConcreteTradeClass.

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.

This is done by reading the attributes dynamically using Linq.

AbstractTradeBaseClass.cs

 public abstract class TradeBaseModel<T> : 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<string, Func<T, object>>
        propertyGetters = typeof( T ).GetProperties()
                          .Where( p => GetValidations( p ).Length != 0 )
                          .ToDictionary( p => p.Name, p => GetValueGetter( p ) );

    private static readonly Dictionary<string, ValidationAttribute[]> validators =
        typeof( T ).GetProperties()
        .Where( p => GetValidations( p ).Length != 0 )
        .ToDictionary( p => p.Name, p => GetValidations( p ) );

    private static ValidationAttribute[] GetValidations( PropertyInfo property )
    {
        return ( ValidationAttribute[] )property.GetCustomAttributes( typeof( ValidationAttribute ), true );
    }

    private static Func<T, object> GetValueGetter( PropertyInfo property )
    {
        var instance = Expression.Parameter( typeof( T ), "i" );
        var cast = Expression.TypeAs( Expression.Property( instance, property ), typeof( object ) );
        return ( Func<T, object> )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<string, string> _errors = new Dictionary<string, string>();
    public IDictionary<string, string> 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 > 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 => !v.IsValid( value ) )
                    .Select( v => 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
}

AbstractTradeClass

 public abstract class TradeClassBase<T> : TradeBaseModel<T>
{
    public string EmptyString
    {
        get { return string.Empty; }
    }
}

ConcreteTradeClass

public class CashFlowTrade : TradeClassBase<CashFlowTrade>
{
    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;
    }

}

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.

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.


Updated Working Code
Constraint T with class and use the type casting operator as below.

    public abstract class TradeBaseModel<T> : INotifyPropertyChanged, IDataErrorInfo
    where T : class

replace call to the abstract method with the type cast.

 if ( propertyGetters.ContainsKey( columnName ) )
            {
                var value = propertyGetters[columnName]( this as T );
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T11:37:00+00:00Added an answer on June 7, 2026 at 11:37 am

    yes… directly use this. Even in an abstract class you have access to this reference. The only place where you can’t use it is in static methods.

    EDIT:

    To enforce type checking, you could add a constraint on T :

    public abstract class TradeBaseModel<T> : INotifyPropertyChanged, IDataErrorInfo where T: TradeBaseModel<T>
    

    EDIT 2:

    To sum-up Kans’ comments below, this is not enough : this conversion enables an implicit type conversion from T to base type while a conversion from base type to T is required.
    The only solution seems to be a cast into using T the as operator in the above code, and for this, T has to be a class (which is OK if constraint above is added).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following structure: class FeatureType(models.Model): type = models.CharField(max_length=20) def __unicode__(self): return self.type
I have a problem while adding a new class in my existing structure. I
I would like to enhance existing class using instance_eval. There original definition contains validation,
I have the following existing classes: class Gaussian { public: virtual Vector get_mean() =
I'm currently struggling to understand how I should organize/structure a class which I have
I have something that looks like the following document structure: public class Document {
I have an existing database structure created outside or Rails. I've edited one of
I have a certain class structure in my app, that currently utilizes django for
I have a class like this: [Serializable] public class Structure { #region Constants and
I have a ASP.NET MVC 3 application, using Entity Framework 4 to handle Data

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.