Reputation: 5889
I have the following two classes. The ConvertToType<T>
class is an existing class and works fine, however when it is used an instance is created each time (via reflection), therefore I am creating a wrapper class to hold all the instances as they are created for efficiency.
public class TypeConverterHelper
{
private IList<ConvertToType<>> types;
}
internal class ConvertToType<T>
{
//snip
}
However, as you can see I need a list of my ConvertToType<T>
class, but I can't specify the type as the whole point of these classes is that the type is unknown until runtime. I have researched this issue a fair amount, but without finding a successful solution. I know I could set the generic type to be an object, but there you could get un/boxing issues at some point. Adding an interface/abstract base class which is restricted to a struct
looked like a good option, but unfortunately T
could be a string, and possibly other custom classes at a later date so that solution doesn't work.
So does anyone have any other solutions/suggestions?
Upvotes: 0
Views: 2386
Reputation: 437854
The list type has to be non-generic (since the generic type arguments cannot be predicted), so object
would do, but it might be better to use a common non-generic base. Boxing/unboxing does not come into the discussion because ConvertToType
is a reference type.
You would of course have to cast the values in the list back to ConvertToType<T>
before being able to use them; the implementation could look like this:
public class TypeConverterHelper
{
private IList<object> types;
public ConvertToType<T> GetConverter<T>()
{
return types.OfType<ConvertToType<T>>.FirstOrDefault();
}
}
Upvotes: 3