Jump to content

C# Getters and Setters Help!

Go to solution Solved by Nineshadow,

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Here's a somewhat useful example . In this example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}


class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}
// Output: Time in hours: 24

As far as the "get" and "set" things go...they are called accessors. The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. The declarations take the following forms:

set {accessor-body}
get {accessor-body}

But I've already shown you an example of what exactly they do , so I won't go more in-depth here.

 

But what's the difference? Well...let's say we had this :

private string _name;
public string Name { get { return _name; } set { _name = value; } }

We could also do something like this :

public string get_Name() { return _name; }
public void set_Name(string value) { _name = value; }

Both of them act identically. And in fact, this is exactly what the compiler does for you when you create a property.

 

So it really comes down to proprieties. Should you use a property over a method? Honestly , it doesn't matter too much. In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. Symantically properties are attributes of your objects. Methods are behaviors of your object Consider a class , Car { Color, Model, Brand } . A car has Color, Model and Brand attributes therefore it does not make sense to have a method SetColor or SetModel because symantically we do not ask Car to set its own color.  When it does not violate the following guidelines, some might prefer using a property, rather than a method, because less experienced developers find properties easier to use. If you're doing something complex that may affect several data members, a method is more appropriate. Or if your getter takes parameters or your setter takes more than a value parameter.

 

So , I'll just say it again , it doesn't really matter. Functionality is identical. Just make sure you stick to one style.

Hi, I'm currently at a new job and developing in c# is one of the things they are having me doing. Today I was looking at some of their code and found a getter/setter propertie thing(not method supposedly) that I have not seen before. I decided to type a program that would demonstrate the old way(my way or like java) and C# new way(like what I found in their code). 




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SandBox
{
    class Program
    {

        static void Main(string[] args)
        {


            GettersSetters myGS = new GettersSetters();
            myGS.count = 3;
            Console.WriteLine(myGS.count);

        }

    }

    public class GettersSetters
    {
        private int num = 5;

        //Old way
        public int getCount()
        {
            return num;
        }


        //Old way
        public void setCount(int num)
        {
            this.num = num;

        }

        //New way
        public int count
        {
            get{
                return this.num;
            }

            set{
                num = value;
            }
        }

    }

 

 

 

So what is different between the two ways? What is the difference between a properties and fields? Which way should I do it? As you can tell I'm really confused. I have a vb, java, and python background so this is new to me. 

Link to comment
https://linustechtips.com/topic/563780-c-getters-and-setters-help/
Share on other sites

Link to post
Share on other sites

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Here's a somewhat useful example . In this example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}


class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}
// Output: Time in hours: 24

As far as the "get" and "set" things go...they are called accessors. The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. The declarations take the following forms:

set {accessor-body}
get {accessor-body}

But I've already shown you an example of what exactly they do , so I won't go more in-depth here.

 

But what's the difference? Well...let's say we had this :

private string _name;
public string Name { get { return _name; } set { _name = value; } }

We could also do something like this :

public string get_Name() { return _name; }
public void set_Name(string value) { _name = value; }

Both of them act identically. And in fact, this is exactly what the compiler does for you when you create a property.

 

So it really comes down to proprieties. Should you use a property over a method? Honestly , it doesn't matter too much. In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. Symantically properties are attributes of your objects. Methods are behaviors of your object Consider a class , Car { Color, Model, Brand } . A car has Color, Model and Brand attributes therefore it does not make sense to have a method SetColor or SetModel because symantically we do not ask Car to set its own color.  When it does not violate the following guidelines, some might prefer using a property, rather than a method, because less experienced developers find properties easier to use. If you're doing something complex that may affect several data members, a method is more appropriate. Or if your getter takes parameters or your setter takes more than a value parameter.

 

So , I'll just say it again , it doesn't really matter. Functionality is identical. Just make sure you stick to one style.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to post
Share on other sites

Properties reduce getter/setter boilerplate code. The compiler does that for you. Generally, simple properties are written like this, known as Automatic Properties.

public int Num { get; set; }

You can also write the following depending on your needs

public int Num { get; private set; }
public int Num { get; } // new in C# 6
public int Num { get; set; } = 5 // also new in C# 6

You can expand the get/set portions if you need something else done that the above options don't provide.

 

Here is some information on choosing properties vs methods.

Here is some information on properties vs fields.

Link to post
Share on other sites

As the other two answers have pointed out the complier does do some work for you but I think it would be good to point out a few small details about this matter.

First off you have the "Old way" like below

private int num = 5;

//Old way
public int getCount()
{
	return num;
}

//Old way
public void setCount(int num)
{
	this.num = num;
}

This is where the Backing Field (num) is only accessed by the methods getCount() and setCount()

 

//New way
public int count
{
  get{
  	return this.num;
}
  set{
  	num = value;
}
//The above is exactly the same as below
public int count { get;set;}

What happens when you write code like the above is that the complier actually makes you a private backing field with those public accessors available to you still.

So effectively they are the same thing, apart from their use cases. 

E.g you might want to processes the data before setting or setting it, therefore you would want to set up your own backing fields so that you can use your own logic in the accessors.

If you just want to get and set the fields then it's easy to just use the second method

Link to post
Share on other sites

It does not matter functionally which method of encapsulation to use, it's all the same in the end. Though style-wise, I'd say you better use properties, they reduce a lot of useless code and looks a lot cleaner. This is a feature I would love that Java had lol.

Link to post
Share on other sites

Don't forget that we also have expression bodied properties and methods now (C# 6):

public someType SomeProperty => somethingElse;

public string SomeFunction() => someString;

In any event, use properties over writing all of that out manually. The language provides you with the facility, ignore it at the peril of your own career.

The single biggest problem in communication is the illusion that it has taken place.

Link to post
Share on other sites

 

15 hours ago, Toxicable said:

As the other two answers have pointed out the complier does do some work for you but I think it would be good to point out a few small details about this matter.

First off you have the "Old way" like below


private int num = 5;

//Old way
public int getCount()
{
	return num;
}

//Old way
public void setCount(int num)
{
	this.num = num;
}

This is where the Backing Field (num) is only accessed by the methods getCount() and setCount()

 


//New way
public int count
{
  get{
  	return this.num;
}
  set{
  	num = value;
}
//The above is exactly the same as below
public int count { get;set;}

What happens when you write code like the above is that the complier actually makes you a private backing field with those public accessors available to you still.

So effectively they are the same thing, apart from their use cases. 

E.g you might want to processes the data before setting or setting it, therefore you would want to set up your own backing fields so that you can use your own logic in the accessors.

If you just want to get and set the fields then it's easy to just use the second method

Also very good answer. Thanks!

Link to post
Share on other sites

14 hours ago, DevBlox said:

It does not matter functionally which method of encapsulation to use, it's all the same in the end. Though style-wise, I'd say you better use properties, they reduce a lot of useless code and looks a lot cleaner. This is a feature I would love that Java had lol.

Now that I get it I agree with you! Java needs this feature. 

Link to post
Share on other sites

Thanks everyone for your awesome help. Totally understand the concept now. I will stick to the properties way in C# a. cause they use them where I work, b. cause it looks cleaner, c. because convince. I understand there is more reason why I should/might use properties over typical methods for getters/setters but those are the main reasons why I'm going to try and use them. 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×