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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)