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

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


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

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


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.


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);}