Reputation: 735
Can we restrict Type property of a class to be a specific type?
Eg:
public interface IEntity { }
public class Entity : IEntity {}
public class NonEntity{}
class SampleControl {
public Type EntityType{get;set;}
}
assume that sampleControl is UI class (may be Control,Form,..) its Value of EntityType Property should only accept the value of typeof(Entity), but not the the typeof(NonEntity) how can we restrict the user to give the specific type at Deign time(bcause - Sample is a control or form we can set its property at design time) , is this posible in C# .net
How can we achive this using C# 3.0?
In my above class I need the Type property that to this must be one of the IEntity.
Upvotes: 5
Views: 1277
Reputation: 1064244
This might be a scenario where generics helps. Making the entire class generic is possible, but unfortunately the designer hates generics; don't do this, but:
class SampleControl<T> where T : IEntity { ... }
Now SampleControl<Entity>
works, and SampleControl<NonEntity>
doesn't.
Likewise, if it wasn't necessary at design time, you could have something like:
public Type EntityType {get;private set;}
public void SetEntityType<T>() where T : IEntity {
EntityType = typeof(T);
}
But this won't help with the designer. You're probably going to have to just 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;
}
}
Upvotes: 7
Reputation: 43217
You will have to create a class EntityType that inherits from System.Type.
public class EntityBaseType : System.Type
{ }
In your control..
public EntityBaseType EntityType{get;set;}
I don't recommend doing it this way.
Certainly you can do type-check in set statement.
class SampleControl {
public Type EntityType{get;
set
{
if(!value.Equals(typeof(Entity))
throw InvalidArgumentException();
//assign
}
}
}
Another option is that You can code against the type of Entity which is base class of all your entities in your case, If I have assumed correctly.
Upvotes: 1