38

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".

2
  • There's also the following problem: If .Text is a property (i.e. a call to a get accessor), the first time the getter is called, it may return a long string, say "John Doe". The we get to evaluate the last "component" of the ternary ?: conditional operator. But this calls the Text getter again, and this time it may return "". So in priciple you have to take a local variable copy of Text. This is not necessary, of course, if you use an extension method. Commented Dec 7, 2012 at 22:18
  • If you use an extension method, you can Trim() the string first before checking, which is hard to do in the single expression. Commented Nov 4, 2015 at 15:43

6 Answers 6

39

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i explictly wrote I know this can be solved by Extension methods - and i know how to do it.. - is there anything better
oops, didn't see that part :) But i don't see a more elegant way.
Even though he said he knew, this is probably the best way instead of a whole bunch if ifs
12

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.

3 Comments

Hehe, if you place this method in a static class, and use the this keyword, you could use it like an extension method ;) - Much shorter to write
you could at least make it an extension method, no?
Of course you can make an extension method but I don't really like it, especially on null references. Personal choice.
10

Is there anything built-in to C# that lets me do this a shorter way

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.

3 Comments

@Royi oh sure, the conditional is a bit ugly there... funny thing, though; I'd say that if you use "" to mean null, then there's already a problem - i.e. why are you holding a "" if you mean null? use a null to mean null, and a "" to mean "", and the problem you are trying to solve ceases to exist
im not holding "" - the property tbCustomer.Text is ""...... ( and not null)
@Royi so why does your database-related code know about what appears to be a UI control (tbCustomer)? Meh, no matter. Another approach you could use, if orchestrated more cleanly, would be to have a property on an object: public bool HasWhatever { get { return !string.IsNullOrEmpty(Whatever);} } then you can use a conditional on that, i.e. object val = obj.HasWhatever ? obj.Whatever : DBNull.Value; - just a thought
0

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 (e.g. 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).

Comments

0

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; }
    }
}

Comments

-1

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);

1 Comment

OP said they don't want an extension method, and there are already multiple answers that provide extension methods anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.