[C#] C# Properties (Get and Set)
Categories: CS
Tags: Get Set Properties
📋 This is my note-taking from what I learned in the class “Programming 2”
Properties and Encapsulation
The meaning of Encapsulation, is to make sure that “sensitive” data is hidden from users. To achieve this, you must:
- declare fields/variables as private
- provide public get and set methods, through properties, to access and update the value of a private field
Regular properties in C# provide a way to encapsulate data and define custom logic for getting and setting the values of the property. They are manually implemented by explicitly defining the backing field and writing the code for the getter and setter methods.
Properties
Private variables can only be accessed within the same class (an outside class has no access to it). However, sometimes we need to access them - and it can be done with properties.
Property in C# is a class member that exposes the class’s private fields. Internally, C# properties are special methods called accessors.
A property is like a combination of a variable and a method, and it has two methods: a get and a set method:
class Person
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}
In the above code, the Person
class has a property called Name
with a private backing field name
. The getter and setter methods define the logic for accessing and modifying the value of the property.
You can add additional logic or validation within the getter and setter methods:
class Person
{
private string name;
public string Name
{
get { return name; }
set
{
if (value != null && value.Length > 0)
{
name = value;
}
else
{
throw new ArgumentException("Name cannot be null or empty.");
}
}
}
}
Regular properties provide flexibility and control over how the values are accessed and modified. They allow you to enforce business rules, perform validation, or trigger additional actions when the property is accessed or modified.
- The Name property is associated with the name field. It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter.
- A C# property has two accessors, a get property accessor or a getter and a set property accessor or a setter.
- 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.
Now we can use the Name property to access and update the private field of the Person class:
class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
// Output: Liam
get and set are accessors used in the property declaration of the Name property in the Person class. They define how the property is accessed and modified.
The get accessor is used to retrieve the value of the property, and the set accessor is used to assign a new value to the property.
-
- get Accessor:
-
- It is used to retrieve the current value of the property.
-
- In the code snippet get { return name; }, it returns the value of the private field name when the Name property is accessed.
-
- set Accessor:
-
- It is used to assign a new value to the property.
-
- In the code snippet set { name = value; }, it assigns the incoming value (value) to the private field name when the Name property is assigned a new value.
using System;
namespace studentInfo
{
class Student
{
private string sname;
private int sno;
// Declare a Name property of type string:
public string Name
{
get { return sname; }
set { name = value; }
}
// Declare a Number property of type int:
public int Number
{
get { return sno; }
set { age = value; }
}
public override string ToString()
{
return "Student Name = " + Name + ", Student No = " + Number;
}
}
class ExampleDemo
{
public static void Main()
{
// Create a new Student object:
Student s = new Student();
// Setting name and sno
s.Name = "John";
s.Number = 7;
Console.WriteLine("Student Info: {0}", s);
// Let us increase sno
s.Number += 1;
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}
}
}
String Converter
// create class
class StringConverter
{
// main method
static void Main()
{
// create variables
int quantity = 20;
double price = 50.00;
char tag = 'T';
bool isFinished = false;
// convert them to strings
string a = quantity.ToString();
string b = price.ToString();
string c = tag.ToString();
string d = isFinished.ToString();
// print out converted values
System.Console.WriteLine(a);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
System.Console.WriteLine(d);
}
}
Access Levels of Properties
Properties in C# have various access levels defined by an access modifier. Properties can be read-write properties, read-only properties, or write-only properties.
- The read-write property implements both a get and a set accessor.
- A write-only property implements a set accessor but no get accessor.
- A read-only property implements a get accessor but no set accessor.
Automatic Properties / Auto-implemented properties (Short Hand)
C# also provides a way to use short-hand / automatic properties, where you do not have to define the field for the property, and you only have to write get; and set; inside the property.
Auto-implemented properties in C# provide a simplified syntax for defining properties of a class without explicitly implementing the backing field. They allow you to declare a property with a getter and setter without having to write the code for the underlying field.
The following example will produce the same result as the example above. The only difference is that there is less code:
Using automatic properties:
class Person
{
public string Name // property
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
In the above code, the Person
class has two properties: Name
and Age
. These properties are auto-implemented properties because they don’t have explicit backing fields. The compiler automatically generates a hidden backing field for each property.
You can access and modify the values of these properties just like you would with regular properties:
Person person = new Person();
person.Name = "John";
person.Age = 25;
Console.WriteLine(person.Name); // Output: John
Console.WriteLine(person.Age); // Output: 25
Why Encapsulation?
- Better control of class members (reduce the possibility of yourself (or others) to mess up the code)
- Fields can be made read-only (if you only use the get method), or write-only (if you only use the set method)
- Flexible: the programmer can change one part of the code without affecting other parts
- Increased security of data
Leave a comment