Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use c# ternary operator for return statement in combination with other statement

Tags:

c#

Is it possible to write this if statement in ternary operator (shorthand of c# if)? If yes what would it be?

   if (condition)
   {
      return true;
   }
   else
   {
      int a = 2;
   }

Thanx everyone in advance. Thank you very much.

Sorry guys if I confused you. I am trying to use ternary operator in this if else block of the method.

public static bool CompareDictionary(this Dictionary<Position, char> 
    dictionary1,
    Dictionary<Position, char> dictionary2, out List<string> wordList)
{
    string str = "";
    wordList = new List<string>();

    foreach (var dic1KeyVal in dictionary1)
    {
        Position d1key = dic1KeyVal.Key;
        char d1Pos = dic1KeyVal.Value;

        bool isFound = false;
        foreach (var dic2KeyVal in dictionary2)
        {
            Position d2key = dic2KeyVal.Key;
            char d2Pos = dic2KeyVal.Value;

            if (d1Pos.Equals(d2Pos) && d1key == d2key)
            {
                isFound = true;
                str = str + d1Pos.ToString();
            }
        }

        if (isFound == false)
        {
            return false;
        }
        else
        {

            wordList.Add(str);
            str = "";
        }
    }
    return true;
}
like image 446
Bibek Maharjan Avatar asked Dec 18 '22 06:12

Bibek Maharjan


1 Answers

Short Answer

No.

Long Answer

First of all this code does not even need an else:

if (condition)
{
    return true;
}
else
{
   int a = 2;
}

and can be written as:

if (condition)
{
   return true;
}

int a = 2;

Now for ternary operator: Both conditions in a ternary operator must return the same thing. You cannot return a bool in one condition and then assign to a variable in another condition. If you were checking the answer to a question, for example, it would be like this:

return answer == 2 ? true : false;

Whether the answer is correct or not, we return a bool. Or it could be like this:

return answer == 2 ? 1: -1;

But not like this:

return answer == 2 ? true : "wrong"; // will not compile
like image 190
CodingYoshi Avatar answered Dec 24 '22 01:12

CodingYoshi