What happens in this self-binding inheritance code?

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

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

In my AppBase class of type T implements the IApp interface, where T implements ???

Can someone explain the last part?

+8
inheritance c # oop interface
source share
1 answer

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

This is usually done as an attempt to bypass the type system and provide access to the implementation type in 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> { } 

Then you can write code, for example:

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

Type information for AppBaseFoo will be printed. However, this is not reliable - for example, subclasses β€œbreak” it. Addendum:

 public class AppBaseBar : AppBaseFoo {} 

And then I write:

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

Invokes printing of the same AppBaseFoo information.

+7
source share

All Articles