Making If Control in One Line (Ternary If)

Making If Control in One Line (Ternary If)

Making If Control in One Line (Ternary If)

 Hello everyone, in this post I will explain how you can perform an if control in a single line in C#.

Before moving on to the content, I must mention that I wrote these codes in Unity; however, you can use them in any C# project you write with Visual Studio. Now we can move on to our article, happy reading.

Let’s look at how a normal if statement is written.

        string urhoba = "urhoba";
        if(urhoba == "urhoba")
        {
            Debug.Log("stringde urhoba yazıyor");
        }
        else
        {
            Debug.Log("stringde urhoba yazmıyor.");
        }
        

Above, we assigned a variable as "urhoba" of string type and set its value as "urhoba". We checked whether the value of the variable is equal to "urhoba" using If and Else, and printed the result to the console.

Now let’s see how Ternary If is written.

        string urhoba = "urhoba";
        string sonuc = (urhoba == "urhoba") ? "stringde urhoba yazıyor" : "stringde urhoba yazmıyor";
        Debug.Log(sonuc);

There are a few things we need to pay attention to when doing an if control with Ternary, let’s take a look at them.

First, when doing an if control with Ternary, we need to assign our ternary condition to a variable, and after the situation is determined, the returned result must be of the same type as the variable we defined.

In the example above, we created a ternary if control that will return a value of string type by defining it as "string sonuc". We then returned the value when the condition is met with "?", and the value when the condition is not met with ":".

If we need to perform an Else If control with Ternary, we can do it as follows.

        int b = 1;
        int a = (b == 1) ? 1
            : (b == 2) ? 2
            : b;

Let’s look at other examples.

        int intDonduren = (urhoba == "urhoba") ? 1 : 0;
        bool boolDonduren = (urhoba == "urhoba") ? true : false;
        

If there is anything you are curious about or stuck on regarding ternary if, you can ask me in the comments section below.