leifre
leifre

Reputation: 33

C# Pass a type into method to be evaluated in an "is" statement?

I want to do something like the code listed below. Basically, I want to be able to create an object but at the same time optionally put on an interface requirement

public UserControl CreateObject(string objectName, Type InterfaceRequirement)
{
     ///// create object code abbreviated here
     UserControl NewControl = createcontrol(objectName);

     if (InterfaceRequirement == null || NewControl is InterfaceRequirement)
          return NewControl;
     else
          throw new SystemException("Requested object does not implement required interface");

}

The above code does not compile due to issues with InterfaceRequirement

now, I know i can do this with generics:

public UserControl CreateObject<T>(string objectName)
{
    ///// create object code abbreviated here
     UserControl NewControl = createcontrol(objectName);

     if (NewControl is T)
          return NewControl;
     else
          throw new SystemException("Requested object does not implement required interface");
}

but with the generics, the interface requirement is not optional. The first code example where I am passing type as a parameter does not compile and I cant see to get the syntax right. Does anyone know a way to do this without generics so i can make it optional?

Upvotes: 3

Views: 1191

Answers (2)

Mario The Spoon
Mario The Spoon

Reputation: 4859

You have to use a constraint for T:

public UserControl CreateObject<T>(string objectName) where T : class
{
    ///// create object code abbreviated here
     UserControl NewControl = createcontrol(objectName);

     if (NewControl is T)
          return NewControl;
     else
          throw new SystemException("Requested object does not implement required interface");
}

hth Mario

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062580

You can check typeof(InterfaceRequirement).IsAssignableFrom(theType) ?

Otherwise, maybe theType.GetInterfaces() and look for it.

(where Type theType = NewControl.GetType();)

Upvotes: 5

Related Questions