0

Trying to insert GUID as primary key within object get set. In the set section I checked if value==null to determine insert or update.

 public string Id
    {
        get
        {
            return this.Id;
        }
        set
        {
            try
            {
                this.Id = value == null ? this.Id = Guid.NewGuid().ToString("D") : value;
            }
            catch (Exception ex) {
                throw ex;
            }
        }
    }
codegrid
  • 977
  • 2
  • 13
  • 33
  • 1
    `this.Id = value == null ? Guid.NewGuid().ToString("D") : value;` You dont need the 2nd `this.Id = ` – Loocid Oct 04 '18 at 08:09
  • 1
    You have a property ``Id`` and also a backing field ``Id``? It may be legal but I question the readability, you may want to rename the backing field. Furthermore your validation logic is (or may be, depending on your requirements) flawed, it checks for a null string but not whether a non-null string is valid for your use case. – dumetrulo Oct 04 '18 at 08:13
  • @Loocid my bad. thanks – codegrid Oct 04 '18 at 08:16
  • @dumetrulo noted, will make changes. thanks – codegrid Oct 04 '18 at 08:16

2 Answers2

0

The problem comes from the get i'd say, it looks like you're returning Id when you are trying to access the value of Id so it will end up in an infinite loop and cause System.StackOverflowException

EDIT

You could also use the ?? operator to check for null values

Example

public string Id
{
    get
    {
        return this.Id;
    }
    set
    {
        try
        {
            this.Id = value ?? Guid.NewGuid().ToString("D");
        }
        catch (Exception ex) {
            throw ex;
        }
    }
}
nalka
  • 1,894
  • 11
  • 26
0

You cant use the propery within the set or get... this will be an endless loop. You use the property as the backing field.

Just define a backing-field and thats it.

private string id;
public string Id
    {
        get
        {
            return this.id;
        }
        set
        {
            try
            {
                this.id = value == null ? Guid.NewGuid().ToString("D") : value;
            }
            catch (Exception ex) {
                throw ex;
            }
        }
    }
}

Also, notice that like @Loocid commented - while your code will work if you change to backing field, there's no need for the second this.id =

Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27