How to convert integer? to Integer in VB.NET?

I am a C # programmer, but I am converting code from C # to VB.NET. In C #, I can just use (int)blah.getValue() , where getValue() returns Integer?

Running DirectCast() on VB.NET does not work, but Integer? cannot be converted to Integer .

Ideas?

+4
source share
8 answers

Integer? is a type with a null value, so you may have to convert it to a null integer.

Do you want to use a CType function, such as "Integer" or "Integer?" Depending on your situation

 Val = CType(Source,Integer?) 
+6
source

Use the value property to get the actual integer value.

 Dim intNullable As Integer? If intNullable.HasValue Then Return intNullable.Value End If 
+7
source

CInt (ValueToBeInteger)

+1
source

You should use CType as follows:

 CType(blah.getValue(), Integer) 
0
source
 dim a as integer? = 1 dim b as integer = a.value 

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

0
source
 myNonNullableVar = if(myNullableVar, 0) 

will set to 0 if an integer? is null or returns the actual value.

In C #, it will be:

  myNonNullableVar = myNullableVar ?? 0; 
0
source

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

Check if the type with a null value has the value specified in @Rhapsody's answer.

You can also use methods like nullable .GetValueOrDefault() and .GetValueOrDefault(x) . Overloading without any parameters returns the default value for the data type if the value is NULL. For instance. The integer default value is zero; The default Boolean value is False. Overloading with a parameter allows you to specify the default value to use if the value is null.

Nullable.GetValueOrDefault Method

0
source

@SLC: Is it really easy to get Nullable Int32 values? from c # to integer.

Example:

  ID(Nullable<Int32?>) 

You need to do: ID.value

where ID is NullableObject.

And it will return an integer in VB.NET.

-1
source

Source: https://habr.com/ru/post/1300725/


All Articles