Reputation: 1114
One interviewer asked this question to me ,when I am checking it's working how it is possible to check type of char and double? Please any one explain me.
class Program
{
static void Main(string[] args)
{
double d=0;
if((double)d == 'c')
{
Console.WriteLine("working");
}
else
{
Console.WriteLine("not");
}
Console.ReadLine();
}
}
Upvotes: 4
Views: 246
Reputation: 458
Actually when you are trying to compare any numeric value to char value, its not giving you any compile time or run time error, because char is actually represent int16 or 16-bit integer value, so when you try to compare double, integer or long with it, it will simple compare its ASCII value of that character with it. here is some example...
double d = 65;
if (d == 'A')
{
Console.WriteLine("working");
}
else { Console.WriteLine("not"); }
the above code's out put is "Working" because char "A" ASCII value is 65 and you are comparing it with 65 so it true with if condition.
Upvotes: 0
Reputation: 186813
Char
type is actually a 16-bit integer, so you can compare them if you like:
Double left = 'B'; // <- 66.0
Char right = 'A'; // <- it's 16-bit int == 65 in fact
if (left > right) {...}
There's one issue, however: you should not use ==
or !=
without tolerance, since Double
as well as other floating point types has round-up error, so
Double left = 66;
could be in fact 66.000000000002
or 65.9999999999998
. Something like that:
Double left = 'B'; // <- 66.0
Char right = 'A'; // <- it's 16-bit int == 65 in fact
// (left == right) comparison with tolerance
// Since right is integer in fact, 0.1 tolerance is OK
if (Math.Abs(left - right) < 0.1) {...}
Upvotes: 8
Reputation: 1737
you can use the normal GetType()
and typeof()
to check type of an any object. like this
class Program
{
static void Main(string[] args)
{
double d=0;
if(d.GetType() == typeof(Char))
{
Console.WriteLine("working");
}
else
{
Console.WriteLine("not");
}
Console.ReadLine();
}
}
Upvotes: 2