Cast null values

I have a query in my TableAdapter that returns a decimal type, but can have also return a null value.

How can I assing a 0 if it returns a null value?

My actual code is:



decimal idUsuario;
idUsuario = (decimal)queriesTableAdapter.GetIdUsuarioByUsuario(Usuario)

and it fails if a null value is returned.

I have test this code and it works:



if (queriesTableAdapter.GetIdUsuarioByUsuario(Usuario) == DBN­ull.Value)
idUsuario = 0M;
else
idUsuario = (decimal)queriesTableAdapter.GetIdUsuarioByUsuario(Usuario);

but I'm lokking for a better method because this execute the query 2 times.

[1196 byte] By [AlexBibiano] at [2007-12-16]
# 1

you can prevent the double execution of your query by assigning its value to a temporary variable and compare it to DBNull.Value only once.

object
TempIdUsuarioByUsuario = queriesTableAdapter.GetIdUsuarioByUsuario(Usuario);

decimal idUsuario;

idUsuario = TempIdUsuarioByUsuario == DBNull.Value ? 0M : (decimal) TempIdUsuarioByUsuario;

FadiToutayo at 2007-9-8 > top of Msdn Tech,Visual C#,Visual C# General...
# 2
if you are using C# 2.0 you can use Nullable types!

decimal? userID = queriesTableAdapter.GetIdUsuarioByUsuario(Usuario);

note the special ? after the decimal data type - this declares the variable to be nullable so the variable can either have a decimal value or hold null.

SaurabhNandu at 2007-9-8 > top of Msdn Tech,Visual C#,Visual C# General...
# 3
hmm
wacko at 2007-9-8 > top of Msdn Tech,Visual C#,Visual C# General...