views:

160

answers:

6

I have two methods A and B only after the success of two methods i have to insert into database... So is this a valid conditional Statement in c#?

if(A() && B())
{
    //insert into db
}

After the execution of method A i have to execute B If both are successful i have to insert...

+8  A: 

Yes it is valid. But note that B will only execute if A() returns true.

klausbyskov
@Klausbyskov ya i want that exactly...
Pandiya Chendur
A: 

It should be

if(A()) 
{ 
   if(B())
   {
    //insert into db 
   }
} 

This will take care that both the functions are getting executed.

Varun Mahajan
why will this take care about that both functions are executed?? If `A()` fails, then `B()` won't be executed, so it exactly the same as the code in the question.
Oliver
+2  A: 

This is called short-circuit evaluation

The conditions will be evaluated in the order of appearance, and only if their testing is still relevant. That is, if A() fails, there is no reason to test B().

Itsik
+1 for providing the link
GrahamS
A: 

As they say B() is not executing if A() returns false. If you want both functions to be executed I recommend something like:

bool resultA = A();
bool resultB = B();
if(resultA && resultB)
{
    //insert into db
}
Cristian
fearofawhackplanet
the example is obviously not short-circuiting the functions which is what the example demonstrates
Cristian
A: 

set fa=1 fd=1 inside both function.

Then check

if(fa==fb==1) { //do }

Ayyappan.Anbalagan
Seriously dude? That is really ugly code. You even want him to instantiate two global variables instead of using return values for something this trivial?.. sigh! If something goes wrong inside the methods it should be caught by a try catch outside.
Silas Hansen
A: 

Your question has already been answered by others, but just to clarify as there are a couple of slightly misleading posts on here...

The && operator is short-circuiting

if (false && Foo()) // Foo() is not run

The & operator is not short-circuiting

if (false & Foo()) // Foo() is run

Use the latter if your functions have side effects which you want to ensure.

fearofawhackplanet