Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using get set properties of C# considered good practice?

Tags:

c#

.net

my question is simple, is using the get set properties of C# considered good, better even than writing getter and setter methods? When you use these properties, don't you have to declare your class data members as public ? I ask this because my professor stated that data members should never be declared as public, as it is considered bad practice.

This....

class GetSetExample
{
    public int someInt { get; set; }
}

vs This...

class NonGetSetExample
{
    private int someInt;
}

Edit:

Thanks to all of you! All of your answers helped me out, and I appropriately up-voted your answers.

like image 919
Alex Avatar asked Dec 02 '09 02:12

Alex


People also ask

What is get set in C?

Get set are access modifiers to property. Get reads the property field. Set sets the property value. Get is like Read-only access. Set is like Write-only access.

What is get set used for?

The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property. If you don't fully understand it, take a look at the example below.

Why we use get and set with properties?

These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers. For example, the get may be public to allow read-only access from outside the type, and the set may be private or protected .

Why do we use 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.


1 Answers

This:

class GetSetExample
{
    public int someInt { get; set; }
}

is really the same as this:

class GetSetExample
{
    private int _someInt;
    public int someInt {
        get { return _someInt; }
        set { _someInt = value; }
    }
}

The get; set; syntax is just a convenient shorthand for this that you can use when the getter and setter don't do anything special.

Thus, you are not exposing a public member, you are defining a private member and providing get/set methods to access it.

like image 118
Nate C-K Avatar answered Sep 28 '22 07:09

Nate C-K