Conditional evaluation and |= operator

C

Caddzooks

Hi

public class Class1
{
public void test()
{
bool result = true;

result |= foo(); // foo() always called.

result = result || foo(); // foo() not called
}

public bool foo()
{
return false;
}
}


The question is quite simply, if I can use 'var |= arg' to do the functional equivalent of 'var = var || arg', why does |= evaluate the right side when the result is already known (e.g, the value being assigning is true) ?

I undertstand why this happens in C++, but in C#, the |= operator is operating on bool operands.

--
caddzooks
 
J

Jon Skeet [C# MVP]

public class Class1
{
public void test()
{
bool result = true;

result |= foo(); // foo() always called.

result = result || foo(); // foo() not called
}

public bool foo()
{
return false;
}
}

The question is quite simply, if I can use 'var |= arg' to do the functional equivalent of 'var = var || arg', why does |= evaluate the right side when the result is already known (e.g, the value being assigning is true) ?

var |= arg; is doing exactly the same as

var = var | arg;

| doesn't apply short-circuiting; || does.

| is a logical operator whereas || is a *conditional* logical
operator.

Now, you could argue for the ability to write var ||= arg; but the
behaviour of var |= arg; itself is exactly as I'd expect.

Jon
 
B

Ben Voigt [C++ MVP]

Caddzooks said:
Hi

public class Class1
{
public void test()
{
bool result = true;

result |= foo(); // foo() always called.

result = result || foo(); // foo() not called
}

public bool foo()
{
return false;
}
}


The question is quite simply, if I can use 'var |= arg' to do the
functional equivalent of 'var = var || arg', why does |= evaluate the

You can't.

var |= arg is equivalent to var = var | arg

The C# spec defines var || arg as just var | arg with short-circuiting
 

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