When you create a generic method (Foo
public static T ChangeTypeLinqVariant<T>(this object value)
{
return (new [] {value}).Cast<T>().Single();
}
Obvious examples where you need a ChangeType
An obvious example is:
private Car GetCar()
{
return new Car
{
Id = GetItemFromXml<Guid>(@"Indentification/id"),
Brand = GetItemFromXml<string>(@"BrandInfo/name"),
ConstructionYear = GetItemFromXml<int>(@"BuilDetails/year"),
};
}
private T GetItemFromXml<T>(string xmlPath)
{
var itemValueAsString = GetAValueFromXml(xmlPath);
return itemValueAsString.ChangeType<T>();
}
private string GetAValueFromXml(string xmlPath)
{
// Open a file and get a string value based on the xmlPath
}
A less obvious example is:
private void AddItem<TK, TV>(Dictionary<TK, TV>dictionary, TK key, TV value)
{
if (key is string) // Then we want the key to be lower case
{
// This wil not compile because key is a TK, not a string
key = key.ToString().ToLower();
// This will do the job
key = key.ToString().ToLower().ChangeType<TK>();
}
if (dictionary.ContainsKey(key)) return;
dictionary.Add(key, value);
}
The code of the GenericRandom class can be found on Github. If you use .Net 6, you can also use the Q11.Tools Nuget package..