Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of C#'s `default` in VB.NET?

I'm normally at home in C#, and I'm looking at a performance issue in some VB.NET code -- I want to be able to compare something to the default value for a type (kind of like C#'s default keyword).

public class GenericThing<T1, T2>
{
    public T1 Foo( T2 id )
    {
        if( id != default(T2) ) // There doesn't appear to be an equivalent in VB.NET for this(?)
        {
            // ...
        }
    }
}

I was led to believe that Nothing was semantically the same, yet if I do:

Public Class GenericThing(Of T1, T2)
    Public Function Foo( id As T2 ) As T1
        If id IsNot Nothing Then
            ' ...
        End If
    End Function
End Class

Then when T2 is Integer, and the value of id is 0, the condition still passes, and the body of the if is evaluated. However if I do:

    Public Function Bar( id As Integer ) As T1
        If id <> Nothing Then
            ' ...
        End If
    End Function

Then the condition is not met, and the body is not evaluated...

like image 517
Rowland Shaw Avatar asked Jan 20 '11 17:01

Rowland Shaw


People also ask

What is the C equivalent of a class?

There is nothing equivalent to classes . Its a totally different paradigm. You can use structures in C. Have to code accordingly to make structures do the job.

What is the equivalent of string in C?

There is no string type in C . You have to use char arrays.

Is C+ the same as C?

The main difference between C and C++ is that C++ is a younger, more abstract language. C and C++ are both general-purpose languages with a solid community. C is a lightweight procedural language without a lot of abstraction. C++ is an object-oriented language that provides more abstraction and higher-level features.


1 Answers

Unlike C#, VB.NET doesn't require a local variable to be initialized with an expression. It gets initialized to its default value by the runtime. Just what you need as a substitute for the default keyword:

    Dim def As T2    '' Get the default value for T2
    If id.Equals(def) Then
       '' etc...
    End If

Don't forget the comment, it is going to make somebody go 'Huh?' a year from now.

like image 194
Hans Passant Avatar answered Sep 25 '22 03:09

Hans Passant