In C#, fields and properties are both members of a class or struct, but they serve different purposes and have distinct characteristics.
Fields in C#
A field is a variable that is declared within a class or struct. Fields hold data or state for objects or instances of a class. They can be of any data type, such as integers, strings, or custom types.
Important features
1. Fields can have access modifiers (e.g., public, private, protected) to control their visibility.
2. Fields can be accessed directly, but it’s generally considered good practice to make them private or protected and access them via properties or methods.
Example:
class Employee
{
public string name; // Public field
private int age; // Private field
// Constructor to initialize fields
public Employee(string empName, int empAge)
{
this.name = empName;
this.age = empAge;
}
}
Note: name is a public field and age is private field.
Properties in C#
A property is a member that provides a mechanism for reading, writing, or computing the value of a field. Properties provide more control over the data compared to fields. They allow you to define getters and setters, which can enforce rules or validation when getting or setting the value of a field.
Example:
using System;
class Employee
{
// Private field to store the name
private string name;
// Property to access and set the name
public string Name
{
get
{
return name; // Returns the value of the private field
}
set
{
name = value; // Sets the private field to the value provided
}
}
// Constructor to initialize the name
public Employee(string name)
{
this.Name = name; // Use the property to set the name
}
}
class ProgramExample
{
static void Main()
{
// Create an instance of Employee
Employee emp = new Employee("John");
// Access the Name property
Console.WriteLine(emp.Name); // Output: Alice
// Modify the Name using the property
emp.Name = "Tom";
Console.WriteLine(emp.Name); // Output: Bob
}
}
Explanation:
- name field to store the value of the Name. It is private to keep it hidden from outside code.
- The getter (get) returns the value of the name field.
- The setter (set) assigns a new value to the name field.