Question

Can somehow an invalid System.Guid object be created in .Net (Visual Basic or C#). I know about Guid.Empty method but it is not what I am searching for. For example with invalid symbols or spaces or being too short or longer than an valid one etc. Thanks!

Was it helpful?

Solution

Can a Guid be created with invalid symbols or spaces or being too short or longer than an valid one etc?

No - a Guid is just a 128-bit number that can be represented in 5 groups of hexadecimal numbers. There's no way for the string representation of a Guid to contain anything other than 32 hex characters (and possibly 4 hyphens or a few other formatting characters).

You can create a string that does not represent a valid Guid, but there's no way to put that into a Guid object.

OTHER TIPS

What does invalid mean to you? That's defined by what your code can deal with. A Guid is just 16 arbitrary bytes without any mandatory format. You define what kinds of Guid you want to accept.

In that sense any Guid object is valid by itself. There's no invalid state for this struct.

It is like an int. Any int is valid.

You should be able to do this using the constructor for Guid:

Guid badGuid = new Guid("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");

If this throws an exception then it means the runtime will not allow you to construct an invalid Guid, and you don't need to test for that scenario. Note that according to the docs it must be given the correct number of characters, so that case is definitely not testable. On a different note, are you sure you're testing the behavior of your code, because it sounds like you're trying to write tests for extremely specific framework features which is not the purpose of unit testing your code.

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top