C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# get And set Accessors: Get And Set The Value Of A Field (property)

In C#, properties are used to access and modify the values of fields, which are private variables inside a class. Properties are a way to encapsulate and protect the fields, while still providing controlled access to their values. The get and set accessors are used within a property to read and write the value of a field, respectively.

Here is a tutorial on using C# properties with get and set accessors:

  • Define the class:

First, create a new C# class that will contain the field and the property. For this example, let's create a Person class with a private field called _name:

public class Person
{
    private string _name;
}
  • Create the property:

To expose the _name field to the outside world, you need to create a property. In this case, we will create a property called Name. Add the following code inside the Person class:

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

Here, the get accessor is used to return the value of the _name field, while the set accessor is used to assign a new value to the _name field. The value keyword represents the value being assigned to the property.

  • Instantiate the class and use the property:

Now you can create a Person object and use the Name property to get and set the value of the _name field:

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();
        
        // Set the value of the Name property
        person.Name = "John Doe";
        
        // Get the value of the Name property
        string personName = person.Name;
        
        Console.WriteLine("The person's name is: " + personName);
    }
}

This code creates a new Person object, sets its Name property to "John Doe", and then retrieves the value of the Name property and writes it to the console.

In this example, the get and set accessors provide unrestricted access to the _name field. However, you can implement additional logic within the accessors to validate the input, enforce certain conditions, or trigger additional actions when the value is read or modified.

  1. C# Get and Set Accessors Example:

    // Property with get and set accessors
    private int _age;
    
    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
    
  2. Defining Properties with Get and Set in C#:

    // Property with get and set accessors
    private string _name;
    
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    
  3. Accessing Fields Using Get and Set in C#:

    • Properties are often used to encapsulate private fields, providing controlled access to the underlying data.
    private string _email;
    
    public string Email
    {
        get { return _email; }
        set { _email = value; }
    }
    
  4. Using Get and Set Accessors for Property Values:

    // Property with get and set accessors
    private double _price;
    
    public double Price
    {
        get { return _price; }
        set
        {
            if (value > 0)
                _price = value;
        }
    }
    
  5. Get and Set Methods in C# Properties:

    • While the typical use is to directly access the field within the get and set accessors, you can also use methods for additional logic.
    private string _password;
    
    public string Password
    {
        get { return Decrypt(_password); }
        set { _password = Encrypt(value); }
    }
    
    private string Encrypt(string value)
    {
        // Encryption logic
        return value;
    }
    
    private string Decrypt(string value)
    {
        // Decryption logic
        return value;
    }
    
  6. Working with Property Accessors in C#:

    • Accessors allow you to control read and write access to the property, enabling validation, transformation, or other logic.
    private int _quantity;
    
    public int Quantity
    {
        get { return _quantity; }
        set
        {
            if (value >= 0)
                _quantity = value;
            else
                throw new ArgumentException("Quantity must be non-negative.");
        }
    }
    
  7. C# Auto-Implemented Properties with Get and Set:

    • In C# 3.0 and later, you can use auto-implemented properties to simplify property declaration when no additional logic is needed.
    public string AutoProperty { get; set; }
    
    • With initializers:
    public string AutoPropertyWithInitializer { get; set; } = "Default Value";