DevAcademia
C++C#CPythonJava
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction

Loading Cs tutorial…

Loading content
C# OOPTopic 46 of 55
←PreviousPrevNextNext→

C# Properties - Complete Guide

Introduction to Properties

Properties in C# are members that act as accessors to fields. They allow reading, writing, or computing values while encapsulating the underlying implementation.

They provide a clean syntax for accessing data (similar to fields) but also support validation, computed results, and different accessibility levels.

Types of Properties

C# supports several types of properties, including auto-implemented properties, read-only properties, properties with validation, computed properties, and expression-bodied properties.

Example
using System;

namespace PropertiesExample
{
    public class Person
    {
        private string _name;
        private int _age;
        private DateTime _birthDate;

        public string Email { get; set; }

        public string ID { get; }

        public string Name
        {
            get => _name;
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                    throw new ArgumentException("Name cannot be empty");
                _name = value;
            }
        }

        public int Age
        {
            get => _age;
            private set
            {
                if (value < 0 || value > 150)
                    throw new ArgumentException("Invalid age");
                _age = value;
            }
        }

        public int BirthYear => _birthDate.Year;

        public bool IsAdult => Age >= 18;

        public Person(string id, string name, int age, DateTime birthDate)
        {
            ID = id;
            Name = name;
            Age = age;
            _birthDate = birthDate;
        }

        public void UpdateAge(int newAge) => Age = newAge;

        public void DisplayInfo()
        {
            Console.WriteLine($"ID: {ID}");
            Console.WriteLine($"Name: {Name}");
            Console.WriteLine($"Age: {Age}");
            Console.WriteLine($"Birth Year: {BirthYear}");
            Console.WriteLine($"Is Adult: {IsAdult}");
            Console.WriteLine($"Email: {Email ?? "Not set"}");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Person person = new Person("P001", "Alice", 25, new DateTime(1998, 5, 15));

                person.Email = "alice@example.com";
                person.DisplayInfo();

                Console.WriteLine("\nAfter updating age:");
                person.UpdateAge(26);
                person.DisplayInfo();

                Console.WriteLine("\nTesting validation:");
                try
                {
                    person.Name = "";
                }
                catch (ArgumentException ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }

                Console.WriteLine("\nComputed properties:");
                Console.WriteLine($"Birth Year: {person.BirthYear}");
                Console.WriteLine($"Is Adult: {person.IsAdult}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}
Output
ID: P001
Name: Alice
Age: 25
Birth Year: 1998
Is Adult: True
Email: alice@example.com

After updating age:
ID: P001
Name: Alice
Age: 26
Birth Year: 1998
Is Adult: True
Email: alice@example.com

Testing validation:
Error: Name cannot be empty

Computed properties:
Birth Year: 1998
Is Adult: True
Test your knowledge: C# Properties - Complete Guide
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
C# OOPTopic 46 of 55
←PreviousPrevNextNext→