Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check for invalid guid parameter passed in

Tags:

c#

guid

I am trying to create some test data and i want to return and error message to the user that the passed in guid is not in valid format - an example of how this could be applied will be great

proper guid format that i am using:

Guid user = new Guid("FF2214F8-5393-4B5A-B1CA-3620F85D9131");

invalid guid that i pass in to test and would like to return a message to the user to notify rather than breaking:

Guid user2 = new Guid("UserName");

method i use to pass in:

public void UserName(user2)
{
....  
}
like image 625
Masriyah Avatar asked Dec 11 '22 16:12

Masriyah


1 Answers

If I understand correctly user2 is the Guid you want to test, if so try Guid.TryParse:

   Guid result;
    if(Guid.TryParse(user2, out result))
    {
    //success (result variable has been assigned the Guid value)
    }
    else
    {
    //error
    }

Edit: According to your comments, I understand that the problem is that you are passing that method an invalid Guid, so the exception happens when you create the variable that you are going to pass to the method as parameter. Does this helps?

Guid user2; 
if(Guid.TryParse("UserName", out user2))
{
 UserName(user2)
}
else
{
//do whatever you need to report the error
}

I'm not sure where do you get "UserName" but the point here is that wherever you are trying to create a Guid from a string and you're not sure if the string is valid you need to use Guid.TryParse method

like image 152
jorgehmv Avatar answered Dec 26 '22 17:12

jorgehmv