Reputation: 2521
I've got a generic method which converts an id from a string (eg, retrieved from the Value of a HiddenField on an ASP.NET Form) to a target type and does something with it.
private void MyMethod<T>(string rawId, Action<T> doSomethingWithId)
{
T id = (T)Convert.ChangeType(rawId, typeof(T));
doSomethingWithId(id);
}
T will be either Guid or Int32 and the above code falls over (at runtime) when it is Guid, saying that the cast from String to Guid is invalid.
Then I thought I might try to check the type and if Guid, instantiate a new Guid:
var id = default(T);
if (id is Guid)
id = new Guid(rawId);
else
id = (T)Convert.ChangeType(rawId, typeof(T));
now this gives an error (at compile time) that Guid cannot be converted to type T
Not too sure how to work around this. Any suggestions?
Upvotes: 13
Views: 7451
Reputation: 841
You can try something like this perhaps:
private void MyMethod<T>(string rawId, Action<T> doSomethingWithId)
{
T id = (T)Activator.CreateInstance(typeof(T), new object[] { rawId });
doSomethingWithId(id);
}
Upvotes: 1
Reputation: 1500535
If T
will either be Guid
or Int32
then it's not really very generic, is it? Just write two methods instead - either with different names, or possibly overloads. I don't see the benefit in using generics here, and it may very well make your code more complicated than it needs to be.
Upvotes: 3
Reputation: 2073
the below code works fine with conversion to Guid . check it
id = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);
Upvotes: 29