views:

308

answers:

3

BACKGROUND: I have a custom class written in C# (2005), with code similar to the following:

public class Savepoint
{
  public int iOffset;                 /* Starting offset in main journal */
  public u32 nOrig;                   /* Original number of pages in file */
  public u32 iSubRec;                 /* Index of first record in sub-journal */
};

After a variable has been declared with Savepoint sp; I can test to see if has been instantiated with code similar to:

if (sp != null) {...}

QUESTION: Is it possible to overload the class operator somehow so that I can also use the following syntax as well: if (sp) {...} or if (sp != 0) {...}

PS: I have no real good reason for wanting to write if (sp) other than force of habit.

+17  A: 

You might be able to do that in C# using the default property decorator, but you shouldn't. Trying to write C# like it was a duck-typed language will lead to all sorts of cognitive dissonance down the line.

As a rule of thumb, it's a good idea to embrace the vernacular of the language you're working in rather than trying to cram it into a more-familiar shape it was never meant to hold.

Jekke
+3  A: 

The if statement in C# takes a boolean expression and doesn't do type conversion to boolean if the expression is non-boolean, unlike in C (or Javascript). My advice is to just deal with the minor annoyance and use the standard C# idiom.

tvanfosson
+4  A: 

I think you can add an implicit cast to bool... something like this should work.

public static implicit operator bool(Savepoint sp)
{
    return sp != null;
}

Example:

Savepoint sp1 = new Savepoint();
sp1.iOffset = 4;
Savepoint sp2 = new Savepoint();
Savepoint sp3 = null;

Console.WriteLine("sp1: " + (sp1 ? "true" : "false")); // prints true
Console.WriteLine("sp2: " + (sp2 ? "true" : "false")); // prints true
Console.WriteLine("sp3: " + (sp3 ? "true" : "false")); // prints false
Aistina
Nice solution. I'll accept your answer if you change your code to eliminate the iOffset test in the operator bool, something likereturn (sp != null)
Noah
Ehm sure, fixed :-)
Aistina
What is the point of implicit ?
You can choose either implicit or explicit. If you use explicit rather than implicit you have to explicitly cast it too bool to work... if ((bool)savePointVar) { ...}
Aistina
*cast it to <- stupid typo's :P
Aistina