2007-09-13

! is a bad operator

In C#, C and C++ the exclamation sign (!) is used for negating a boolean value.

This is considered a bad thing because it is so small and easy to miss.

    if( !IsPostBack ){...

I would like to write

    if( Not( IsPostBack ) ){...

instead.  But I have yet to find a way to overload it such in C#.

Even with the improved readability of "Not" it is easy to think wrong.  It is way too easy to get lost in negations in a just slighty complex boolean expression.

A way to improve readability is to avoid the useage of ! or negations at all:
    if( IsPostBack ){
        // Does nothing.
    }else{
        ...
    }

2 comments:

Edward said...

At work we currently work on negating negative negations for fun, no practical application.

if !(!unHidden != false)
{
return !DontShow(!unHidden);
}

Somehow I don't see your problem. It's perfectly obvious isn't it? :-)

Anonymous said...

Well you can always try VB?

If Not IsPostback Then

:-D


/ Ola