1

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.

2
  • 1
    Why do you want to avoid an if? If there is no second element, what value do you expect CompassIp/Port to hold? Commented Sep 1, 2017 at 1:23
  • 1
    Answers below are apt for your purpose. Just to clarify the reason of error. When you use c[1]?.Ip you are assigning an integer to the right hand side variable, but if it is not present then it will assign NULL, for which your variable is not ready. Since you have int CompassIp hence this error. If you would like to use your original code, you should have 'int? CompassIp`, i.e. CompassIp should be nullable integer and not just integer. And yes, out of index exception will be there, even before you can do anything with that NULL value. Commented Sep 1, 2017 at 1:35

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.