Cast a string into Guid in VB.Net

19,137

Try with this

Dim UserID As New Guid()
If HttpContext.Current.Session("UserID") IsNot Nothing Then
    UserID = Guid.Parse(HttpContext.Current.Session("UserID").ToString())
End If

Just in case you're confused, take into account that, unless my memory is failing, Guid contructor will generate an "empty" guid. If you want to generate a fresh guid use Guid.NewGuid()

Share:
19,137
Scott Selby
Author by

Scott Selby

I make websites , mostly in c#

Updated on June 04, 2022

Comments

  • Scott Selby
    Scott Selby almost 2 years

    I have the Guid "UserID" , it needs to be filled with Session("UserID") which is a String , but formatted to convert perfectly to a Guid.

    If I try this , "Cannot Convert type string into type Guid"

           Dim UserID As New Guid()
           If HttpContext.Current.Session("UserID") IsNot Nothing Then
              UserID = HttpContext.Current.Session("UserID")
           End If
    

    If I try this "Cannot Cast type string into type Guid"

           Dim UserID As New Guid()
           If HttpContext.Current.Session("UserID") IsNot Nothing Then
              UserID = DirectCast(HttpContext.Current.Session("UserID"), Guid)
           End If
    

    This converts the string into Guid perfectly , but it is not accessable outside of the If Statement

           If HttpContext.Current.Session("UserID") IsNot Nothing Then
             Dim UserID As new Guid(HttpContext.Current.Session("UserID"))
           End If
    

    I can not figure out how to define UserID outside of the If statement , then assign it conditionally