Veli Gebrev
Veli Gebrev

Reputation: 2521

Convert value from string to generic type that is either Guid or int

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

Answers (3)

chemicalNova
chemicalNova

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

Jon Skeet
Jon Skeet

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

SShebly
SShebly

Reputation: 2073

the below code works fine with conversion to Guid . check it

id = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);

Upvotes: 29

Related Questions