Home > Net >  How to write if else statement in single line in C#
How to write if else statement in single line in C#

Time:11-29

In the below code, I am repeating the same code twice except one change. If there is a way to write the same in single line then it would be great.

The only changes I made is Obsc and zp based on the if..else statement.

Please see this one St= string.Format(Obsc, .......,userProfile.DisplayName()); I am only replacing Obsc with zp in if .. else block. So if we can write in such way that we can accomodate all in one except writing the same twice.

var zp = __Services.GetValue("Z", Order.Code);
               var St="";
               if(sp.Label != null)
                {
                    var Obsc = _Services.GetValue("Z", sp.Label);
                     St= string.Format(Obsc, .......,userProfile.DisplayName());
                }
                else
                {
                     St = string.Format(zp, ......., userProfile.DisplayName());
                }       

CodePudding user response:

You might want to look into the ternary operator in c#: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator.

CodePudding user response:

St = string.Format(sp.Lable != null? _Services.GetValue("Z", sp.Label) : __Services.GetValue("Z", Order.Code), ......., userProfile.DisplayName());

CodePudding user response:

Are you happy with something like this?

var code = sp.Label is null
                ? Order.Code
                : sp.Label;

var zpOrObsc = service.GetValue("Z", code); // please use a valid variable name
var st = string.Format(zpOrObsc, ......, userProfile.DisplayName());

CodePudding user response:

St = string.Format(_Services.GetValue("Z", sp.Label ?? Order.Code), ......., userProfile.DisplayName());

CodePudding user response:

Make a variable to determine which parameter value you want to call GetValue with. You only need to call GetValue once and string.Format once.

var whateverTheSecondParamForGetValueIs = Order.Code;

if (sp.Label != null) {
    whateverTheSecondParamForGetValueIs = sp.Label;
}

var zp = _Services.GetValue("Z", Order.Code);
var St = string.Format(zp, ......., userProfile.DisplayName());

No, this isn't a "single line", but I don't see the appeal in that. To me, this is much more readable than any ternary operator.


I'm also going to say that these variable names need quite an improvement. They don't convey any meaning.

  •  Tags:  
  • c#
  • Related