Why this code is everytime generating 0000-0000 as guid?
static int Main(string[] args)
{
Guid obj = new Guid();
Console.WriteLine("New Guid is " + obj.ToString());
Console.ReadLine();
}
Why this code is everytime generating 0000-0000 as guid?
static int Main(string[] args)
{
Guid obj = new Guid();
Console.WriteLine("New Guid is " + obj.ToString());
Console.ReadLine();
}
You have to do following to get new Guid.
Guid.NewGuid()
By default it is blank.
new Guid();
This just instantiates a new structure of Guid. It doesn't generate any values for it.
From the MSDN docs:
Initializes a new instance of the Guid structure.
To get a new GUID each time with a new value:
Guid.NewGuid();
To test whether you have a new Guid or not, you can use the Guid.Empty
if (myGuid == Guid.Empty())
Aside
Here's another interesting snippet, I've been told for value types to always use ==
to do equality comparing, and for reference types you can do .Equals()
. However, looking under the hood of the Guid implementation, it seems very safe to use .Equals()
:
public bool Equals(Guid g)
{
// Now compare each of the elements
if(g._a != _a)
return false;
if(g._b != _b)
return false;
if(g._c != _c)
return false;
if (g._d != _d)
return false;
if (g._e != _e)
return false;
if (g._f != _f)
return false;
if (g._g != _g)
return false;
if (g._h != _h)
return false;
if (g._i != _i)
return false;
if (g._j != _j)
return false;
if (g._k != _k)
return false;
return true;
}
I don't know about anyone else, I've always been interested in whether you should do ==
or .Equals()