I am trying to create a generic extension that uses 'TryParse' to check if a string is a given type:
public static bool Is<T>(this string input)
{
T notUsed;
return T.TryParse(input, out notUsed);
}
this won't compile as it cannot resolve symbol 'TryParse'
As I understand, 'TryParse' is not part of any interface.
Is this possible to do at all?
Update:
Using the answers below I have come up with:
public static bool Is<T>(this string input)
{
try
{
TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(input);
}
catch
{
return false;
}
return true;
}
It works quite well but I think using exceptions in that way doesn't feel right to me.
Update2:
Modified to pass type rather than use generics:
public static bool Is(this string input, Type targetType)
{
try
{
TypeDescriptor.GetConverter(targetType).ConvertFromString(input);
return true;
}
catch
{
return false;
}
}
I managed to get something that works like this
Here's my code
The StaticMembersDynamicWrapper is adapted from David Ebbo's article (it was throwing an AmbiguousMatchException)
Here's another option.
I wrote a class that makes it easy to register any number of
TryParse
handlers. It lets me do this:I get
42
printed to the console.The class is:
Borrowed from http://blogs.msdn.com/b/davidebb/archive/2009/10/23/using-c-dynamic-to-call-static-members.aspx
when following this reference: How to invoke static method in C#4.0 with dynamic type?
And use it as follows:
This uses a static constructor for each generic type, so it only has to do the expensive work the first time you call it on a given type. It handles all the types in the system namespace which have TryParse methods. It also works with nullable versions of each of those (that are structs) except for enumerations.
Using try/catches for flow control is a terrible policy. Throw an exception causes performance lags while the runtime works around the exception. Instead validate the data before converting.
How about something like this?
http://madskristensen.net/post/Universal-data-type-checker.aspx (Archive)
This can be converted to a generic method pretty easily.