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;
}
}
You should use the TypeDescriptor class:
Inspired by the solution posted here by Charlie Brown, I created a generic TryParse using reflection that optionally outputs the parsed value:
It can be called thus:
Update:
Also thanks to YotaXP's solution which I really like, I created a version that doesn't use extension methods but still has a singleton, minimizing the need to do reflection:
Call it like this:
As you said,
TryParse
is not part of an interface. It is also not a member of any given base class since it's actuallystatic
andstatic
functions can't bevirtual
. So, the compiler has no way of assuring thatT
actually has a member calledTryParse
, so this doesn't work.As @Mark said, you could create your own interface and use custom types, but you're out of luck for the built-in types.
I also required a generic TryParse recently. Here's what I came up with;
Then it's simply a matter of calling thusly:
You can't do it on general types.
What you could do is to create an interface ITryParsable and use it for custom types that implement this interface.
I guess though that you intend to use this with basic types like
int
andDateTime
. You can't change these types to implement new interfaces.This is my try. I did it as an "exercise". I tried to make it as similar to use as the existing "Convert.ToX()"-ones etc. But this one is extension method: