operator overloading true and false

X

xllx.relient.xllx

Hi, there. I need two simple things explained to me:

1.) I want to know why the "true" overloaded operator method gets
called with a test to a null-initialized instance:

public class AnimalClass
{
public static bool operator true( AnimalClass lhs )
{
Console.WriteLine("In true operator");
return true;
}

public static bool operator false( AnimalClass lhs )
{
Console.WriteLine("In false operator");
return false;
}
}

public class MainClass
{
public static void Main( )
{
AnimalClass A = null;

if ( A )
Console.WriteLine("true");
}
}

// output: In true operator
// is true



2.) How can you call the "false" operator method? because I've tried to
in many ways and I cannot get it to be invoked - only "true" works.

Thanks,
relient.
 
R

Rudderius

I think this is because the overloaded operator is a static method, so
it needs no instance to work. secondly you do not use the parameter lhs
for this operator. Compare it to calling a static member return a fixed
value like
public static int GetInt()
{
return 0;
}

as far as i know, this must solve your problem:
public static bool operator true( AnimalClass lhs)
{
if (lhs != null)
{
Console.WriteLine("In true operator : return true");
return true;
}
else
{
Console.WriteLine("In true operator: return false");
return false;
}
}
 
J

Jon Skeet [C# MVP]

Hi, there. I need two simple things explained to me:

1.) I want to know why the "true" overloaded operator method gets
called with a test to a null-initialized instance:

<snip>

The compiler sees an AnimalClass expression which needs converting to
true/false, so it calls the true operator with the value of the
expression - which is null in this case.

2.) How can you call the "false" operator method? because I've tried to
in many ways and I cannot get it to be invoked - only "true" works.

Hmm... looking at the spec, I can't see any examples of where it's
called. Odd.

I must say, I've *never* seen these operators used in production code -
I would suggest you steer clear of them providing an explicit method
call so that it's more obvious what's going on.
 

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