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?
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.
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
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.
the below code works fine with conversion to Guid . check it
id = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With