public class BinarySearchTree
where T : IComparable
{
public static BinarySearchTree InitializeSampleCharacterBST()
{
v
As Marc said, it's sometimes useful to overload the type to have a non-generic class - and it would be in this case.
As for why it's necessary, suppose that the static method were actually implemented as:
public static BinarySearchTree InitializeSampleCharacterBST()
{
Console.WriteLine(typeof(T));
return null;
}
That would be perfectly valid code - it's in a generic type, so it should have access to the type parameter... but you're trying to call the method without providing a generic type parameter, so it couldn't possibly work. In your case you happen to not use T anywhere within the method, but that's a coincidence. It's a bit like having an instance method which doesn't use this: you're not using the instance, but you still can't call it as if it were a static method.
As well as having separate static classes, another design technique which can be useful is to split your type into non-generic and generic pieces. That way, in cases where it can be awkward to work out which exact type you have, you don't actually need to know it in order to call some of the members. For example, a collection interface hierarchy might have:
public interface ISomeCollection
{
int Count { get; }
void Clear();
}
public interface ISomeCollection : ISomeCollection
{
void Add(T item);
}
I've used this technique myself for my Protocol Buffers port to C#, and it's proved very useful (if somewhat complicated).