Properties in C#

7 questions found

What are Properties in C#? Explain with an example.

Beginner
Properties in C# are members that provide a flexible way to read, write, or compute the value of a private field while still exposing that access through a simple, field like syntax. A property typically consists of a get accessor for reading the value and a set accessor for writing it, allowing you to add validation logic or computed behavior behind the scenes without changing how the property is used from outside the class.
public class Person {
    private int _age;
    public int Age {
        get { return _age; }
        set {
            if (value < 0) throw new ArgumentException("Age cannot be negative");
            _age = value;
        }
    }
}
Real-world example A Person class exposes an Age property that silently validates any value being assigned to it, rejecting negative numbers, so any code that sets a person's age automatically benefits from this protection without needing to call a separate validation method.

Common follow-ups: What is the difference between a field and a property in C#?;Can a property have only a getter and no setter?

What are the different types of properties available in C#?;What are the advantages of using properties in C#?

What are the different types of properties available in C#?

Beginner
C# supports several types of properties, including read write properties that have both get and set accessors, read only properties that only expose a get accessor, write only properties that only expose a set accessor, auto implemented properties that let the compiler generate the backing field automatically, and computed properties that calculate their return value dynamically instead of storing it directly in a field.
public string FullName { get; }           // read only
public string Password { set; private get; } // write focused
public string Email { get; set; }            // read write, auto implemented
public int Total => Price * Quantity;        // computed property
Real-world example An order class exposes a computed Total property that always multiplies price by quantity on the fly, guaranteeing the total is never out of sync since it is calculated fresh every time it is accessed rather than stored separately.

Common follow-ups: What is an auto implemented property and how does it differ from a regular property?;When would you use a computed property instead of storing a value directly?

What are Properties in C#? Explain with an example.;What is a static property? Give an example.

What are the advantages of using properties in C#?

Beginner
Properties offer several advantages over exposing raw public fields, including the ability to add validation logic when a value is set, the ability to make a member effectively read only or write only from outside the class, the ability to compute a value dynamically instead of storing it, and the flexibility to change the internal implementation later without breaking any code that uses the property, since the external syntax for accessing it remains exactly the same.
public class BankAccount {
    private decimal _balance;
    public decimal Balance {
        get { return _balance; }
        private set { _balance = value; }
    }
}
Real-world example A BankAccount class exposes its Balance as a property with a private setter, allowing external code to read the current balance freely while preventing anyone outside the class from directly overwriting it without going through proper deposit or withdrawal methods.

Common follow-ups: How do properties support the principle of encapsulation?;Can changing a public field to a property later break existing code that used the field?

What are Properties in C#? Explain with an example.;What are the different types of properties available in C#?

What is a static property? Give an example.

Intermediate
A static property belongs to the class itself rather than to any specific instance of that class, meaning it is accessed through the class name directly and shares the exact same value across every part of the application, regardless of how many objects of that class have been created. Static properties are commonly used for values that should be shared globally, such as a counter tracking how many instances of a class have been created.
public class Counter {
    private static int _count = 0;
    public static int TotalCreated {
        get { return _count; }
    }
    public Counter() { _count++; }
}

var a = new Counter();
var b = new Counter();
Console.WriteLine(Counter.TotalCreated); // 2
Real-world example A logging library uses a static property to track the total number of log entries written across the entire application, since this count needs to be shared globally rather than tracked separately for each individual logger instance.

Common follow-ups: Can a static property be accessed through an instance of the class instead of the class name?;What is the difference between a static property and a static field?

What is Virtual Property in C#? Give an example.;Can you use virtual override or abstract keywords on an accessor of a static property?

What is Virtual Property in C#? Give an example.

Intermediate
A virtual property is a property declared in a base class using the virtual keyword, which allows a derived class to override its behavior using the override keyword, giving subclasses the ability to provide their own custom implementation of the getter or setter while still being accessible through the same property name.
public class Shape {
    public virtual double Area {
        get { return 0; }
    }
}

public class Circle : Shape {
    public double Radius { get; set; }
    public override double Area {
        get { return Math.PI * Radius * Radius; }
    }
}
Real-world example A shape hierarchy defines a virtual Area property on a base Shape class, and each specific shape like Circle or Rectangle overrides it with its own correct area calculation formula, letting calling code treat every shape uniformly through the same Area property.

Common follow-ups: What happens if a derived class does not override a virtual property?;What is the difference between a virtual property and an abstract property?

What is an Abstract Property in C#? Give an example.;What is a static property? Give an example.

What is an Abstract Property in C#? Give an example.

Intermediate
An abstract property is a property declared inside an abstract class without any implementation, using the abstract keyword, which forces every non abstract class that inherits from it to provide its own concrete implementation for that property. Unlike a virtual property, an abstract property has no default behavior at all in the base class, meaning the base class simply defines what the property should look like while leaving the actual logic entirely up to each derived class.
public abstract class Employee {
    public abstract decimal MonthlySalary { get; }
}

public class Manager : Employee {
    public override decimal MonthlySalary {
        get { return 8000m; }
    }
}
Real-world example A payroll system defines an abstract MonthlySalary property on an Employee base class, forcing every specific employee type such as Manager or Developer to define exactly how their own salary should be calculated.

Common follow-ups: Can an abstract property have a default implementation?;What is the difference between an abstract class and an interface when it comes to properties?

What is Virtual Property in C#? Give an example.;Why is class an abstract data type?

Can you use virtual, override, or abstract keywords on an accessor of a static property?

Advanced
No, static members in C# belong to the type itself rather than to any specific instance, so they cannot participate in polymorphism, which means you cannot use the virtual, override, or abstract keywords on a static property or its accessors. Polymorphic behavior through these keywords only applies to instance members, since overriding fundamentally relies on the actual runtime type of an object instance, which static members simply do not have.
public class Base {
    // This is not allowed and will cause a compiler error
    // public static virtual int Value { get; set; }
}
Real-world example A developer attempting to make a shared configuration value overridable across subclasses using a static virtual property quickly discovers this is not allowed in C#, and instead redesigns the solution using an instance based virtual property.

Common follow-ups: How can you achieve similar shared, overridable behavior without using static members?;Why does polymorphism require instance level members specifically?

What is a static property? Give an example.;What is Virtual Property in C#? Give an example.