tags:

views:

70

answers:

7

I'm a C# programmer but am converting some code from C# to VB.NET. In c# I can simply use (int)blah.getValue() where getValue() returns an Integer?

Doing a DirectCast() in VB.NET doesn't work though, saying Integer? cannot be converted to Integer.

Ideas?

A: 

You should use CType function like this:

CType(blah.getValue(), Integer)
Restuta
A: 

Integer? is a nullable type, so you may have to convert it to a nullable Integer.

You want to use CType function like so, 'Integer' or 'Integer?' Depending on your situation

Val = CType(Source,Integer?)
Pino
CType sorted it with just Integer. Thanks!
SLC
-1 This answer is not totally correct. There's a different behaviour for null. `(int) blah.getValue()` throws an exception if `blah.getValue()` is null. `CType(blah.getValue(), Integer)` returns zero if `blah.getValue()` is null.
MarkJ
+1  A: 

Use the value property to get the actual integer value.

Dim intNullable As Integer?

If intNullable.HasValue Then
 Return intNullable.Value
End If
Rhapsody
+1. For bonus marks, add an Else clause that throws `InvalidOperationException "Nullable object must have a value."` That's what happens when the C# `(int)` cast encounters a `null` value.
MarkJ
A: 

dim a as integer? = 1 dim b as integer = a.value remember to check if a.hasvalue ( returns boolean, true if a has value)

Sami Männistö
A: 
myNonNullableVar = if(myNullableVar, 0)

will set 0 if integer? is null or return the actual value

in c# it would be

 myNonNullableVar = myNullableVar ?? 0;
Fredou
A: 

CInt(ValueToBeInteger)

Amy
A: 

Converts 'Nullable Integer' to 'Integer'. Replaces missing value with zero if 'blah' has not been initialized.

Dim i As Integer = If (blah IsNot Nothing, blah.value, 0)
Paul Williams