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 ???
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 .
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 ();
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.
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.
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.
if (numerator.GetType() == typeof(int))
{
...
}
typeof (MSDN)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With