Type restriction

Is it possible to restrict the Type property of a class to a specific type?

For instance:

public interface IEntity { } public class Entity : IEntity {} public class NonEntity{} class SampleControl { public Type EntityType{get;set;} } 

suppose sampleControl is a UI class (maybe Control, Form, ..). The Value EntityType Property should only accept typeof (Entity), but not type (NonEntity), how can we restrict the user to specify a specific type in Deign time (bcause - Sample is a control or form that we can set for its property in development time), it is possible in C # .net

How can we achieve this with C # 3.0?

In my class above, I need a Type property, which should be one of IEntity.

+4
source share
2 answers

This may be a scenario in which generics help. It is possible to create a general class, but, unfortunately, the designer hates generics; do not do this, but:

 class SampleControl<T> where T : IEntity { ... } 

SampleControl<Entity> works, but SampleControl<NonEntity> does not.

Similarly, if this was not necessary during development, you could have something like:

 public Type EntityType {get;private set;} public void SetEntityType<T>() where T : IEntity { EntityType = typeof(T); } 

But this does not help the designer. You may just have to use validation:

 private Type entityType; public Type EntityType { get {return entityType;} set { if(!typeof(IEntity).IsAssignableFrom(value)) { throw new ArgumentException("EntityType must implement IEntity"); } entityType = value; } } 
+6
source

You will need to create an EntityType class that inherits from System.Type.

 public class EntityBaseType : System.Type { } 

In your control ..

 public EntityBaseType EntityType{get;set;} 

I do not recommend doing it this way.

Of course, you can do type checking in the set statement.

 class SampleControl { public Type EntityType{get; set { if(!value.Equals(typeof(Entity)) throw InvalidArgumentException(); //assign } } } 

Another option is that you can code the Entity type, which is the base class of all your entities in your case, if I assumed correctly.

+1
source

All Articles