I am trying to get two different return values from dictionary extension methods for convenience. The first being an Item of the RealType
, the other being a List<RealType>
.
The problem / question is this: Getting a single RealType
item works like a charm, getting the List crashes and calls for IConvertable implementation. Is there no build in call to convert a full list?
Edit: I am trying to convert from Base Class to Derived Class, not the other way around. Also, I 100% know the data will be of type Derived Class and the caller is passing the correct type each time, without any chance of error.
Why is that? Can I avoid it, without "dirty" tricks?
There are about two dozen RealType
- classes that all extend from MyAbstractModel
and get saved in a
List<Dictionary<string, MyAbstractModel>
. Writing code for two dozen conversions seems like no good idea, when a small dirty (?) trick seems to do it as well.
Consider the following (working) DictionaryExtention class
public static class DictionaryExtenders
{
public static T GetItem<T>(this Dictionary<string, MyAbstractModel> instance, string key)
{
return (T)Convert.ChangeType(instance[key], typeof(T));
}
}
Called like this: RealType item = myDictionary.GetItem<RealType>("choosenIDString");
Edit: Each Dictionary can and will only ever have one type present. There won't ever be two different types stored in one. Yes, this code would allow that and spew out errors, but a saveguard is not needed in this case and is not part of my question.
Now in contrast, the following GetList<RealType>
extention calls for IConvertable implementation:
public static List<T> GetList<T>(this Dictionary<string, MyAbstractModel> instance)
{
return (List<T>)Convert.ChangeType(instance.Values.ToList(), typeof(List<T>));
}
I feel like I am missing something here, because the following workaround also returns a List<RealType>
, but does not call for IConvertable. I simply loop the dictionary and call GetItem<T>()
each time.
public static List<T> GetList<T>(this Dictionary<string, MyAbstractModel> instance)
{
var temp = new List<T>();
foreach (RealType myType in instance.Values.ToList())
{
temp.Add(instance.GetItem<T>(myType.ID));
}
return temp;
}
This does not feel like a solid solution, but like a workaround. What am I missing here? Do the Lists give me a hard time due to faulty syntax on my side, or is there a reason I have to understand?