-1

Let's say I have a class of some object representing a Page which has two properties strTitle where the original title is stored and strUrlTitlewhere I want to store the URL friendlz title. I want to assign the strUrlTitleonly when assigning the strTitle therefore I have used the following code.

public class Page
{
    public strUrlTitle {get; private set;}
    public strTitle {
      get
      {
          return strTitle;
      }
      set
      {
          strTitle = value;
          strUrlTitle = HttpUtility.UrlEncode(value.Replace(" ", "-").Trim());
      }
    }
}

But It appears as if when the set method i called and it assigns the strTitle value, the set method is called again and we end up in infinite loop. Hence my question is how to assign both values from one get method?

Thanks

m3div0
  • 1,556
  • 3
  • 17
  • 32

1 Answers1

3

You need to create a backing field. Now your setter and getter call themselves, causing an infinite loop:

private string _title;  
public Title 
{
    get
    {
        return _title;
    }
    set
    {
        _title = value;
        UrlTitle = HttpUtility.UrlEncode(value.Replace(" ", "-").Trim());
    }
}

public UrlTitle { get; private set; }

See also I am getting into infinite loop in property setter and probably many other potential duplicates if you search for "C# property setter infinite loop".

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 2
    It's also worth mentioning that such backing field is created automatically during compilation when one is using shorthand `set;`. After getting so used to the shorthand form I fell into the same problem when I needed a custom setter recently :) – Gerino Dec 08 '14 at 13:31