Skip to main content

Class Members

C# is an object-oriented programming language, and as such, it allows for the classification of real-world objects into classes. A class is a blueprint or template that describes the behavior and state that the objects of the class all share. An object is an instance of a class.

In C#, a class can contain multiple members. These can be fields, methods, properties, and other class types. In this guide, we will discuss each type of these class members and how to use them.

Fields

Fields are variables that are declared directly in a class. They are used to store the state of an object.

Here is an example of a field in a class:

public class Car
{
string color; // this is a field
}

Fields are usually private, meaning they can only be accessed within the same class. This is a principle of encapsulation in OOP.

Methods

Methods are blocks of code that are declared directly in a class. They define the behaviors or actions an object can perform.

Here is an example of a method in a class:

public class Car
{
public void Drive() // this is a method
{
// code to implement driving
}
}

Methods can be called on an object of the class.

Properties

Properties are a kind of class member that provides a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors.

Here is an example of a property in a class:

public class Car
{
private string color; // private field

public string Color // this is a property
{
get { return color; }
set { color = value; }
}
}

In this example, Color is a property that encapsulates the color field. It provides a way to access the color field using a get accessor and a way to modify it using a set accessor.

Constructors

Constructors are special methods in a class that are called when an object of the class is created. They usually initialize the fields of the class.

Here is an example of a constructor in a class:

public class Car
{
string color;

public Car() // this is a constructor
{
color = "Red";
}
}

In this example, the constructor Car() sets the color field to "Red" when an object of the Car class is created.

In summary, fields, methods, properties, and constructors are all members of a class in C#. They define the state and behavior of an object. Fields store the state of an object, methods define what an object can do, properties provide a way to read and write the state of an object, and constructors initialize an object when it is created.