Press J to jump to the feed. Press question mark to learn the rest of the keyboard shortcuts

C# Gottcha! Usage Of "is" Operator Should Be Handled With Care

31% Upvoted
This thread is archived
New comments cannot be posted and votes cannot be cast
level 1
1 point · 8 years ago

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.

level 1

What you might want here is

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

which should return true.

level 1

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.

Community Details





Computer Programming

Create Post
r/programming Rules
Keep submissions on topic and of high quality
No surveys
No résumés/job listings
/r/programming is not a support forum

Related reddits

Specific languages

Cookies help us deliver our Services. By using our Services or clicking I agree, you agree to our use of cookies. Learn More.