Bibek Maharjan
Bibek Maharjan

Reputation: 585

Can a return statement returning the result of a ternary expression be made to not return for one branch of the ternary?

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;
}

Upvotes: 1

Views: 28797

Answers (3)

Joee
Joee

Reputation: 2016

Try something like this

    public static T GetResultByCondition<T>()
    {
        return (T)Convert.ChangeType(condition ? true : 2, typeof(T));
    }

Upvotes: -2

CodingYoshi
CodingYoshi

Reputation: 27039

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

Upvotes: 15

dnickless
dnickless

Reputation: 10918

No. The ternary operator just returns one out of two potential values depending on a condition.

What you can do with the ternary operator is, e.g. int a = condition ? 0 : 2 which would assign the variable a value of either 0 or 2 depending on the value of condition.

Given a more complete example of what you intend to do someone here could potentially come up with a nicer syntax.

Upvotes: 0

Related Questions