joe
joe

Reputation: 8654

Return a Type of a specific interface?

Suppose there's a interface IView where several implementations exist.
Now there are multiple other classes that has the following property:

public Type ViewType { get; }

I want to ensure that the returned Type is of type IView.
Is there any way to achieve this? (like where returnvalue: IView)

Please note that the property does not return a instance of IView.
If so there would be this way:
public T GetView<T>() where T: IView { }

The other way would be to check the returned type at any place where the property is called - but that's a lot of code for the same check.

Upvotes: 0

Views: 123

Answers (2)

faby
faby

Reputation: 7556

try in this way

bool ImplementsIView(object t)
{
   return typeof(IView).IsAssignableFrom(typeof(t.GetType()));
}

update

 bool ImplementsIView(Type t)
    {
       return typeof(IView).IsAssignableFrom(typeof(t));
    }

Upvotes: 0

kidshaw
kidshaw

Reputation: 3451

Both your solutions immediately sprang to mind.

Perhaps you could alleviate the repetition of checking the returned type by adding a helper method:

public bool ViewImplementsIView()
{
    return typeof(this.ViewType).GetInterfaces().Contains(typeof(IView));
}

That encapsulates the test into your class so you've reduced the amount of validation needed elsewhere - potentially, you could even throw an exception on your getter if this returns false.

Upvotes: 1

Related Questions