How to make a condition that checks the variable type of a var

Asked

Viewed 51 times

0

I was trying to do a basic program to make the rule of three, but I came across a problem, the user should write at the command prompt the two fractions and so I would give them a value var to identify later if the characters would be int or string because a variable would be the arithmetic variable as the values x or y, now I am doing an if with the condition.

var valor1 = fracoes[0];
var valor2 = fracoes[1];
var valor3 = fracoes[2];
var valor4 = fracoes[3];

if(valor1 == string) // é nessa parte que tenho problema
{
  // aqui teria meu bloco de comando se o if funcionasse
}
  • In fact it makes no sense to make this check, it is a known information and this if is completely unnecessary. At least looking at this code, there may be something we don’t know, but then the question isn’t clear. To tell you the truth I think this is an XY problem, you want to do something completely different than what you’re describing. The variable has known type at compile time and this if is innocuous. Either the block will execute every time or it will never execute, there is no decision to be made.

1 answer

4


For type checking do not use the ==, and yes the is

An example:

if(varName is string) 
{
  // bloco
}

See working: IDEONE


Now, you need to see if it makes sense in your case. Probably not!

It probably doesn’t, it’s almost certain that we already know the type beforehand, without requiring any testing, there’s something in the rest of the code that already determines this. If you already know the type, I consider testing with is (in Runtime, which is even worse) is practically a bug.


Further reading:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.