I want to write
double num1;
if(num1 != double)
{
Console.WriteLine("Invalid operator.");
}
But I get an error message saying "Invalid expression term 'double'" I want to have the if statement write "Invalid operator" if num1 isn't a double.
I want to write
double num1;
if(num1 != double)
{
Console.WriteLine("Invalid operator.");
}
But I get an error message saying "Invalid expression term 'double'" I want to have the if statement write "Invalid operator" if num1 isn't a double.
Your question makes grammatical but not logical sense.
double num1;
num1
is a double
. It can't be anything but a double
, since you explicitly declared it to be a double
.
if(num1 != double)
Bad syntax aside, since num1
is a double
, the check is wholly unnecessary. It can never not be true, so there's no point in checking it.
That being said, your syntax of num1 != double
isn't valid. You're trying to compare the value of a variable to a given variable type. You're comparing apples and pears and the compiler has no idea how to handle that.
To compare types, you need to take the type of the variable, and compare it to another type. Something along the lines of:
public static void Main()
{
double num1 = 0;
if(num1.GetType() == typeof(double))
{
Console.WriteLine("num1 is a double");
}
else
{
Console.WriteLine("num1 is not a double, it is a " + num1.GetType().FullName);
}
int num2 = 0;
if(num2.GetType() == typeof(double))
{
Console.WriteLine("num2 is a double");
}
else
{
Console.WriteLine("num2 is not a double, it is a " + num2.GetType().FullName);
}
}
And the resulting output:
num1 is a double
num2 is not a double, it is a System.Int32
Instead of num1.GetType() == typeof(double)
you can also use num1 is double
. It's cleaner code but they don't always work exactly the same. For double
they are equivalent, but not if your chosen type could be derived (is
would yield true
on a derived type, but GetType() == typeof()
would yield false
)
But again, as I mentioned before, checking the type of a variable whose type you've explicitly defined makes no sense. Type checking is not a very common occurrence specifically because you often declare the type (implicitly or explicitly, it's the same to the compiler). It makes more sense when dealing with derived classes, when your variable is of a base type and you are interested if a particular derived type is being used.