Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of this approach to access modifiers?

Consider the following code:

    private string _text = null;
    private string[] _values = null;

    public string Text { get { return _text; } }
    public string[] Values { get { return _values; } }

What does this accomplish that having the public members alone would not?

like image 223
John Straka Avatar asked Apr 24 '12 16:04

John Straka


People also ask

What is the main purpose of access modifiers?

The purpose of using access modifiers is to implement encapsulation, which separates the interface of a type from its implementation.

What are the 3 types of access modifiers?

Simply put, there are four access modifiers: public, private, protected and default (no keyword).

What is the main purpose of access modifiers MCQS?

C) Access modifiers help in implementing the Encapsulation feature of Object-Oriented Programming (OOPs).

What are access modifiers used to implement?

Access modifiers are used to implement an important aspect of Object-Oriented Programming known as Data Hiding.


1 Answers

By using properties instead of public fields, you hide the implementation.

If at some point you need to change what the Text and Values properties return, you can change the behavior without changing the API of the class.

Additionally, this idiom limits external access to the exposed data as read-only.

like image 75
Luca Geretti Avatar answered Sep 21 '22 15:09

Luca Geretti