GibboK
GibboK

Reputation: 73908

Guid Costructor - How to create a Guid verifying that string passed is in the right format

I use c# asp.net 4.

I need to create a Guid from a String. The String could be in the right format (so a Guid can be created) or in a not accepted format - In this case I need to set a variable isGuid to false.

At the moment I use this approach. As you can see I'm driven logic using a Try Catch.

I would like to know if you know a better way to perform this operation, to be honest I'm not sure if the use or Try Catch is appropriate here.

PS: If you feel the Title of my Q is not appropriate please let me know I will change it. Thanks! PS2: If you know a better form of syntax, let me know I'm pretty new at coding.

  string filename;
   bool isGuid;
   Guid guid;
   try
   {
        guid = new Guid(filename);
        isGuid = true;
   }
   catch
   {
        isGuid = false;
   }
   if(isGuid)
   // Do smt here!

Upvotes: 0

Views: 282

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239636

Guid.TryParse is available from .NET 4:

if (Guid.TryParse(stringGuid, out newGuid))
        Console.WriteLine("Converted {0} to a Guid", stringGuid);

Otherwise (3.5 or earlier), the best I could recommend would be using the code you already have - to avoid an exception, you'd have to implement almost all of the Guid.Parse method anyway.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499740

If you're using .NET 4, you can use Guid.TryParse:

Guid guid;
bool valid = Guid.TryParse(text, out guid);

Upvotes: 4

Related Questions