liv2hak
liv2hak

Reputation: 14970

Using conditional operator ? to avoid if condition

I have the following C# code

public Config(SConfig[] c)
{
    GpsdIp = c[0].Ip;
    GpsdPort = c[0].Port;

    CompassIp = c[1]?.Ip;
    CompassPort = c[1]?.Port;
}

CompassPort = c[1]?.Port; is giving a warning (red carpet) Cannot implictly convert int? to int. Explict conversion exists are you missing a cast?

My intention here is that if the SConfig[] c contains one element it should be assigned to GpsdIp and GpsdPort. If it contains two elements then the second element should be treated as CompassIp and CompassPort. I would really like to avoid and if condition if I can.

Upvotes: 1

Views: 83

Answers (3)

Travis Manning
Travis Manning

Reputation: 350

Anything you do, other than an if statement, to accomplish the same will have more overhead than a simple if.

That said, it would seem ripe for a ternary.

public Config(SConfig[] c) {
    GpsdIp = c[0].Ip;
    GpsdPort = c[0].Port;

    CompassIp = c.Length == 1 ? CompassIp : c[1].Ip;
    CompassPort = c.Length == 1 ? CompassPort : c[1].Port;
}

Upvotes: 2

Eser
Eser

Reputation: 12546

What in your code is null conditional operator. Your correct syntax should be:

 CompassIp = c.Length > 1 ? c[1].Ip : null;
 CompassPort  = c.Length > 1 ? c[1].Port : 0;

PS: You would get an Index out of range exception at runtime if it would be compilable.

Upvotes: 3

Andrey Nasonov
Andrey Nasonov

Reputation: 2629

You should learn the basics of C#. When trying to access at item outside array bounds, IndexOutOfRangeException is raised instead of returning default nullable value.

The solution for you is to use if operator:

if (c.Length > 1)
{
    CompassIp = c[1].Ip;
    CompassPort = c[1].Port;
}

Upvotes: 1

Related Questions