Get and install in C #

I am new to C # syntax. I wrote the following class (codebehind for the main page of my site):

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 html:

<title>MySite<%=pageTitle%></title>

I get stackoverflow error. Looking at the code, it’s pretty clear that the problem is that the method calls itself recursively, but I don’t know what to write to solve this problem. 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 it looks like you have a syntax shortcut. What is the right way to do this?

+5
source share
6 answers

, , . , , , , stackoverflow.

- / setter/getter. get/set.

:

class foo {

 public int myInt;

 public int MyInt { get { return myInt;} 
                    set { myInt = value;} }

 }

 class foo {

 public int MyInt { get; set; }

 }

, , .

setter/getter, , , .

+6

, , .

, .

, , .

, :

public string pageTitle{get;set;}

.

+6

, , "" ( ) #, .

+3

, get. ?

. get set, . - - , .

, , -:

public string MyName { get; set; }

get set.

, , , :

  • get set , .. .
  • , (.. , , ).
+1

" " . -,

public String PageTitle {get; ; }

and everything for you, including the support field. The real point of properties is to hide the support field from the executors ... OOP, abstraction and inheritance and all that. Using the property, you can add a confirmation or change the format of its return without having to search for each instance of access to the backup field.

+1
source

In addition, properties (get and set syntax) usually have PascalCase, i.e. PageTitle

+1
source

All Articles