GUID for Random Unique ID (C#)


GUIDcan be used for random unique IDs. The chances of collisions are rare and that can be ignored. So instead of using Random() class to generate random characters/integers and check them each time in a global List structure, you can simply use GUID to generate random strings. The following is a quick C# example that declares a public get property (you can’t and don’t need to set the property for GUID).

1
public string ID { get { return Guid.NewGuid().ToString();} }
public string ID { get { return Guid.NewGuid().ToString();} }

You can also return the structure-type Guid.

1
public GuidID { get { return Guid.NewGuid();} }
public GuidID { get { return Guid.NewGuid();} }

Less is more! I believe this can simplify your design in the application.

Update: Careful with the code above – you will be creating a new guid on every get so the Id will constantly change! You should use a private backing property or else use a private setter to create a new guid in the constructor.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
229 words
Last Post: Avoid Magic String Constants in C# Using Reflection
Next Post: The IT interviews differences between UK and USA

The Permanent URL is: GUID for Random Unique ID (C#)

Leave a Reply