Why doesn't is operator take in consideration if the explicit operator is overriden when checking ty
Posted
by Galilyou
on Stack Overflow
See other posts from Stack Overflow
or by Galilyou
Published on 2010-06-02T08:55:47Z
Indexed on
2010/06/02
9:03 UTC
Read the original article
Hit count: 317
c#
Hey Guys,
Consider this code sample:
public class Human {
public string Value { get; set;}
}
public class Car {
public static explicit operator Human (Car c) {
Human h = new Human();
h.Value = "Value from Car";
return h;
}
}
public class Program {
public static void Mani() {
Car c = new Car();
Human h = (Human)c;
Console.WriteLine("h.Value = {0}", h.Value);
Console.WriteLine(c is Human);
}
}
Up I provide a possibility of an explicit cast from Car to Human, though Car and Human hierarchically are not related! The above code simply means that "Car is convertible to human"
However, if you run the snippet you will find the expression c is Human
evaluates to false! I used to believe that the is operator is kinda expensive cause it attempts to do an actual cast that might result in an InvalidCastException
. If the operator is trying to cast, then the cast should succeed as there's an operator logic that should perform the cast!
What does "is" test?
Does test a hierarchical "is-a" relationship?
Does test whether a variable type is convertible to a type?
© Stack Overflow or respective owner