Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ???

like image 278
user707895 Avatar asked May 26 '11 06:05

user707895


People also ask

How do you check if a variable is a specific type?

Use isinstance() to check if a variable is a certain type Call isinstance(variable, type) to check if variable is an instance of the class type .

What is GetType C#?

GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType ();

How do you check if an object is a certain type C#?

To determine whether an object is a specific type, you can use your language's type comparison keyword or construct. For example, you can use the TypeOf… Is construct in Visual Basic or the is keyword in C#. The GetType method is inherited by all types that derive from Object.

What is the use of typeof ()?

The typeof operator is used to get the data type (returns a string) of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. The operator returns the data type.


2 Answers

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.

like image 196
elder_george Avatar answered Oct 09 '22 16:10

elder_george


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

typeof (MSDN)

like image 39
bniwredyc Avatar answered Oct 09 '22 17:10

bniwredyc