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?