Why doesn't is operator take in consideration if the explicit operator is overriden when checking ty
- by Galilyou
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?