Have better than: IsInt(string value)

S

skneife

Does anyone have a better way for knowing if a string contains an
int ?

bool IsInt(string valeur)
{
bool result = false;
try {
int.Parse(valeur);
result = true;
}
catch {}
return result;
}

Sam
 
M

Matt McGregor

You can use "is"

if (variable is int)
{
return true;
}


or just inline the "variable is int" in your code conditionals without calling a function. This also works for most types.

However, I have not found a good way to detect int? (nullable int) as a type like above. It does not find it; always returns false. Still looking.
Does anyone have a better way for knowing if a string contains an
int ?

bool IsInt(string valeur)
{
bool result = false;
try {
int.Parse(valeur);
result = true;
}
catch {}
return result;
}

Sam
On Wednesday, November 14, 2007 4:11 AM Jon Skeet [C# MVP] wrote:
If you are using .NET 2.0, use int.TryParse.

Jon
Submitted via EggHeadCafe
Review of Redgate ANTS Performance Profiler 6
http://www.eggheadcafe.com/tutorial...w-of-redgate-ants-performance-profiler-6.aspx
 
A

Arne Vajhøj

You can use "is"

if (variable is int)
{
return true;
}

Why answer on a 3 year old question with a WRONG answer?

The "is" test if something is already an int not whether
a string can be parsed to an int.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top