where (generic type constraint) (C# Reference)
The relevant text from the document cited above is:
For example, you can declare a generic class, MyGenericClass, such that the type parameter T implements the IComparable<T> interface:
Here is MyGenericClass
, copied verbatim from documentation cited above:
public class AGenericClass<T> where T : IComparable<T> { }
Here is a small console app shows my attempts to create the instance:
class Program
{
static void Main(string[] args)
{
AGenericClass<MyComparable<string>> stringComparer = new AGenericClass<MyComparable<string>>(); // does not build
AGenericClass<MyStringComparable> stringComparer2 = new AGenericClass<MyStringComparable>(); // does not build
}
}
public class MyStringComparable : IComparable<string>
{
public int CompareTo(string other) => throw new NotImplementedException();
}
public class MyComparable<T> : IComparable<T>
{
public int CompareTo(T other) => throw new NotImplementedException();
}
// verbatim from documentation cited above
public class AGenericClass<T> where T : IComparable<T> { }
For clarity my question is "How do I create an instance of AGenericClass
as it is defined in the cited C# documentation". Please note my question relates to the specific example cited above, not other related questions such as this one and this one.
I'm obviously very confused on how type parameters work. I hope by answering this question I will become enlightened as it closely resembles the business problem I'm trying to solve.
Also my question has nothing to do with IComparable<T>
or comparing objects - that just happens to be the interface in the example code.
Edit: Additional code provided based on reply from @CoolBots. This code provides a more realistic example and shows an interface that is intended to operate on a single object:
public class Program2
{
public Program2()
{
Selector<Selectable<string>, string> stringSelector = new Selector<Selectable<string>, string>();
}
}
public interface ISelectable<T>
{
bool IsSelected { get; set; }
T Item { get; set; }
}
public class Selectable<T> : ISelectable<T>
{
public bool IsSelected { get; set; }
public T Item { get; set; }
}
public class Selector<T, TData> where T:ISelectable<TData>
{
}