AshOoO
AshOoO

Reputation: 1148

How to make a property or whatever to hold specific data .net

I have a class that hold some properties I need one of those properties to hold only some values

mean when I need to set a value I need to accept only value from an already defined enum

so when I use the class and on this property I could only use a value from enum

I just need to make sure that this property doesn't hold other values that I don't know in my enum

If there any solution other than using property it's ok :)

Upvotes: 1

Views: 148

Answers (4)

codymanix
codymanix

Reputation: 29490

Iam not sure if I understood you right, but don't you simply want this:

enum MyEnum 
{
  MyValue1,
  MyValue2
}    

class Test
{
  public MyEnum MyProperty { get; set; }
}

Another way would be to define the property as string or int (or whatever type your enum is based on) and check if the value is valid according to the enum:

string _value;

public string MyProperty 
{
  get{return _value;}
  set {
   if (Enum.GetName(typeof(MyEnum), _value)==null) 
      throw new ArgumentException("Unknown Value")
   _value=value;
   }
}

If you make your property integer based, you can use Enum.IsDefined() to check if the integer value is valid for that enum.

You may also want to consider usage of C#4.0 Code Contracts.

Upvotes: 2

Maged Samaan
Maged Samaan

Reputation: 1752

private int _field
public int Property
{
    get{ return _field;}
    set{
        if (Enum.GetValues(typeof(SomeEnum))).Contains(value))
            _field = value;
        else 
            _field = 0;
        }
}

Upvotes: 2

Gabriel
Gabriel

Reputation: 1443

Do you mean this:

public enum SomeEnum { item1, item2, item3 };
public class Myclass
{
    private SomeEnum enumItem;
    public SomeEnum EnumItem
    {
        get { return enumItem; }
        set { enumItem = value; }
    }
}

Upvotes: 1

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64923

There're some object validation libraries. I'd like to suggest you NHibernate Validator.

It could sound like it has a dependency with NHibernate, but it can be used standalone.

NH Validator and others are attribute-oriented, so you can place an attribute for your properties and then, by calling a validation engine, you'll be able to ensure some object property would hold some expected value or any other validation rule.

Learn more here:

EDIT: I forgot to mention NH Validator has an extensibility API so you can implement your own validation rules, fact that should make sense for you!

Upvotes: 0

Related Questions