tags:

views:

263

answers:

6

How can tell if my object's value is a float or int?

For example, I would like this to return me bool value.

+8  A: 

I'm assuming you mean something along the lines of...

if (value is int) {
  //...
}

if (value is float) {
  //...
}
Hugoware
+2  A: 
if (value.GetType() == typeof(int)) {
    // ...
}
Mehrdad Afshari
This is slightly convoluted (and less efficient) way of doing it, when you can use the `is` keyword.
Noldorin
@Noldorin: Agreed. For `bool` or `int` (or any `struct`, for that matter), `is` is definitely better. But for other classes `is` will return true even if the actual type is a derived class and not the exact type.
Mehrdad Afshari
@Noldorin: less efficient for what? Shouldn't the IL be identical?
Jeff Yates
Yeah, that is true (though I suspect the situation in which you'd actually need to test for that would be reasonably rare). Given that this question only refers to value types, there's no issue here of course.
Noldorin
@Jeff Yates: No, they do very different things. And the result (as I mentioned in the comment) can be different. How the IL can be the same?
Mehrdad Afshari
@Jeff Yates: No, I don't believe it is. The `is` keyword gets compiled to a unique CIL instruction (maybe someone could verify this?), which the CLR then interprets specially and performs the test. As Mehrdad points out, the two methods don't behave exactly the same for reference types.
Noldorin
@Noldorin: IL has an `isinst` instruction.
Mehrdad Afshari
+1  A: 

If you mean an object that is a (boxed) float / int - if(obj is float) etc

If you mean a string that might be either... int.TryParse(string, out int) / float.TryParse(string, out float)

Marc Gravell
+1  A: 

Double.TryParse and Int.TryParse may be what you need, although this is assuming that you're working with a string given by a user.

chills42
A: 

Are you getting the value in string form? If so there is no way to unambiguously tell which one it isbecause there are certain numbers that can be represented by both types (quite a few in fact). But it is possible to tell if it's one or the other.

public bool IsFloatOrInt(string value) {
  int intValue;
  float floatValue;
  return Int32.TryParse(value, out intValue) || float.TryParse(value, out floatValue);
}
JaredPar
A: 

The TryParse method on various types returns a boolean. You can use it like this:

string value = "11";
float f;
int i;
if (int.TryParse(value, out i))
    Console.WriteLine(value + " is an int");
else if (float.TryParse(value, out f))
    Console.WriteLine(value + " is a float");
RedFilter