Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a string into Guid in VB.Net

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

like image 359
Scott Selby Avatar asked Jul 10 '12 02:07

Scott Selby


1 Answers

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

like image 91
Claudio Redi Avatar answered Sep 24 '22 19:09

Claudio Redi