Type Restriction

c#

Solution

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;
    }
}

Problem

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.

Original source