28

How i can compare type data type in VB.NET? My code:

Private Function Equal(ByVal parameter As String, ByVal paramenterName As String, ByVal dataType As Type) As String

    If dataType = String Then
        return 1;
    End If

 End Function

Any ideas?

1
  • Can you choose a different answer as the selected answer you chose has a syntax error in vb.net? Commented Apr 15, 2017 at 2:36

4 Answers 4

29
If dataType = GetType(String) Then
    return 1
End If
3
  • 3
    I got a compile error when trying this in VS 2013 Express - the below suggestion to use "type Is GetType()" worked for me, though. Commented Jan 28, 2015 at 20:58
  • 3
    Hi Darin, your solution appears to no longer be valid in VB.NET. As the accepted answer, can you please update it, so that it remains valid?
    – Sheridan
    Commented Oct 27, 2015 at 11:10
  • Syntax error. Should not have semi colon but StackOverflow's ridiculous rules won't let you edit one character in an invalid answer. Commented Apr 15, 2017 at 2:11
25
If datatype Is GetType(String) Then
    'do something
End If

Substitute Is for = and everything works

18

The accepted answer has a syntax error. Here is the correct solution:

If dataType = GetType(String) Then
    Return 1
End If

Or

 If dataType.Equals(GetType(String)) Then
      Return 1
 End If

Or

 If dataType Is GetType(String) Then
     Return 1
 End If

The last way is probably the best way to check because it won't throw an exception if the object is null.

Also see https://msdn.microsoft.com/en-us/library/system.object.gettype(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

1

This is probably the best way to do it in VB.

If dataType Is String Then
    return 1
End If
3
  • 1
    This will not work. You have to use GetType(String), because the Is operator compares two objects and String is a type not an object.
    – Marcell
    Commented Sep 4, 2017 at 10:56
  • 3
    If TypeOf dataType is String
    – nh32rg
    Commented Nov 10, 2018 at 17:52
  • TypeOf dataType won't work, because it returns Type, not String. dataType Is GetType(String) is the correct way to check the type, as mentioned in the other answers. Commented May 27, 2022 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.