I’m new to c# syntax. I wrote the following class (the codebehind for the masterpage of my website):
public partial class MasterPagePro : System.Web.UI.MasterPage
{
public String pageTitle
{
get
{
if (this.pageTitle == null)
return "";
else
return " - " + this.pageTitle;
}
}
}
However, when I try to access pageTitle like this in the html:
<title>MySite<%=pageTitle%></title>
I get a stackoverflow error. Looking at the code, it’s pretty clear that the problem is that the method is calling itself recursively, but I don’t know what to write to resolve this. I could do something like:
public partial class MasterPagePro : System.Web.UI.MasterPage
{
private String _pageTitle
public String pageTitle
{
get
{
if (_pageTitle == null)
return "";
else
return " - " + _pageTitle;
}
set { _pageTitle = value; }
}
}
But that seems to defeat the point of having the syntactic shortcut at all. What is the right way to do this?
In your first example, you’re expecting the compiler to know whether or not you actually meant to recursively call the same property. Since the compiler can’t know your intentions, it will create the code as written, which as you pointed out, leads to a stackoverflow.
The syntatic shortcut is for when you have a simple property with a assigning/returning setter/getter. The compiler creates the backing class member for you, and generates the get/set routines.
For example:
vs
In this case, it is not ambiguous at all what you are trying to do, thus the compiler can help out and auto generate as necessary.
If you need to implement custom setter/getter functionality, that also includes setting a value, you must make use of a backing class member, as you have shown in your 2nd example.