C# Properties

What is a Property?

A property is a special way to access and modify data in a class.

Instead of directly accessing variables, properties allow controlled access using get and set.

Loading...
Output:

Why Use Properties?

Properties help protect data and make your code more flexible.

  • Control how data is accessed
  • Allow validation
  • Make code cleaner than traditional methods
  • Standard practice in C#

Basic Property Example

Here is a simple class using properties.

Loading...
Output:

Properties vs Fields

A field is a simple variable, while a property adds control over how the value is accessed.

Loading...
Output:

Custom Get and Set

You can customize the behavior of properties using get and set.

This allows you to add logic like validation or formatting.

Loading...
Output:

Read-Only Properties

A property can be read-only by removing the set.

This means the value can only be accessed, not changed.

Loading...
Output:

Write-Only Properties

A property can also be write-only by removing the get.

This is less common but useful for sensitive data.

Loading...
Output:

Why Properties Matter in C#

Properties are a core part of C# development and are used in almost every real-world application.

  • Used in APIs and models
  • Essential for frameworks like ASP.NET
  • Cleaner than traditional getter/setter methods

Practice

Create a Student class with Name and Age properties. Add validation so Age cannot be negative.

Loading...
Output:

Need Help?