Properties and Methods
Properties and methods are important concepts in object-oriented programming. They enable us to encapsulate data and behavior within objects.
Properties
Properties in C# are members of a class and are used to get or set values. They offer a way to protect a field in a class by reading or writing to it through the property, providing a layer of security and validation.
public class Person { // A private field, typically this is where data is stored private string name; // A public property, used to control access to the private field public string Name { get { return name; } set { name = value; } } }
In the above example, Name is a property. It provides a way to read or write to the name field.
You can also have read-only properties or write-only properties by only providing either the get or set accessor, respectively. In C# 6 and later, you can initialize auto-implemented properties directly from their declaration, simplifying your code:
public class Person { // Auto-implemented properties for trivial get and set public string Name { get; set; } public int Age { get; set; } = 18; // With initializer }
Methods
Methods in C# are operations that objects can perform. They are defined within a class or struct and typically operate on data that is contained in the class.
public class Calculator { public int Add(int a, int b) { return a + b; } }
In this example, Add is a method that takes two parameters and returns their sum.
You can create an instance of the Calculator class and call its Add method like this:
Calculator calculator = new Calculator(); int sum = calculator.Add(1, 2); // sum is 3
Note: Methods can have any number of parameters (including zero), and they can return a value or be void (returning no value).