web-dev-qa-db-fra.com

Une fonction pour convertir null en chaîne

Je veux créer une fonction pour convertir toute valeur nulle, par exemple. d'une base de données à une chaîne vide . Je sais qu'il existe des méthodes telles que if value != null ?? value : String.Empty mais existe-t-il un moyen de passer null à une méthode, par ex.

public string nullToString(string? value)
{
    if(value == null) return empty;
    return value
}

Mais je ne suis pas sûr de la syntaxe des paramètres pour le faire ..

J'ai essayé ce qui précède mais il ne dit pas un type nullable.

Merci d'avance.

17
James Andrew Smith
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;


}
26
Gareth Wilson

Lorsque vous obtenez une valeur NULL d'une base de données, la valeur renvoyée est DBNull.Value. Dans ce cas, vous pouvez simplement appeler .ToString() et il renverra "".

Exemple: 

 reader["Column"].ToString() 

Vous permet d'obtenir "" si la valeur renvoyée est DBNull.Value

Si le scénario n'est pas toujours une base de données, je choisirais une méthode d'extension:

public static class Extensions
{

    public static string EmptyIfNull(this object value)
    {
        if (value == null)
            return "";
        return value.ToString();
    }
}

Usage: 

string someVar = null; 
someVar.EmptyIfNull();
22
Icarus

Convert.ToString(object) convertit en chaîne. Si l'objet est null, Convert.ToString le convertit en chaîne vide. 

Appeler .ToString() sur un objet avec une valeur null génère un System.NullReferenceException .

MODIFIER:

Deux exceptions aux règles:

1) ConvertToString(string) sur une chaîne null retournera toujours null.

2) ToString(Nullable<T>) sur une valeur null retournera "".

Exemple de code:

// 1) Objects:

object obj = null;

//string valX1 = obj.ToString();           // throws System.NullReferenceException !!!
string val1 = Convert.ToString(obj);    

Console.WriteLine(val1 == ""); // True
Console.WriteLine(val1 == null); // False


// 2) Strings

String str = null;
//string valX2 = str.ToString();    // throws System.NullReferenceException !!!
string val2 = Convert.ToString(str); 

Console.WriteLine(val2 == ""); // False
Console.WriteLine(val2 == null); // True            


// 3) Nullable types:

long? num = null;
string val3 = num.ToString();  // ok, no error

Console.WriteLine(num == null); // True
Console.WriteLine(val3 == "");  // True
Console.WriteLine(val3 == null); // False 

val3 = Convert.ToString(num);  

Console.WriteLine(num == null);  // True
Console.WriteLine(val3 == "");  // True
Console.WriteLine(val3 == null); // False
19
live-love

Vous pouvez simplement utiliser l'opérateur de fusion nul.

string result = value ?? "";
12
cadrell0

Il est possible de le rendre encore plus court avec C # 6:

public string NullToString(string Value)
{
    return value?.ToString() ?? "";
}
4
Trojaner

Vous pouvez utiliser Convert.ToString((object)value). Vous devez d'abord convertir votre valeur en un objet, sinon la conversion entraînera la valeur null.

using System;

public class Program
{
    public static void Main()
    {
        string format = "    Convert.ToString({0,-20}) == null? {1,-5},  == empty? {2,-5}";
        object nullObject = null;
        string nullString = null;

        string convertedString = Convert.ToString(nullObject);
        Console.WriteLine(format, "nullObject", convertedString == null, convertedString == "");

        convertedString = Convert.ToString(nullString);
        Console.WriteLine(format, "nullString", convertedString == null, convertedString == "");

        convertedString = Convert.ToString((object)nullString);
        Console.WriteLine(format, "(object)nullString", convertedString == null, convertedString == "");

    }
}

Donne:

Convert.ToString(nullObject          ) == null? False,  == empty? True 
Convert.ToString(nullString          ) == null? True ,  == empty? False
Convert.ToString((object)nullString  ) == null? False,  == empty? True

Si vous passez un System.DBNull.Value à Convert.ToString (), il sera également converti en une chaîne vide.

1
Stephen Turner

Il est possible d'utiliser le "?" (accès de membre conditionnel nul) avec le "??" (opérateur à coalescence nulle) comme ceci:

public string EmptyIfNull(object value)
{
    return value?.ToString() ?? string.Empty;
}

Cette méthode peut également être écrite en tant que méthode d'extension pour un objet:

public static class ObjectExtensions
{
    public static string EmptyIfNull(this object value)
    {
        return value?.ToString() ?? string.Empty;
    }
}

Et vous pouvez écrire les mêmes méthodes en utilisant "=>" (opérateur lambda):

public string EmptyIfNull(object value)
    => value?.ToString() ?? string.Empty;
1
David Orbelian
public string nullToString(string value)
{
    return value == null ?string.Empty: value;   
}
0
Shyju

C'est un sujet ancien, mais il existe une manière "élégante" de le faire ...

static string NullToString( object Value )
{       
    return Value = Value ?? string.Empty;    
}
0
Rogerio Azevedo
 public string ToString(this string value)
        {
            if (value == null)
            {
                value = string.Empty;
            }               
            else
            {
                return value.Trim();
            }
        }
0
Liton

vous pouvez utiliser ?? "" par exemple: 

y=x??""

si x n'est pas nul y = x mais si x est nul y = ""

0
mohammad
 public string ToString(this object value)
{
    // this will throw an exception if value is null
    string val = Convert.ToString (value);

     // it can be a space
     If (string.IsNullOrEmpty(val.Trim()) 
         return string.Empty:
}
    // to avoid not all code paths return a value
    return val;

}

0
Gauravsa