Home > Software engineering >  How to render optional text in string interpolation
How to render optional text in string interpolation

Time:08-27

I have this which works fine:

var firstName = "Greg";
var ipAddress = "0.0.0.0";

var sql = @$"sp_create_enrollment @first_name = '{firstName}',
        @ip_address = '{ipAddress}'";

Console.WriteLine(sql);

This produces:

sp_create_enrollment @first_name = 'Greg', @ip_address = '0.0.0.0'

However, if ip_address is null, I need it to produce this:

sp_create_enrollment @first_name = 'Greg', @ip_address = null

Note that there are no quotes around the null, otherwise it gets passed as a string.

How do I achieve that?

CodePudding user response:

ipAddress = ipAddress != null ? "'"   ipAddress   "'" : "null";

var sql = @$"sp_create_enrollment @first_name = '{firstName}',
        @ip_address = {ipAddress}";

CodePudding user response:

You can do something like this:

var firstName = "Greg";
string ipAddress = "'0.0.0.0'";

var sql = @$"sp_create_enrollment @first_name = '{firstName}',
        @ip_address = {(string.IsNullOrWhiteSpace(ipAddress) ? "null" : ipAddress)}";

Console.WriteLine(sql);

CodePudding user response:

This is @Maytham's answer slightly modified:

var firstName = "Greg";
string ipAddress = null;

var sql = @$"sp_create_enrollment @first_name = '{firstName}',
        @ip_address = {(string.IsNullOrWhiteSpace(ipAddress) ? "null" : "'"   ipAddress   "'")}";

Console.WriteLine(sql);

For creating SQL Passthrough, my preference is all one statement, but I wouldn't use it in other contexts.

CodePudding user response:

Here is a way to do it with an extension method (as suggested by @Panagiotis Kanavos):

var firstName = "Greg";
string ipAddress = null;

var sql = @$"sp_create_enrollment @first_name = {firstName.QuoteOrDefault()},
        @ip_address = {ipAddress.QuoteOrDefault()}";

Console.WriteLine(sql);

public static string QuoteOrDefault(this string value)
{
    if(value is null)
    {
        return "null";
    }
    else
    {
        return "'"   value   "'";
    }
}
  • Related