简体   繁体   中英

Is there a built-in C# method to go from an empty string to null value?

There are many times in which I have an input text, and, if it's empty (if the user didn't type any text, for example), I want to send a null value to the DB query.

I do not want to send String.Empty. (or "" ).

Thus I find myself doing this a lot:

var mySqlValue =  string.IsNullOrEmpty( tbCustomerId.Text)?null:tbCustomerId.Text;

This seems ugly to me. .NET gives a lot of other solutions for the opposite scenarios:

string.IsNullOrEmpty
string.IsNullOrWhiteSpace
myProblemVal ?? myDefultVal

Is there anything built-in to C# that lets me do this a shorter way, like the opposite direction?

I know this can be solved by writing my own extension methods and I know how to do that; that's not a solution I'm interested in.

I'm looking for some code like " if empty -> null ".

You can use an extension method:

public static class Extensions {
    public static string NullIfWhiteSpace(this string value) {
        if (String.IsNullOrWhiteSpace(value)) { return null; }
        return value;
    }
}

Which you could use like that:

var mySqlValue = tbCustomerId.Text.NullIfWhiteSpace();

I don't really know what you imagine by something better than Extension methods. How do you define "better"? Shorter? Using a special keyword? Using rarely used operators to look clever? This is already just a single method call appended to your value, which even works on null values, and the logic you need can't really be expressed in a shorter way than this. Also, I don't know of any special syntax for it.

but is there anything better ?

No, although I'd argue that what you describe in the question (extension methods) is absolutely fine. And as you describe in the question, in the other direction you have null-coalescing.

Declare your own static method :

public static string NullIfEmpty(string value)
{
  return string.IsNullOrEmpty(value) ? null : value;
}

Doing

MyHelper.NullIfEmpty(value) is not uglier than a call to a static method of string type... And it seems cleaner than writing "string.IsNullOrEmpty( tbCustomerId.Text)?null:tbCustomerId.Text" each time.

Starting with your string

string myString = "";

Write a method that converts blank to null

public static string NullIf(string value)
{
    if (String.IsNullOrWhiteSpace(value)) { return null; }
    return value;
}

Then wrap in the method and call it back with the same syntax you'd expect in SQL

NullIf(myString);

Is it not what you directly asked, but one way to achieve what you are trying to do (pass a null value to SQL for a string if the string's value is empty) is use an if-statement to check the length of the string value being passed during the SQL Query parameter assignment (eg Parameters.AddWithValue("@parameter", mySqlValue) ):

if (mySqlValue.Length > 0) {
    SqlCommand.Parameters.AddWithValue("@mySqlValue", mySqlValue);
}
else {
    SqlCommand.Parameters.AddWithValue("@mySqlValue", DBNull.Value);
}

where SqlCommand is the variable in a using statement that utilizes a parameterized SQL Query and a pre-established SQL connection/connection string.

It's not an elegant solution, but it works (and doesn't require that you write an extension method).

If you want to return an empty string as null automatically when deserializing json:

public partial class MyClass
{
    string sample;
    [JsonProperty("myProperty")]
    public string MyProperty
    {
        get { return sample; }
        set { sample = string.IsNullOrEmpty(value) ? null : value; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM