Convert to unknown generic type: ChangeType<T>


When you create a generic method (Foo) or generic class (Bar), it often happens that you need to change (or convert) a type to T. In these situations you need a ChangeType function that changes "any" type to T. Unfortunately this is not a standard method. The Cast() method of Linq looks like a solution but it is very limited. This wil not work for a lot of types:

public static T ChangeTypeLinqVariant<T>(this object value)
  return (new [] {value}).Cast<T>().Single();


Obvious examples where you need a ChangeType method are:

  • Returns T but the parameter of the method is an object, string, XML or data from a DataReader.
  • Method returns T1 but the parameters of the method is T2: T1 Foo(T2 value))

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);

How to use ChangeType in your project?

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..

Leave a Comment