Overriding the NOT (!) Operator

One thing commonly seen in C and C++ code is use of the NOT operator to check whether a struct or class pointer is set to NULL. For instance:

class value = NULL;
if( !value )
{
printf( “value is null” );
}

In C# code this results in an error because the compiler has no idea what “NOT” means on a class.  To be able to use this syntax in C# you have to override the ! operator, which is something I’ve never had occasion to do, AND that there are no easy-to-find code examples of. Luckily it’s just like overloading any operator in C#:

public static bool operator !( ClassType ct )
{
if( ct == null )
return true;
return false;
}

It works and it saves me the trouble of changing around 700 lines of code. We’re now down to 20,392 errors.

Categories: C#