You can use Guid.TryParse
.
string[] guids = { "cd334e7e-7370-4d2f-8276-25d08e582da7", "Foo" };
Guid newGuid;
foreach (string guidString in guids)
{
if (Guid.TryParse(guidString, out newGuid))
Console.WriteLine("Converted {0} to a Guid", guidString);
else
Console.WriteLine("Unable to convert {0} to a Guid", guidString);
}
Output:
Converted cd334e7e-7370-4d2f-8276-25d08e582da7 to a Guid
Unable to convert Foo to a Guid
Edit: "What I need is not to test if a Guid is valid or not but if I am able to create an invalid one and pass it as method argument in a Unit Test for example."
So you need to find a way to pass an "invalid" Guid
to a method. I would suggest to use a Nullable<Guid>
instead.
public static void Foo(Guid? guid)
{
if (guid.HasValue)
{
Guid g = guid.Value;
// ...
}
else
{
// ...
}
}
Now you can use this method in these ways:
Foo(null); // will be a Guid? without a value
Foo(new Nullable<Guid>()); // will be a Guid? without a value
Foo(Guid.NewGuid());
Foo(Guid.Empty);
Foo(guidVariable);