Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Restriction

Tags:

c#

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.

like image 914
dinesh Avatar asked Jan 08 '10 06:01

dinesh


People also ask

What is Type 1 and Type 2 restriction enzymes?

Today, scientists recognize three categories of restriction enzymes: type I, which recognize specific DNA sequences but make their cut at seemingly random sites that can be as far as 1,000 base pairs away from the recognition site; type II, which recognize and cut directly within the recognition site; and type III, ...

What is a Type 1 restriction enzyme?

Type I restriction enzymes (REases) are large pentameric proteins with separate restriction (R), methylation (M) and DNA sequence-recognition (S) subunits.


1 Answers

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;
    }
}
like image 134
Marc Gravell Avatar answered Oct 08 '22 07:10

Marc Gravell