Last post Aug 09, 2007 11:37 PM by David Anton
Aug 09, 2007 10:45 PM|sun21170|LINK
Normally in VB.Net if I pass an integer parameter as 'Nothing', then in the
called method this parameter is automatically set to zero. I want it to remain null so I can use the following code as it seems more intuitive than checking for 0 value:
if moduleId is nothing then
'Do some processing here
In C#, I guess we can declare the parameter as int? moduleId and it can then be checked for null value.
Aug 09, 2007 11:15 PM|Scott Mitchell|LINK
The int? in C# is an example of using nullable types, which are a feature new to .NET 2.0. The ? is just syntactic sugar in the C# language.
While VB lacks this syntactic sugar, you can still make use of the nullable types concept - you just have to write a bit more code:
Dim moduleId as Nullable(Of Integer)
I'm not a VB programming, so I don't know off the top of my head if you can compare it to Nothing to see if it has no value, but I know you can do:
If Not moduleId.HasValue Then ...
Aug 09, 2007 11:18 PM|ghinx|LINK
In VB.NET 0 is also treated as nothing. So even if you pass in 0 you can still compare it agaisnt nothing or vice versa.
Aug 09, 2007 11:20 PM|drazz75|LINK
If you are using .NET 2.0 you can use nullable types. All you have to do is declare you int as int? instead. The nullable type will give you some extra properties you don't have with a strict value type. For instance you can do the following:
int? mID = null;
If you aren't using .NET 2.0 then you can use the MinValue of whatever value type you are using. Technically there is a risk that the following method is unsafe code (because perhaps your ID value could equal the MinValue of the type), but in most cases
int mID = int.MinValue;
if(mID != int.MinValue)
Aug 09, 2007 11:37 PM|David Anton|LINK
Note that "Nothing" in VB means much more than "null" in C#.
I think what you're looking for is just:
"If moduleId = Nothing Then" (instead of "If moduleID Is Nothing Then")
Testing for equality with Nothing for value types is done with the "=" operator. This tests that the value type variable is set to it's default value. Note that you can only do this in C# with nullable types. True, you can use "Nullable(Of Integer)" in
VB 2005 or "Integer?" in 2008, but I think you're just needing the simpler "= Nothing" test (which has been available in VB for years).