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;
}
}
When I wanted to do almost this exact thing, I had to implement it the hard way, given reflection. Given
T
, reflect ontypeof(T)
and look for aTryParse
orParse
method, invoking it if you've found it.A version for getting descendants from XDocument.
This is a question of 'generic constraints'. Because you don't have a specific interface then you are stuck unless you follow the suggestions of the previous answer.
For documentation on this, check the following link:
http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx
It shows you how to use these constraints and should give you some more clues.
If you are set on using TryParse, you can use reflection and do it like this:
Quite a bit late to the party, but here's what I came up with. No exceptions, one-time (per type) reflection.
The extra class is required because extention methods are not permitted inside generic classes. This allows simple usage, as shown below, and only hits reflection the first time a type is used.