Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function to convert null to string

Tags:

c#

asp.net

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.

like image 783
James Andrew Smith Avatar asked Sep 06 '12 13:09

James Andrew Smith


People also ask

How do you convert to null?

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.

Can null convert to string in Java?

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.

What is null ToString ()?

ToString(null) returns a null value, not an empty string (this can be verified by calling Convert.


2 Answers

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;   } 
like image 52
Gareth Wilson Avatar answered Sep 19 '22 11:09

Gareth Wilson


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(); 
like image 29
Icarus Avatar answered Sep 21 '22 11:09

Icarus