Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats happening in this Self referencing inheritance code?

I have this code written by another programmer and I cant get my head around it

public abstract class AppBase<T> : IApp where T : AppBase<T>, new()
{
    //
}

From my understanding the AppBase class of type T implements the interface IApp where T implements ???

Can some one explain the last part?

like image 218
Abhi.Net Avatar asked Mar 29 '16 22:03

Abhi.Net


1 Answers

The constraint on T in this case means that T must implement AppBase<T> and have a default constructor. Effectively, you need to pass yourself as the type.

This is usually done as an attempt to workaround the type system and provide access to the implementing type within the base class via typeof(T). For example, given:

public interface IApp {}

public abstract class AppBase<T> : IApp where T : AppBase<T>, new()
{
    public void Print()
    {
        Console.WriteLine(typeof(T).ToString());
    }
}

public class AppBaseFoo : AppBase<AppBaseFoo>
{
}

You can then write code like:

var foo = new AppBaseFoo();
foo.Print();

Which will print the type information for AppBaseFoo. However, this isn't foolproof - for example, subclassing "breaks" this. Adding:

public class AppBaseBar : AppBaseFoo {}

And then writing:

var bar = new AppBaseFoo();
bar.Print();

Causes the same AppBaseFoo information to be printed.

like image 101
Reed Copsey Avatar answered Oct 15 '22 02:10

Reed Copsey