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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With