Reputation: 4596
In the code below, although I am getting a typeconverter for type Person, but I could also use it for the type Dog. (The types Person and Dog have nothing to do with each other.)
var person = new Person {Name = "Foo", Age = 99, Ssn = Guid.NewGuid()};
TypeConverter converter = TypeDescriptor.GetConverter(typeof (Person));
string str = converter.ConvertToInvariantString(new Dog());
Console.WriteLine(str);//ConsoleApplication1.Dog
So what is the purpose of passing in a type int the GetConverter method?
Upvotes: 0
Views: 154
Reputation: 7830
The TypeDescriptor.GetConverter(Type type) overload gives more options to the developer. MSDN states:
Call this version of this method only when you do not have an instance of the object.
So you should use the TypeDescriptor.GetConverter(Object o) whenever possible.
Scott Hanselmann has a good example in his blog article TypeConverters - he uses this method for a generic type identification:
public static T GetTfromString<T>(string mystring)
{
var foo = TypeDescriptor.GetConverter(typeof(T));
return (T)(foo.ConvertFromInvariantString(mystring));
}
The overload using Object
as parameter will not work with scalar data types.
UPDATE
It will work, but you have to write one line more :-P (and add a restriction):
public static T GetTfromString<T>(string mystring) where T : new()
{
var o = new T();
var foo = TypeDescriptor.GetConverter(o);
return (T)(foo.ConvertFromInvariantString(mystring));
}
GetTfromString<double>("10.5").Dump();
Upvotes: 1