Question: How do I communicate which types my generic method can be used with?
I want to use generics to create methods that are compatible with three or four different types (rather than all types). Here's a contrived example:
public List<T> GetAll<T>()
{
Type typeParameterType = typeof(T);
if(typeParameterType == typeof(string))
{
var myList = new List<string>() { "one", "two", "three" };
return myList.Cast<T>().ToList();
}
else if (typeParameterType == typeof(int))
{
var myList = new List<int>() { 1, 2, 3 };
return myList.Cast<T>().ToList();
}
return new List<T>();
}
var intResult = GetAll<int>();
var stringResult = GetAll<string>();
Here I am using int and string, but in my real code they would be class objects. This functions fine, but to other programmers they won't know what they can put into <T> because the logic of what it supports is internal.
Is there any way I can say GetAll<int>, GetAll<string>, GetAll<bool>, etc in such a way that intellisense will "see" it and be able to communicate it to users of my code.
I am trying to move away from this style:
public List<int> GetAllInt();
public List<int> GetAllString();
public List<int> GetAllBool();
Since it makes it bloats out the interface. I want them to be able to see a small list of functions they can do, and then to pick the type after they've picked the activity, so like GetAll<int>() seems cleaner to me. But having no way to communicate what is compatible is a road block.
I have seen the where T : IMyInterface which does restrict what they can send, but it doesn't communicate what it is they can send.