Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an object is a number in C#

I'd like to check if an object is a number so that .ToString() would result in a string containing digits and +,-,.

Is it possible by simple type checking in .net (like: if (p is Number))?

Or Should I convert to string, then try parsing to double?

Update: To clarify my object is int, uint, float, double, and so on it isn't a string. I'm trying to make a function that would serialize any object to xml like this:

<string>content</string> 

or

<numeric>123.3</numeric> 

or raise an exception.

like image 394
Piotr Czapla Avatar asked Jul 15 '09 10:07

Piotr Czapla


People also ask

How to check item exist in list in C#?

List < string > list1 = new List < string > () { "Lawrence", "Adams", "Pitt", "Tom" }; Now use the Contains method to check if an item exits in a list or not.


1 Answers

You will simply need to do a type check for each of the basic numeric types.

Here's an extension method that should do the job:

public static bool IsNumber(this object value) {     return value is sbyte             || value is byte             || value is short             || value is ushort             || value is int             || value is uint             || value is long             || value is ulong             || value is float             || value is double             || value is decimal; } 

This should cover all numeric types.

Update

It seems you do actually want to parse the number from a string during deserialisation. In this case, it would probably just be best to use double.TryParse.

string value = "123.3"; double num; if (!double.TryParse(value, out num))     throw new InvalidOperationException("Value is not a number."); 

Of course, this wouldn't handle very large integers/long decimals, but if that is the case you just need to add additional calls to long.TryParse / decimal.TryParse / whatever else.

like image 191
Noldorin Avatar answered Sep 28 '22 03:09

Noldorin