NibblyPig
NibblyPig

Reputation: 52932

How do I convert an Integer? to an Integer in VB.NET?

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?

Upvotes: 9

Views: 21905

Answers (8)

LeoRocks
LeoRocks

Reputation: 1

@SLC: It is very simple to get values of Nullable Int32? of C# into Integer.

Example:

    ID(Nullable<Int32?>)

You have to do: ID.value

where ID is a NullableObject.

And it will return an integer in VB.NET.

Upvotes: -1

Fredou
Fredou

Reputation: 20100

myNonNullableVar = if(myNullableVar, 0)

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

In C#, it would be:

 myNonNullableVar = myNullableVar ?? 0;

Upvotes: 1

dim a as integer? = 1
dim b as integer = a.value

Remember to check if a.hasvalue (returns boolean, true if a has value).

Upvotes: 0

ulty4life
ulty4life

Reputation: 3012

If you use CType or CInt or another conversion function to convert the nullable integer to a regular integer, a null value will be converted to zero.

Check to see if the nullable type has a value as in @Rhapsody 's answer.

You can also use the nullable type methods .GetValueOrDefault() and .GetValueOrDefault(x). The overload without any parameters returns the default value of the datatype if the value is null. E.g. Integer default value is zero; Boolean default value is False. The overload with a parameter allows you to specify a default value to use if the value is null.

Nullable.GetValueOrDefault Method

Upvotes: 1

Amy
Amy

Reputation: 132

CInt(ValueToBeInteger)

Upvotes: 1

Rhapsody
Rhapsody

Reputation: 6077

Use the value property to get the actual integer value.

Dim intNullable As Integer?

If intNullable.HasValue Then
 Return intNullable.Value
End If

Upvotes: 11

LiamB
LiamB

Reputation: 18586

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?)

Upvotes: 9

Restuta
Restuta

Reputation: 5903

You should use CType function like this:

CType(blah.getValue(), Integer)

Upvotes: 0

Related Questions