Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
Veli Gebrev Avatar asked Oct 27 '11 11:10

Veli Gebrev


People also ask

Can we convert GUID to string in C#?

According to MSDN the method Guid. ToString(string format) returns a string representation of the value of this Guid instance, according to the provided format specifier.

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

What is generic type C#?

Generic means the general form, not specific. In C#, generic means not specific to a particular data type. C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type.


1 Answers

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

id = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);
like image 128
SShebly Avatar answered Sep 25 '22 15:09

SShebly