C# Interview Questions

36 Questions
C# Programming

C# Programming

Web DevelopmentFrontendBackendGame Dev

Question 28

What are properties in C#?

Answer:

Properties in C# are members of a class, struct, or interface that provide a flexible mechanism to read, write, or compute the values of private fields. Properties enable a class to expose a public way of getting and setting values, while hiding the implementation or verification code. They are a combination of methods and fields, and provide a level of abstraction that can be used to implement encapsulation in object-oriented programming.

Key Concepts of Properties

  1. Accessors:

    • Properties have accessors that are used to access the value of a private field. There are two types of accessors:
      • get: Retrieves the value of the property.
      • set: Assigns a value to the property.
  2. Auto-Implemented Properties:

    • Auto-implemented properties simplify property declarations when no additional logic is required in the property accessors. The compiler automatically creates a private, anonymous backing field that can only be accessed through the property’s get and set accessors.
  3. Read-Only and Write-Only Properties:

    • Properties can be read-only (with only a get accessor) or write-only (with only a set accessor).

Basic Syntax

Full Property Syntax

public class Person
{
    private string name; // Private backing field

    public string Name
    {
        get
        {
            return name; // Getter
        }
        set
        {
            name = value; // Setter
        }
    }
}

Auto-Implemented Properties

public class Person
{
    public string Name { get; set; } // Auto-implemented property
}

Example Usage

public class Person
{
    private string name;

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                name = value;
            }
        }
    }

    public int Age { get; set; } // Auto-implemented property
}

public class Program
{
    public static void Main()
    {
        Person person = new Person();
        person.Name = "John Doe"; // Calls the set accessor
        person.Age = 30; // Uses auto-implemented property

        Console.WriteLine($"Name: {person.Name}"); // Calls the get accessor
        Console.WriteLine($"Age: {person.Age}"); // Uses auto-implemented property
    }
}

Read-Only and Write-Only Properties

Read-Only Property

public class Person
{
    private string name;

    public Person(string name)
    {
        this.name = name;
    }

    public string Name
    {
        get
        {
            return name;
        }
    }
}

Write-Only Property

public class Person
{
    private string secret;

    public string Secret
    {
        set
        {
            secret = value;
        }
    }
}

Computed Properties

Properties can also be computed based on other fields or properties:

public class Rectangle
{
    public double Width { get; set; }
    public double Height { get; set; }

    public double Area
    {
        get
        {
            return Width * Height;
        }
    }
}

public class Program
{
    public static void Main()
    {
        Rectangle rect = new Rectangle { Width = 10, Height = 5 };
        Console.WriteLine($"Area: {rect.Area}"); // Output: Area: 50
    }
}

Property Access Modifiers

You can control the accessibility of the property’s get and set accessors independently:

public class Person
{
    public string Name { get; private set; } // Public getter, private setter

    public Person(string name)
    {
        Name = name;
    }
}

Benefits of Properties

  1. Encapsulation:

    • Properties enable encapsulation by providing controlled access to the class’s fields. They can include logic to validate the input or to transform the output.
  2. Flexibility:

    • Properties provide flexibility to change the internal implementation without changing the public interface. This allows for maintaining backward compatibility while improving or modifying the internal code.
  3. Readability and Usability:

    • Properties make the code more readable and user-friendly compared to using explicit getter and setter methods.

Summary

Properties in C# provide a powerful mechanism to encapsulate data and control access to the internal state of an object. They allow for a clear and intuitive syntax while providing the flexibility to include logic for validation, computation, and other processing. By using properties, developers can achieve better encapsulation, maintainability, and readability in their code.

Recent job openings