implicit operator bool - question 1

  • Thread starter Thread starter Jon Shemitz
  • Start date Start date
J

Jon Shemitz

How come I can write code like "if (L)" but NOT code like "if (L ==
true)" when L is a class with an implicit operator bool?

///////////

List L = new List();

public class List
{
private long count = 0;

public static implicit operator bool (List L)
{
return L.count > 0;
}
}
 
the Code "If (L == true) reqires that L have an == operator.
Becase It does not, (L == true) does not evaluate to a function.
There are (at least) two ways to fix this
One way is to add the opperator overload to the List class
So it looks like the following


public class List
{
private long count = 0;
public static implicit operator bool (List L)
{return (L.count > 0);}
public static bool operator ==(List L, bool comparType)
{return (L.count > 0);}
public static bool operator !=(List L, bool comparType)
{return (L.count <= 0);}
public override bool Equals(object obj)
{return base.Equals (obj);}
public override int GetHashCode()
{return base.GetHashCode ();}
}

The other way is to type cast it to a bool
if(((bool)L) == true)
this way the bool's operator == function is called.

Hope this helps

Andy Renk

Junker_Mail(remove)@yahoo.com -- delete "(remove)" to email
 
Back
Top