user707895
user707895

Reputation: 351

If-statement GetType() c#

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

Answers (8)

Carter Medlin
Carter Medlin

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

elder_george
elder_george

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 ints can be parsed as doubles, so you need to try to parse token as int before trying to parse it as `double.

Upvotes: 16

Akram Shahda
Akram Shahda

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

Stefano Ricciardi
Stefano Ricciardi

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

Unmesh Kondolikar
Unmesh Kondolikar

Reputation: 9312

Use the is operator in C#.

if(number is int)

Upvotes: 1

PVitt
PVitt

Reputation: 11760

You can use the typeof-operator:

if(typeof(int) == numerator.GetType())
{
    //put code here
}

Upvotes: 2

VMAtm
VMAtm

Reputation: 28355

You should try the is/as operator:

if (numerator is int) {...}

Upvotes: 1

bniwredyc
bniwredyc

Reputation: 8829

if (numerator.GetType() == typeof(int))
{
    ...
}

typeof (MSDN)

Upvotes: 5

Related Questions