Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now

C#: Property, Indexer, Exception Handling & Enum

Level : Intermediate
Mentor: Shailendra Chauhan
Duration : 00:04:30

Auto-implemented Properties:

Auto-implemented properties simplify property declaration by automatically generating a private backing field. They are often used when no additional logic is needed in the property accessor methods.

Example:

public class Person
{
    public string Name { get; set; } // Auto-implemented property
}
var person = new Person();
person.Name = "John";
Console.WriteLine(person.Name); // Output: John

Read-Only Properties:

Read-only properties have a getter but no setter, making their value immutable after initialization.

Example:

public class Circle
{
    public double Radius { get; } // Read-only property
    public Circle(double radius)
    {
        Radius = radius;
    }
}
var circle = new Circle(5.0);
Console.WriteLine(circle.Radius); // Output: 5.0

Write-Only Properties:

Write-only properties have a setter but no getter, allowing you to set values but not retrieve them directly.

Example:

public class TemperatureSensor
{
    private double temperature;
    public double Temperature
    {
        set { temperature = value; } // Write-only property
    }
}
var sensor = new TemperatureSensor();
sensor.Temperature = 25.5;

Custom Properties with Logic:

Custom properties allow you to add custom logic within their getter and setter methods. In this example, we ensure that the age is always non-negative.

Example:

public class Person
{
    private int age;
    public int Age
    {
        get { return age; }
        set
        {
            if (value >= 0)
                age = value;
            else
                throw new ArgumentException("Age cannot be negative.");
        }
    }
}
var person = new Person();
person.Age = 30; // Valid
person.Age = -5; // Throws an ArgumentException

Backing Fields with Properties:

Properties often use private backing fields to store their values, allowing encapsulation and control over access.

Example:

public class BankAccount
{
    private decimal balance; // Private backing field
    public decimal Balance
    {
        get { return balance; }
        set { balance = value; }
    }
    public BankAccount(decimal initialBalance)
    {
        balance = initialBalance;
    }
}
var account = new BankAccount(1000.0m);
decimal currentBalance = account.Balance;

C# Indexer:

In C#, an indexer is a special property of a class or struct that allows objects of that type to be accessed like an array or collection, using square brackets. Indexers provide a way to get or set values of an object's elements without having to create explicit methods for each element.

Example:

using System;
class MyCollection
{
    private int[] data = new int[5];
    // Indexer declaration
    public int this[int index]
    {
        get
        {
            if (index >= 0 && index < data.Length)
                return data[index];
            else
                throw new IndexOutOfRangeException();
        }
        set
        {
            if (index >= 0 && index < data.Length)
                data[index] = value;
            else
                throw new IndexOutOfRangeException();
        }
    }
}
class Program
{
    static void Main()
    {
        MyCollection collection = new MyCollection();
        // Setting values using the indexer
        collection[0] = 42;
        collection[1] = 99;
        // Getting values using the indexer
        int value1 = collection[0];
        int value2 = collection[1];
        Console.WriteLine($"Value at index 0: {value1}"); // Output: Value at index 0: 42
        Console.WriteLine($"Value at index 1: {value2}"); // Output: Value at index 1: 99
    }
}

C# Exception Handling:

Exception handling in C# allows developers to gracefully handle runtime errors or unexpected situations in their code. It helps prevent crashes and provides a mechanism to recover from errors. You can use try/catch blocks to handle exceptions and maintain program stability.

C# try/catch:

The try/catch statement is used in C# to handle exceptions. Code within the try block is monitored for exceptions, and if an exception occurs, it is caught and processed in the catch block. This ensures that even if an error occurs, the program can continue to execute without crashing.

Example:

try
{
    // Code that might throw an exception
}
catch (Exception ex)
{
    // Handle the exception
    Console.WriteLine($"An error occurred: {ex.Message}");
}

C# finally:

The finally block is used in conjunction with try/catch to ensure that certain code is executed regardless of whether an exception is thrown or not. It is often used for cleanup tasks like closing files or releasing resources.

Example:

try
{
    // Code that might throw an exception
}
catch (Exception ex)
{
    // Handle the exception
}
finally
{
    // This code will always execute
    Console.WriteLine("Cleanup tasks are performed.");
}

C# Custom Exception:

In C#, you can create custom exceptions by defining your own exception classes that inherit from the Exception base class. This allows you to create more specific and meaningful exceptions for your application.

Example:

public class MyCustomException : Exception
{
    public MyCustomException(string message) : base(message) { }
}

C# checked/unchecked:

In C#, the `checked` and `unchecked` keywords are used to control the behavior of arithmetic overflow. By default, C# checks for overflow, but you can use `unchecked` to disable these checks, allowing overflow to occur without throwing exceptions. Conversely, `checked` ensures that overflow results in an exception.

Example:

int x = int.MaxValue;
int y = checked(x + 1); // This will throw an OverflowException

C# SystemException:

SystemException is the base class for all exceptions in the System namespace. It provides a common base for exceptions like InvalidOperationException, ArgumentNullException, and many others. You can catch SystemException to handle various system-related exceptions in a more general way.

Example:

try
{
    // Code that might throw a system-related exception
}
catch (SystemException ex)
{
    // Handle the system exception
    Console.WriteLine($"A system exception occurred: {ex.Message}");
}

C# Enum:

Enums are used to define a set of named constant values. They provide better code readability.

Example:

enum DaysOfWeek
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
DaysOfWeek today = DaysOfWeek.Wednesday;
Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this