Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get and set in c#

Tags:

c#

asp.net

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?

like image 426
Oliver Avatar asked Jul 28 '11 16:07

Oliver


People also ask

What is the use of set and get?

The get method returns the value of the variable name . The set method takes a parameter ( newName ) and assigns it to the name variable. The this keyword is used to refer to the current object.

What are get and set properties in C#?

A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.

Is Get set a method?

Getter and Setter are methods used to protect your data and make your code more secure. Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc.

What is get in C#?

The get keyword defines an accessor method in a property or indexer that returns the property value or the indexer element. For more information, see Properties, Auto-Implemented Properties and Indexers. The following example defines both a get and a set accessor for a property named Seconds .


6 Answers

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:

class foo {

 public int myInt;

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

 }

vs

 class foo {

 public int MyInt { get; set; }

 }

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.

like image 147
Alan Avatar answered Sep 30 '22 18:09

Alan


When you use a getter in this way you also need to manually add a field like you have in your second example.

You can't just make reference to the same property as in your first example.

You mention a syntactic shortcut but you're not using a shortcut as far as I can tell.

The shortcut for properties when no processing is done on the variable before it's returned would be:

public string pageTitle{get;set;}

This automatically creates the backing field for you.

like image 23
Jamie Dixon Avatar answered Sep 30 '22 17:09

Jamie Dixon


The second block of code you provided is as close to the "correct" way to implement non-trivial (with logic) properties in c# as I'm aware of.

like image 35
Nick Heidke Avatar answered Sep 30 '22 19:09

Nick Heidke


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

like image 43
Johan Tidén Avatar answered Sep 30 '22 18:09

Johan Tidén


  • List item

You are returning the property, which will walk into the get again. Does this property have a backing field?

Your proposed way is correct. The idea of properties is only to be syntactic sugar over get and set methods, not around removing the need for a local field. Auto-properties is syntactic sugar for that, but you cannot provide an implementation in that case.

What you might be thinking of is an auto-property:

public string MyName { get; set; }

But for these you cannot implement get or set.

Also, if you are providing a non-trivial implementation for a property, note that there are a couple of guidelines:

  • The get and set actions should be lightweight, ie fast.
  • The return value of the property should not change between calls unless it is set to a different value (ie, if the state of the class internally causes a different value, it's advised to use a method instead to return the value).
like image 45
Adam Houldsworth Avatar answered Sep 30 '22 18:09

Adam Houldsworth


The "syntactic shortcut" is not necessarily there to be a syntactic shortcut. If you want to use auto-properties, you can use

public String PageTitle { get; set; }

and everything is there for you, including a backing field. The real point of properties is to hide the backing field from implementers... OOP, abstraction and inheritence and all that stuff. With a property, you can add validation or change the format of how it gets returned without having to search for every instance of access to the backing field.

like image 22
Kyle W Avatar answered Sep 30 '22 19:09

Kyle W