Reputation: 351
if I have int number in nominator, I will do one method from my1.cs, if I have double number in nominator/denominator I will do method from another class called my2.cs . How I may code IF,
if (number = int) {//; bla bla bla...}
OR
if (number = double) {//; bla bla bla...}
How to code this if-statement: if (numerator.GetType==int){...}
?
The main trouble is in this: I read nominator and denominator from textbox, with var dr1 = textBox1.Text.Split('/'); ! split, but how i can gettype from string ???
Upvotes: 9
Views: 17241
Reputation: 12475
C# 7
if (number is int myint) {//; do something with myint} OR
if (number is double mydouble) {//; do something with mydouble}
Each case is true if the type matches. The cast value will be placed in the variable.
Upvotes: 0
Reputation: 7879
if (numerator is int) { ... }
or
if (numerator.GetType() == typeof(int)) {...}
The former is usually better.
EDIT:
Нou say the problem is parsing numbers from string representation. I'm afraid, the best approach here is to call type.TryParse
and check if given string can be parsed as a number of given type.
E.g.
var tokens = line.Split('/');
double dArg1,dArg2; int iArg1, iArg2;
if (int.TryParse(tokens[0], out iArg1)
&& int.TryParse(tokens[1], out iArg2)){
return iArg1/iArg2;
} else if (double.TryParse(tokens[0], out dArg1)
&& double.TryParse(tokens[1], out dArg2)){
return dArg1/dArg2;
} else { /* handle error */ }
Note that all int
s can be parsed as double
s, so you need to try to parse token as int
before trying to parse it as `double.
Upvotes: 16
Reputation: 14781
Use the following:
if ( value is int ) { }
You may also want to take a look at Generic Methods (C# Programming Guide)
Upvotes: 1
Reputation: 2973
This should work:
if (numerator.GetType() == typeof(int))
{
// it's an int
}
else if (numerator.GetType() == typeof(double))
{
// it's a double
}
Not sure why you'd want to do that though...
Upvotes: 0
Reputation: 11760
You can use the typeof-operator:
if(typeof(int) == numerator.GetType())
{
//put code here
}
Upvotes: 2