This is an archived post. You won't be able to vote or comment.

all 3 comments

[–][deleted] 0 points1 point  (0 children)

Uh, no. It's user-defined cast operators that should be handled with care, and by handled with care I mean never implemented. Except maybe for value types representing mathematical concepts, and even then with extreme caution.

For instance, var human = (Human)employee; if (human == employee) ... is false, does that make you think there's a "gotcha" in equality comparison?

Basically, the retardiation of you example can't be discounted on it being "abstract" or something, you simply should never implement cast for reference types, not for "humans" and "employees", not for anything else, ever.

As for performance, I doubt you could ever find a program where eliminating a superfluous cast matters.

But of course when you want to use as operator, you should use as operator, not is operator plus cast.

[–]adaptable 0 points1 point  (0 children)

What you might want here is

typeof(Human).IsAssignableFrom(new Employee())

which should return true.

[–]oniony 0 points1 point  (0 children)

The interesting thing here is that the 'as' operator wouldn't actually invoke the implicit or explict casts, so what is written in the article is actually incorrect advice.

Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed using cast expressions..

The other thing to remember is that an 'as' cast should always be immediately followed by a null check, otherwise you risk transforming perfectly understandable cast exceptions at point of problem into hard-to-fathom null reference exceptions in some potentially unrelated part of your codebase.