Search code examples
c#.netif-statementconsole.writeline

How to control output by if statement


if (vm.Name != null)
{
    Console.WriteLine("VM name is \"{0}\" and ID is \"{1}\". State is: \"{2}\". Location: \"{3}\" and the Instance Type is \"{4}\". Key is \"{5}\".",
        vm.Name, vm.InstanceId, vm.State, vm.Region, vm.InstanceType, vm.KeyName);
}
else
{
    Console.WriteLine("VM ID is \"{0}\". State is: \"{1}\". Location: \"{2}\" and the Instance Type is \"{3}\". Key is \"{4}\".",
        vm.InstanceId, vm.State, vm.Region, vm.InstanceType, vm.KeyName);
}

I'm trying to do as little copy-pasting here as possible. My question's how to shrink this code so that simply apply if-statement only for the first bit of information vm.Name and not the whole output line?


Solution

  • Use an expression. Something like this:

    Console.WriteLine(
        "VM {0}ID is \"{1}\". State is: \"{2}\". Location: \"{3}\" and the Instance Type is \"{4}\". Key is \"{5}\".",
        vm.Name != null ? $"name is \"{vm.Name}\" and " : string.Empty, vm.InstanceId,
        vm.State, vm.Region, vm.InstanceType, vm.KeyName);