Creating a new Value Type for hiding creation of Guid's

G

Guest

I want to create a new value type for hiding the creation of Guid's that can
be used in my business classes. I suppose I have to achieve this by creating
a struct (ID)
The problem is I'm completely stuck as how to develop my struct. Anyone can
help?
Thanks.

e.g.

class Person
{
ID PersonID; // ID is the struct
string FirstName;
string LastName;
Person()
{
this.ID = ID.new(); // Calling the static method of the struct ID, with
the purpose of getting a Guid
...
}
...
}

struct ID
{
...
public static ??? new()
{
???
}
}
 
J

Jon Skeet [C# MVP]

Guy said:
I want to create a new value type for hiding the creation of Guid's that can
be used in my business classes. I suppose I have to achieve this by creating
a struct (ID)
The problem is I'm completely stuck as how to develop my struct. Anyone can
help?

Well, you can't create a method called "new" in C# (you could use @new,
but it's really not a good idea).

Instead, you should create a factory method which calls a constructor
and does whatever is required. For instance:

using System;

struct ID
{
Guid guid;

public Guid Guid
{
get { return guid; }
}

public static ID CreateID()
{
ID id = new ID();
id.guid = Guid.NewGuid();
return id;
}
}

public class Test
{
static void Main()
{
ID id = ID.CreateID();
Console.WriteLine (id.Guid);
id = ID.CreateID();
Console.WriteLine (id.Guid);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top