Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
Getters and setters are essential concepts in object-oriented programming languages like C#. These two methods allow us to control the access and modification of class properties. In this tutorial, we'll explore both beginner and intermediate aspects of C# getters and private setters using code blocks.
At its core, getters and setters are nothing but methods with the same name in a class. The getter returns the value of a private field variable, while the setter modifies the importance of it. These methods ensure that a class's internal data (fields) is securely and correctly accessed or modified.
Imagine having a public class car
with a private string description property name
. If someone outside this class wants to know the description, they can't directly access it because it's private. Here comes the role of getters and setters.
A getter would allow users to retrieve the value of a private string description
without giving them direct access to modify it. On the other hand, a setter would let users modify the implicit parameter description under the conditions we set.
Access modifiers define the level of visibility and accessibility of a field or property from outside the class. The most commonly used modifiers are public
and private
.
Public
: Fields or properties declared public
can be accessed from anywhere in your program. For instance, you might have a public int age
property that can be accessed and modified by any part of your code.Private
: Properties or fields declared private can only be accessed within the defined class, for example private int age
. This encapsulation helps prevent unauthorized modifications and ensures that the class's internal state is maintained properly.Let’s begin with a simple example.
//set accessor
public class Person
{
private string name; // This is a private string name property variable
public string GetName() // This is the getter
{
return name;
}
public void SetName(string newName) // This is the setter, new value
{
name = newName;
}
}
static void Main()
{
Person person = new Person();
person.SetName("John");
Console.WriteLine(person.GetName());
}
//set accessor
public class Person
{
private string name; // This is a private string name property variable
public string GetName() // This is the getter
{
return name;
}
public void SetName(string newName) // This is the setter, new value
{
name = newName;
}
}
static void Main()
{
Person person = new Person();
person.SetName("John");
Console.WriteLine(person.GetName());
}
'set accessor
Public Class Person
Private name As String ' This is a private string name property variable
Public Function GetName() As String ' This is the getter
Return name
End Function
Public Sub SetName(ByVal newName As String) ' This is the setter, new value
name = newName
End Sub
End Class
Shared Sub Main()
Dim person As New Person()
person.SetName("John")
Console.WriteLine(person.GetName())
End Sub
In the above class Person
, we have both a getter (GetName) and a setter (SetName) for the name
property. When you run the static void Main
method, it will print "John" as we've set that value for the name using the setter.
Now, you might think, "Do I always need to write separate methods for getters and setters?" The answer is "no." C# introduced a concept called "auto-implemented properties" or "automatic properties" to simplify this.
In C#, you can use automatic properties, which give you a shorthand for declaring a private field
and its associated property. Here's an example:
public class Student
{
public string Name { get; set; } // This is an auto-implemented or automatic property, public string Name
public string Title {get; set;}
}
static void Main()
{
Student student = new Student();
student.Name = "Alice"; // Using setter
Console.WriteLine(student.Name); // Using getter
}
public class Student
{
public string Name { get; set; } // This is an auto-implemented or automatic property, public string Name
public string Title {get; set;}
}
static void Main()
{
Student student = new Student();
student.Name = "Alice"; // Using setter
Console.WriteLine(student.Name); // Using getter
}
Public Class Student
Public Property Name() As String ' - This is an auto-implemented or automatic property, public string Name
Public Property Title() As String
End Class
Shared Sub Main()
Dim student As New Student()
student.Name = "Alice" ' Using setter
Console.WriteLine(student.Name) ' Using getter
End Sub
In the Student
class
, the Name
property is both a getter and a setter, which are auto-implemented. The C# compiler creates a private string name
field behind the scenes, and the Name property provides access to that field.
Sometimes, you might want to provide a property that can be read but not modified externally. This is where read-only properties come in handy. You can omit the setter in a property to make it read-only.
Let's say we want to add a read-only string Description
property to our Person
class:
public class Person
{
public string Name { get; set; }
public string Description { get; }
public Person(string name, string description)
{
Name = name;
Description = description;
}
}
public class Person
{
public string Name { get; set; }
public string Description { get; }
public Person(string name, string description)
{
Name = name;
Description = description;
}
}
Public Class Person
Public Property Name() As String
Public ReadOnly Property Description() As String
Public Sub New(ByVal name As String, ByVal description As String)
Me.Name = name
Me.Description = description
End Sub
End Class
In this example, the Description
property can only be set within the constructor of the Person
class with less code. Once set, it cannot be modified externally.
Sometimes, you might want to allow the property to be read from outside the class but only set from within the class. This is achieved using a private set
.
public class Program
{
public string Description { get; private set; }
public Program()
{
Description = "This is a program about getters and setters.";
}
}
class ProgramTest
{
static void Main()
{
Program myProgram = new Program();
Console.WriteLine(myProgram.Description); // Allowed
// myProgram.Description = "New Description"; // Not allowed
}
}
public class Program
{
public string Description { get; private set; }
public Program()
{
Description = "This is a program about getters and setters.";
}
}
class ProgramTest
{
static void Main()
{
Program myProgram = new Program();
Console.WriteLine(myProgram.Description); // Allowed
// myProgram.Description = "New Description"; // Not allowed
}
}
Public Class Program
Private privateDescription As String
Public Property Description() As String
Get
Return privateDescription
End Get
Private Set(ByVal value As String)
privateDescription = value
End Set
End Property
Public Sub New()
Description = "This is a program about getters and setters."
End Sub
End Class
Friend Class ProgramTest
Shared Sub Main()
Dim myProgram As New Program()
Console.WriteLine(myProgram.Description) ' Allowed
' myProgram.Description = "New Description"; // Not allowed
End Sub
End Class
In the class Program
, the Description
property has a private set
, which means it can't be changed from outside the class, ensuring the integrity of the data.
When working with derived classes, you can override the getter and setter methods to customize their behavior. This allows you to add additional logic while getting or setting values.
public class Person
{
public virtual string Name { get; set; }
}
public class Student : Person
{
private string studentID;
public override string Name
{
get { return base.Name; }
set
{
if (!string.IsNullOrEmpty(value))
base.Name = value;
}
}
}
public class Person
{
public virtual string Name { get; set; }
}
public class Student : Person
{
private string studentID;
public override string Name
{
get { return base.Name; }
set
{
if (!string.IsNullOrEmpty(value))
base.Name = value;
}
}
}
Public Class Person
Public Overridable Property Name() As String
End Class
Public Class Student
Inherits Person
Private studentID As String
Public Overrides Property Name() As String
Get
Return MyBase.Name
End Get
Set(ByVal value As String)
If Not String.IsNullOrEmpty(value) Then
MyBase.Name = value
End If
End Set
End Property
End Class
In this example, the Student
class inherits from Person
and overrides the Name
property's setter. It adds a validation check before setting the name, ensuring it is not empty or null.
Iron Suite is a collection of research effort tools that significantly boost C# development capabilities. It includes IronPDF, IronXL, IronOCR, and IronBarcode. Each of these tools serves a unique purpose and can be integrated into various aspects of C#.
IronPDF
is a library that allows developers to create, read, and edit PDF documents in C#. Whether it's converting HTML to PDF using the HTML to PDF tutorial
or managing PDF metadata through getters and setters, IronPDF has you covered.
When working with Excel files, IronXL
simplifies the reading and writing process. This tool can be used to manipulate Excel files' private and public strings or integers, similar to how you might handle data within a class using the same syntax for getters and setters in C#.
IronOCR
is an Optical Character Recognition library that translates images into searchable text. If your application involves reading text from scanned documents, IronOCR's powerful capabilities can be easily integrated. It can handle private fields and public string descriptions, just like you would expect in a class Person or class Student from the previous example setup.
IronBarcode is an essential tool for applications requiring barcode reading and writing. It allows both direct access to barcode data and customization through automatic properties, just like the getters and setters used in C# programming.
The Iron Suite package seamlessly integrates with C# development, including getters and setters. These tools add value to any C# project.
To summarize:
Getter and Setter
: They help access and modify a class's private fields.Auto Properties
: An elegant way to have automatic getters and setters with the help of auto-implemented properties.Access Modifiers
: They help fine-tune the accessibility of properties.By now, you should have a solid grasp of how to use getters and setters in C#.
Iron Suite's suite of tools offers incredible functionality for C# developers. Each of these products, including IronPDF, IronXL, IronOCR, and IronBarcode, comes with a free trial, allowing you to explore and integrate these powerful libraries into your projects without any initial investment.
When you're ready to commit, individual licenses start from $749. If you find that more than one of these tools fits your needs, you can take advantage of the opportunity to buy the complete Iron Suite package for the price of just two individual licenses.
9 .NET API products for your office documents