-2

Please see the code below:

public class Service : IService
    {
        private readonly Guid _id = new Guid("5C60F693-BEF5-E011-A485-80EE7300C692");
    }

Notice that I have just hardcoded a Guid. Is there a way to generate a Guid ensuring it is the same every time? Therefore in the case of the above, then every time an instance of Service is created, then _id is always the same.

I have spent time Googling this and I have found lots of other questions, which talk about generating GUIDs and how you can be confident that there will be no collisions. I guess I am asking the opposite to this.

w0051977
  • 15,099
  • 32
  • 152
  • 329
  • Guids are meant to be unique. – Dimitar Mar 12 '19 at 12:04
  • 5
    *Is there a way to generate a Guid ensuring it is the same every time.*: But you're already doing this, the GUID will already always be the same... – sloth Mar 12 '19 at 12:04
  • 4
    What's wrong with hard-coding it? How is that not making sure that "it's the same every time"? – canton7 Mar 12 '19 at 12:05
  • It just doesn't seem to be a particularly elegant way of doing it in terms of readibility. I have already had one developer ask why this service has that specific Guid. I had to explain that it is just a random number I created. – w0051977 Mar 12 '19 at 12:06
  • you want a constant, you have a readonly which you initialize to a constant value, that's as close as it gets. just fine, where's the problem? Microsoft Visual Studio (and probably other IDEs too), have the "Tools > Create GUID" menu item mainly for this reason - to create this kind of identifiers – Cee McSharpface Mar 12 '19 at 12:07
  • 5
    I think it's probably time to add a comment... https://xkcd.com/221/ . – canton7 Mar 12 '19 at 12:07
  • @w0051977 then add a comment what it's for – Biesi Mar 12 '19 at 12:07
  • You can pass your guid in web.config file and read it from there. But it is not very different then hard coding. It only helps finding the guid what you set and where you set when needed – Serhat Oz Mar 12 '19 at 12:07
  • 2
    (If you do `private static readonly Guid _id = Guid.NewGuid()` then you'll get a Guid which remains constant within a given AppDomain, but it will change every time your application starts. If you need it to be constant across application restarts, then you need to hard-code it, which is what you've done) – canton7 Mar 12 '19 at 12:08
  • Maybe you can try another identifier to serve the permanent purpose. – Yarl Mar 12 '19 at 12:11
  • 1
    `It just doesn't seem to be a particularly elegant way of doing it in terms of readibility. I have already had one developer ask why this service has that specific Guid. I had to explain that it is just a random number I created.` Let's say you **didn't** use a readonly Guid - like you currently are. You use some other (as yet unspecified) solution. Do you think that other developer would **still** have to asked you why you did it? _I fail to see how **any solution** would be more effective than what you have now and a comment next to it explaining what you have done **and why you did it**._ – mjwills Mar 12 '19 at 12:12
  • If you want a unique value for identifying your service, why you don’t store the Id in an config-file. Then you could get it every Time the service starts. And you could give another instance of your service a different id through the config. – Nikolaus Mar 12 '19 at 12:28
  • Should it be a static field bearing in mind that I am trying to follow ddd and tdd? Should it be configurable? – w0051977 Mar 12 '19 at 13:17
  • Well you're ignoring the fact that a GUID was designed to be as unique as possible, that said, it makes no sense to generate them as a non-unique variant. However if you're gonna need a specific GUID each time your app runs for a specific configuration then you should store those generated GUIDs somewhere (hard-coding, file, database, etc.) and read it again on app start. I also would rather create a custom function that generates your key related to some data (like hashs) that always output the same id for the same setup. – DanielD Oct 22 '21 at 11:56

2 Answers2

0

Try adding an XML comment, and maybe use a more descriptive name for the variable.

public class Service : IService
{
    /// <summary> This is the unique ID for this service. It will never change. </summary>
    private readonly Guid _id = new Guid("5C60F693-BEF5-E011-A485-80EE7300C692");
}

The XML Comment will show up in IntelliSense.

Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
-2

I found it extremely amusing to read the confused comments and answers from our cybernetic friends -- who genuinely didn't get the question, because it was written using vague, human being wording.

Now having said that, it is perfectly valid to advocate for hard-coding the Guid. Guids should be random, by definition I will just answer the question technically, without questioning its underlying choice.

What @w0051977 wanted (paraphrased)

Guid g = MySeededGuidGenerator.CreateGuid(); // Generates the same sequences of Guids each time the program runs

Implementation

    public static class MySeededGuidGenerator {

        private static int sequence;

        public static Guid CreateGuid() {
            using (MD5 md5 = MD5.Create()) {
                byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes($"{sequence++}"));
                return new Guid(hash);
            }
        }
    }

Note: You might get warnings that md5.ComputeHash is unsafe cryptography, but here we use it as a cheap way of generating a Guid from a string, not in any security-oriented way. Therefore it doesn't matter, because it is accepted that anyone who would want a program where the Guids are not randomized (but instead always the same) has no concern for security. My guess is that it's just for mass-seeding a test environment in a deterministic manner.

Output :

(start program)

var guid1 = MySeededGuidGenerator.CreateGuid();
var guid2 = MySeededGuidGenerator.CreateGuid();
var guid3 = MySeededGuidGenerator.CreateGuid();

(stop program) (run program again)

var guid1 = MySeededGuidGenerator.CreateGuid();
var guid2 = MySeededGuidGenerator.CreateGuid();
var guid3 = MySeededGuidGenerator.CreateGuid();

Success! The values of guid1, guid2 and guid3 were identical (respectively) the second time to the first time.

jeancallisti
  • 1,046
  • 1
  • 11
  • 21