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.
if? If there is no second element, what value do you expectCompassIp/Portto hold?c[1]?.Ipyou are assigning an integer to the right hand side variable, but if it is not present then it will assignNULL, for which your variable is not ready. Since you haveint CompassIphence 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.