bizzehdee
bizzehdee

Reputation: 21023

Inherit from generic type as interface

I am attempting to do something similar to:

public interface IView<T> : T where T : class 
{ 
    T SomeParam {get;} 
}

So that i can later do

public class SomeView : IView<ISomeView> 
{
}

Is it possible to specify inheritance using generics in this way or do i have to go the long way round and explicitly specify both interfaces when defining the class and do:

public interface IView<T> 
{ 
    T SomeParam {get;} 
}
public class SomeView : IView<ISomeView>, ISomeView 
{
}

Upvotes: 7

Views: 208

Answers (2)

nmclean
nmclean

Reputation: 7734

This isn't possible, but your goal may be achievable with conversion operators. It seems that what you're trying to do is make it possible to pass an IView<T> as the T object which it contains. You could write a base class like this:

public abstract class ViewBase<T> {
    public abstract T SomeParam { get; }

    public static implicit operator T(ViewBase<T> view) {
        return view.SomeParam;
    }
}

Then, if you define a class like:

public class SomeView : ViewBase<ISomeView> { }

It can be accepted anywhere an ISomeView is expected:

ISomeView view = new SomeView();

Upvotes: 2

Guish
Guish

Reputation: 5160

Short answer: It is not possible. See this post

An Interface can't derive from a class. However nothing prevent you from doing this:

public interface ISomeView
{
}

public interface IView<out T> where T:class 
{
    T SomeParam { get; }
}

public class SomeView:IView<ISomeView>
{
    public ISomeView SomeParam { get; set; }
}    

Edit:

If you don't want to implement the T SomeParam { get; } each time you need to have an implementation, Does this would work?

public interface ISomeView
{
}

public abstract class BaseView<T> where T : class
{
    public T SomeParam { get; set; }
}

public class SomeView : BaseView<ISomeView>{
}

In both case this would work:

public class main
{
    public class OneOfThoseView : ISomeView
    {
    }

    public main()
    {
        OneOfThoseView oneOfThose = new OneOfThoseView();
        SomeView x = new SomeView();
        x.SomeParam = oneOfThose;
    }

}

Edit 2: Not exactly what you want to do but this would force your SomeView class to return a BaseView<SomeView> class

public interface ISomeView
{
}

public abstract class BaseView<T> where T : BaseView<T>
{
    public T SomeParam { get; set; }
}

public class SomeView : BaseView<SomeView>
{
}

Now only this would work.

public main()
{
    SomeView y= new SomeView ();
    SomeView x = new SomeView();
    x.SomeParam = y;
}

Upvotes: 0

Related Questions