Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using same type with a class definition where keyword

Tags:

c#

generics

I have seen this kind of definition in a library I'm using. I got crazy about the where TObjectType: CSObject. It is obvious that It seems I can use the same time in the constraint because it works and compiles but what does this really mean?

public class CSList<TObjectType>: CSList, IList<TObjectType>, IList
    where TObjectType: CSObject<TObjectType>
like image 976
Notbad Avatar asked Mar 06 '26 21:03

Notbad


1 Answers

It means that the TObjectType here must inherit from CSList<TObjectType>.

Usually you use this construct to get typed methods and properties on the base class that adjust to the actual derived classes you intend to use.

To declare such a derived class:

public class SomeDerivedClass : CSList<SomeDerivedClass>

Example:

public class Base<T>
{
    public T[] Values { get; set; }
}

public TestCollection : Base<TestCollection>
{
    // here, Values inherited from Base will be:
    // public TestCollection[] Values { get; set; }
}

public OtherCollection : Base<OtherCollection>
{
    // here, Values inherited from Base will be:
    // public OtherCollection[] Values { get; set; }
}
like image 73
Lasse V. Karlsen Avatar answered Mar 08 '26 09:03

Lasse V. Karlsen