简体   繁体   中英

In C#, how can I generate a value for a class property only if there isn't one?

I have the following C# class with a property Id which I would like to set with a GUID and return if the consumer calls the value of an instance of myClass.Id for which this value has not yet been set, but otherwise to keep and return the existing value.

public class IdentifiableClass{
   public string Id {
          get { 
                if (this.Id == null) {
                    this.Id = Guid.NewGuid().ToString();
                    Console.WriteLine("########## Id : " + this.Id );
                }
                return this.Id;
            }
            set => this.Id = value;
   }
}

In C# , this does not work, but rather I get a stackoverflow (not this site, obviously). Best guess, invoking this.Id within the same property's getter seems to resulting in circular logic.

In Salesforce Apex , with this similar code, it does work as I would expect it to, evaluating the value of this.Id as null, assigning the value to the new Guid, displaying the value, and then returning the value:

public class IdentifiableClass {
   public string Id {
          get { 
                if (this.Id == null) {
                    this.Id = String.valueOf(Integer.valueof((Math.random() * 10)));
                    System.debug('########## Id : ' + this.Id );
                }
                return this.Id;
            }
            set;
   }
}
  • Is it possible to make this work in C# ?
  • If so, how ?

Probably you should create full property with private field.

public class IdentifiableClass{
   private string id;
   public string Id {
          get { 
                if (this.id == null) {
                    this.id = Guid.NewGuid().ToString();
                    Console.WriteLine("########## Id : " + this.id );
                }
                return this.id;
            }
            set => this.id = value;
   }
}

What you need to do is not to use auto-property feature.

You should put explicitly private string _id; field and your getters and setters should internaly use that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM