csharp-clases

What are and how to use classes in C#

  • 7 min

An 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 template 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 functionality into a single entity, which facilitates code reuse and maintenance of our applications. They are the foundation of object-oriented programming.

If you want to learn more, check out the Object-Oriented Programming Course

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
    }
}
Copied!
  • ClassName: 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 in 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.

Persona
  • stringfechaNacimiento
  • stringdni
  • stringNombre
  • stringApellido
  • stringSaludar()
  • stringMandarEmail()

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 how we store information within a class and allow us to manipulate it according to our needs.

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 are an abstraction layer that makes it easier to handle fields and provides flexibility in how we interact with them.

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

Basic example

To create a class in C#, we use the class keyword followed by the name we want to give to 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!");
    }  
}
Copied!

In this example we have:

  • Class Declaration
  • Created fields, public dni and private birthDate.
  • Defined properties, public Name and private 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);
Copied!

Accessing Fields and Properties

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

Console.WriteLine(person.name);
Copied!

Calling Methods

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

person.Greet();
Copied!

Practical examples