check, if string is convertable to another type

  • Thread starter Thread starter Daniel
  • Start date Start date
D

Daniel

Hello,

This is maybe a simple one:
Is there any way to check, if a string can be converted to
another type (like DateTime or Integer) without using
try/catch? In VB, i can use IsDate or IsNumeric to do
this, but how can i do it in C#?

Thanks in advance,
Daniel
 
Decimal has a TryParse function that won't throw an exception.

C# can reference the VB assemblies and call IsNumeric (shudder) -- please
don't do this. It's been a while since I looked at the code for IsNumeric,
but I think, in addition to doing some additional processing (VB is
sometimes more lenient on conversions), it might do a Try/Catch internally.

Try/Catch is usually how it's done, unless it's a performance critical
section, in which case you might run it through a regex first (remember to
take into account culture settings).

-mike
MVP
 
Daniel said:
Hello,

This is maybe a simple one:
Is there any way to check, if a string can be converted to
another type (like DateTime or Integer) without using
try/catch? In VB, i can use IsDate or IsNumeric to do
this, but how can i do it in C#?

Thanks in advance,
Daniel

There is no such thing as IsNumeric in C#. You'll have to work with a try
catch to test it or use the VB function.

public static bool IsNumeric(string input)
{
try
{
int.Parse(input);
return true;
}
catch
{
return false;
}
}

Yves
 
Back
Top