0

I would like to add 'Price' on class B as reference to 'Price' on class A. I want to avoid the repetition of the declaration of a property:

public class A{

    // ... stuff 

    [Required]
    [Display(Name = "Price (Euros)")]
    [Range(1, 1000)]
    public float Price { get; set; }

    // ... more stuff 
}

public class B{

    // ... stuff 

    [Required]
    [Display(Name = "Price (Euros)")]
    [Range(1, 1000)]
    public float Price { get; set; }

    // ... more stuff 
}

So, for example, if in class A i want to change the range i don't want to have to remember which other classes have the same property.

2 Answers 2

1

What about inheritance?

public class A{

    // ... stuff 
    [Required]
    [Display(Name = "Price (Euros)")]
    [Range(1, 1000)]
    public float Price { get; set; }

    // ... more stuff 
}

public class B : A{

    // ... stuff 

    // ... more stuff 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Might want to mention interface in your answer too :)
0

you can define a constant for this

public static class Constants
{
    public const int PriceMin = 1;
    public const int PriceMax = 1000;
}

....


[Range(Constants.PriceMin, Constants.PriceMax)]

Or you can inherit the Range attribute like

public class MyRangeAttribute : RangeAttribute
{
    public MyRangeAttribute()
       :base(1, 1000)
    {
    }
}

then you can just do

[MyRange]

and when you want to change the value just change it inside MyRangeAttribute.cs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.