There is something that I don't understand about generic class types that I need explained to me.
Let's take the following silly method as an example:
public List<> RandomList() //Note that the Compiler yells at you for not giving a type parameter
{
var RandObj = new Random();
var myint = RandObj.Next(1,3);
switch(myint)
{
case 1: var StringList = new List<string>{ "Test" };
return StringList;
case 2: var IntList = new List<int>{ 1,2,3,4 };
return IntList;
}
}
Is there anyway to make a function like this work? I'm wondering if there is a way to set it so that I'm saying. "This function returns a list. I'm not sure what type of list it will return, but it will definitely be a list.
To do this you must return a type that is common to all of the possible options that your return object could be, for the two Lists you could return the best possible option for this situation is IList
public IList RandomList()
{
var RandObj = new Random();
var myint = RandObj.Next(1,3);
switch(myint)
{
case 1: var StringList = new List<string>{ "Test" };
return StringList;
case 2: var IntList = new List<int>{ 1,2,3,4 };
return IntList;
}
}
Some other possible choices are object
, IEnumerable
, and ICollection
In principle, in the C# Language, as specified, you can not do this.
See K.4.2 Open and closed types (Extracted Relevant Paragraph)
At run-time, all of the code within a generic type declaration is executed in the context of a closed constructed type that was created by applying type arguments to the generic declaration. Each type parameter within the generic type is bound to a particular run-time type. The run-time processing of all statements and expressions always occurs with closed types, and open types occur only during compile-time processing.
The compiler needs to be able to convert all open types to closed types. Hence it complains.
If you want a consistent external view, then Interfaces are the way to go. Here IList would work nicely.
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