user3356020
user3356020

Reputation: 119

Writing an "if" condition in C# but there will not be any code written inside it

I have a DataTable pgRestrictionTbl :

pgRestrictionTbl = GetDataTable(ProjectID, sgID)

I have written an "if" condition, in which again I have written "if and else" conditions.

if()
{
    if()
    {
         KnownErrorException.Throw("eSGNTRSTRCTD");
    }
    else
    {
          KnownErrorException.Throw("eSGNKKTURSTRCTD");
    }
}
else
{
    if()
    {
       // I dont need any code to be execute in this block
    }
    else
    {
        KnownErrorException.Throw("eSGNTRHJISTRCTD");
    }
}

method call();

Have some code after all these conditions. Now if my condition is true at elseif condition, I need to execute the code method call which is out of all these conditions. I don't want to write any goto label. Is there any other way? Can someone help on this ?

I tried this without writing any code in that if condition, but I don't think that was an efficient way.

Upvotes: 0

Views: 151

Answers (4)

NeverHopeless
NeverHopeless

Reputation: 11233

I think it would make your life easier if you combine conditions like:

if(condition1 && condition2) // Combine conditions
{
   KnownErrorException.Throw("eSGNTRSTRCTD");
}
else if(condition1Only)
{
   KnownErrorException.Throw("eSGNKKTURSTRCTD");
}
else
{
   // Since there in no sense to have an IF statement with no statements then no need to define it.
   KnownErrorException.Throw("eSGNTRHJISTRCTD");
}

// Congratulation, you have all valid inputs, it is safe to call a method.
methodCall();

Upvotes: 0

SeeMoreGain
SeeMoreGain

Reputation: 1273

This is just a matter of style and convention. There is no one right answer.

Some will argue to invert the logic so there is no need to have the branch in question.

Others will argue to include the branch and put a comment in there to say nothing need be done, just to show that the branch has been considered and was not left out by mistake.

SUMMARY: Do what makes most sense to you or what the people at your current job / place of study do

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28588

You can try:

if(cond1)
{
  if(cond2)
  {
   KnownErrorException.Throw("eSGNTRSTRCTD");
  }
  else
  {
    KnownErrorException.Throw("eSGNKKTURSTRCTD");
  }
}
else if(!cond3)
{
  KnownErrorException.Throw("eSGNTRHJISTRCTD");
}

Upvotes: 2

Euphoric
Euphoric

Reputation: 12859

Just invert the if?

if()
{
if()
{
 KnownErrorException.Throw("eSGNTRSTRCTD");
}
else
{
  KnownErrorException.Throw("eSGNKKTURSTRCTD");
}
}
else
{
if(!expr)
{
KnownErrorException.Throw("eSGNTRHJISTRCTD");
}
}

Upvotes: 1

Related Questions