How To Use Null ?

  • Thread starter Thread starter Miha Markic [MVP C#]
  • Start date Start date
Hi Tiraman
i would like to init an integer param to Null

dim x as integer
x = null

x = 0

When you did mean to set the reference from the integer to null, that is
impossible because it is a value not a referenced type.

I hope this helps?

Cor
 
Hi ,

i would like to init an integer param to Null

dim x as integer
x = null

how can this be done ?
 
Hi,

You cannot set integer variable to Null, but if you need to assign Null to
the field in a dataTable, then you could do this. It would look like

MyDataTable.Rows(0).Item("MyColumnName")=DbNull.Value
 
As the others mentioned, int is a value type and won't ever be 'null' or
'nothign'. However, if you are talking about a Db Parameter of type int ie
cmd.Paraemters.Add("@MyIntParam", SqlDbType.Int, 4). Value = whatever then
set whatever to DbNull.Value

This is a very important distinction and here's why. Let's say that you set
it to an actual Null value and the procedure was expecting the Parameter
@MyIntParam. SO you have an object and it has a propety which is
unintialized so it's null and you try to reference it (This is rally wrong
on purpose):
private static DataRow dr;

// private int someInt;

public static DataRow SomeValue

{


get{return dr;}

}

SqlConnection cn = new SqlConnection("");

SqlCommand cmd = new SqlCommand("cawead", cn);

cmd.Parameters.Add("@SoemParam", SqlDbType.Int, 4).Value = Test.SomeValue;



You are going to have some problems (assume the connection string and all
that jazz was good. The thing is that it's expecting a value, and since
it's Null (Nothing in VB.NET ) in the .NET Sense vs. the Database sense,it
thinks the value wasn't sent it. On the other hand, If you send in
DbNull.Value, it knows you sent something in, a DbNull value which is in
fact Nothing in the DB but something in .NET.

That may sound like parsing words, but it's much different b/c in one case
you'll get the behavior you want, (you sent in a parameter as expected, the
paramter was a Null in the Database sense so it can change the DB field to
null or do a check against it) in the other hand it thinks you forgot to
give it something it expected and blows up.



HTH,



Bill
 
Back
Top