Language: EN

csharp-clases

What are and how to use classes in C#

A class in C# is a data type that defines a set of fields, properties, methods, and events that represent a concept or entity in the real world.

Classes provide a blueprint for creating instances of the class. Each instance has its own state (stored in fields) and behavior (defined in methods).

Classes allow us to encapsulate related data and functionalities in a single entity, making code reuse and application maintenance easier. They are the foundation of object-oriented programming.

Classes in C#

The basic syntax for defining a class in C# is as follows,

[modifier] class ClassName
{
    // Field definition
    [modifier] dataType fieldName;

    // Property definition
    [modifier] dataType propertyName { get; set; }

    // Method definition
    [modifier] returnType methodName(parameters)
    {
        // Method code
    }
}
  • ClassName: Is the unique name given to the class.
  • Modifier: Can be public, private, protected, among others, to define the access level of the class, fields, properties, and methods.
  • dataType: Specifies the data type of the fields and properties.
  • fieldName, propertyName, methodName: Are the unique identifiers for the fields, properties, and methods, respectively.
  • returnType: Specifies the data type that the method returns as a result.
  • parameters: Are the variables used to pass information to the method when it is called.

Classes can be defined anywhere in the code, but it is common to define them inside a separate file with the .cs extension.

Composition of a class in C#

A class in C# is composed of three main elements: fields, properties, and methods.

Person
  • stringbirthDate
  • stringdni
  • stringName
  • stringSurname
  • stringGreet()
  • stringSendEmail()

The fields represent the variables or data that are part of a class. These can be of different types, such as integers, strings, booleans, etc. Fields are the way we store information within a class and allow us to manipulate it according to our needs.

The properties are a way to access and modify the fields of a class. They allow us to set rules and validations for data access, preventing unwanted or incorrect changes. Properties provide an abstraction layer that facilitates the management of fields and offers flexibility in how we interact with them.

The methods are the actions or behaviors that a class can perform. These can be functions that return a value or procedures that do not return anything. Methods allow us to modularize the code and break tasks into smaller, more manageable parts.

Basic Example

To create a class in C#, we use the keyword class followed by the name we want to give our class. Let’s see an example:

public class Person
{
    // Fields
    public int dni;
    private DateTime birthDate;
    
	// Properties
    public string Name { get; set; }
    private string Surname { get; set; }   

    // Methods
    public void Greet()
    {
        Console.WriteLine("Hello!");
    }  
}

In this example we have:

  • Class Declaration
  • Created fields, public dni and private birthDate.
  • Defined public property Name and private property Surname.
  • Defined a method Greet().

Using Classes

Creating Objects

To create an object of a class, the new operator is used followed by the class name, and optionally, arguments for the constructor if it has one.

Person person = new Person("Luis", 25);

Accessing Fields and Properties

The fields and properties of a class are accessed using dot notation (.).

Console.WriteLine(person.name);

Calling Methods

The methods of a class are called using dot notation (.).

person.Greet();

Practical Examples