Pergunta

No servidor SQL, você pode usar o IsNull() Função para verificar se um valor é nulo e, se for, retorne outro valor. Agora estou me perguntando se há algo semelhante em C#.

Por exemplo, eu quero fazer algo como:

myNewValue = IsNull(myValue, new MyValue());

ao invés de:

if (myValue == null)
  myValue = new MyValue();
myNewValue = myValue;

Obrigado.

Foi útil?

Solução

É chamado de coalescência nula (??) Operador:

myNewValue = myValue ?? new MyValue();

Outras dicas

Sadly, there's no equivalent to the null coalescing operator that works with DBNull; for that, you need to use the ternary operator:

newValue = (oldValue is DBNull) ? null : oldValue;

Use the Equals method:

object value2 = null;
Console.WriteLine(object.Equals(value2,null));
public static T isNull<T>(this T v1, T defaultValue)
{
    return v1 == null ? defaultValue : v1;
}

myValue.isNull(new MyValue())

For working with DB Nulls, I created a bunch for my VB applications. I call them Cxxx2 as they are similar to VB's built-in Cxxx functions.

You can see them in my CLR Extensions project

http://www.codeplex.com/ClrExtensions/SourceControl/FileView.aspx?itemId=363867&changeSetId=17967

You Write Two Function

    //When Expression is Number
    public static double? isNull(double? Expression, double? Value)
    {
        if (Expression ==null)
        {
            return Value;
        }
        else
        {
            return Expression;
        }
    }


    //When Expression is string (Can not send Null value in string Expression
    public static string isEmpty(string Expression, string Value)
    {
        if (Expression == "")
        {
            return Value;
        }
        else
        {
            return Expression;
        }
    }

They Work Very Well

I've been using the following extension method on my DataRow types:

    public static string ColumnIsNull(this System.Data.DataRow row, string colName, string defaultValue = "")
    {
        string val = defaultValue;
        if (row.Table.Columns.Contains(colName))
        {
            if (row[colName] != DBNull.Value)
            {
                val = row[colName]?.ToString();
            }
        }
        return val;
    }

usage:

MyControl.Text = MyDataTable.Rows[0].ColumnIsNull("MyColumn");
MyOtherControl.Text = MyDataTable.Rows[0].ColumnIsNull("AnotherCol", "Doh! I'm null");

I'm checking for the existence of the column first because if none of query results has a non-null value for that column, the DataTable object won't even provide that column.

Use below methods.

    /// <summary>
    /// Returns replacement value if expression is null
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="replacement"></param>
    /// <returns></returns>
    public static long? IsNull(long? expression, long? replacement)
    {
        if (expression.HasValue)
            return expression;
        else
            return replacement;
    }

    /// <summary>
    /// Returns replacement value if expression is null
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="replacement"></param>
    /// <returns></returns>
    public static string IsNull(string expression, string replacement)
    {
        if (string.IsNullOrWhiteSpace(expression))
            return replacement;
        else
            return expression;
    }

This is meant half as a joke, since the question is kinda silly.

public static bool IsNull (this System.Object o)
{
   return (o == null);
}

This is an extension method, however it extends System.Object, so every object you use now has an IsNull() method.

Then you can save tons of code by doing:

if (foo.IsNull())

instead of the super lame:

if (foo == null)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top