I want to create a function to convert any null value e.g. from a database to an empty string. I know there are methods such as if value != null ?? value : String.Empty
but is there a way to pass null
to a method e.g.
public string nullToString(string? value) { if(value == null) return empty; return value }
But I am not sure on the parameter syntax to do this..
I tried the above but it says not a nullable type.
Thanks in advance.
Using the Number() Method The Number() method in JavaScript is used to convert a value into a number. If the value is not convertible, then it will return NaN. To convert the null into a Number we pass the "null" as an argument to the Number() method.
Both methods String. valueOf(Object) and Objects. toString(Object) essentially do the same thing: call the toString() method on a passed-in object. This is the case as long as it's not null or it doesn't return the string "null" when null is passed to them.
ToString(null) returns a null value, not an empty string (this can be verified by calling Convert.
static string NullToString( object Value ) { // Value.ToString() allows for Value being DBNull, but will also convert int, double, etc. return Value == null ? "" : Value.ToString(); // If this is not what you want then this form may suit you better, handles 'Null' and DBNull otherwise tries a straight cast // which will throw if Value isn't actually a string object. //return Value == null || Value == DBNull.Value ? "" : (string)Value; }
When you get a NULL value from a database, the value returned is DBNull.Value on which case, you can simply call .ToString()
and it will return ""
Example:
reader["Column"].ToString()
Gets you ""
if the value returned is DBNull.Value
If the scenario is not always a database, then I'd go for an Extension method:
public static class Extensions { public static string EmptyIfNull(this object value) { if (value == null) return ""; return value.ToString(); } }
Usage:
string someVar = null; someVar.EmptyIfNull();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With