implicit operator bool - question 1

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;
}
}
 
A

Andy Renk

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top