Search code examples
c#.netstringstring-formattinginterpolation

string.Format paste string as parameter without quotes


I am formatting a string:

string.Format(
            "{{\"EventType\":\"{0}\",\"OrganizationId\":\"{1}\",\"Timestamp\":{2},\"ExecutionTime\":{3},\"Success\":{4}}}",
            telemetryEvent.EventType ?? "null", telemetryEvent.OrganizationId ?? "null", telemetryEvent.Timestamp,
            telemetryEvent.ExecutionTime, telemetryEvent.Success);

I need to get null instead of string if it is null.

E.g. ""OrganizationId":null" but I get ""OrganizationId":"null"" instead

Thanks


Solution

  • I think the simplest solution would probably be to use replace:

    string.Format(
            "{{\"EventType\":\"{0}\",\"OrganizationId\":\"{1}\",\"Timestamp\":{2},\"ExecutionTime\":{3},\"Success\":{4}}}",
            telemetryEvent.EventType ?? "null", telemetryEvent.OrganizationId ?? "null", telemetryEvent.Timestamp,
            telemetryEvent.ExecutionTime, telemetryEvent.Success)
        .Replace("\"null\"", "null");
    

    You can see a live demo on rextester.