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 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 in a single entity, making it easier to reuse code and maintain our applications. They are the basis of object-oriented programming.
If you want to learn more about Objects, Classes, and Instances
check out the Object-Oriented Programming Course read more ⯈
Classes in C#
The basic syntax for defining a class in C# is as follows,
[modifier] class ClassName
{
// Definition of fields
[modifier] dataType fieldName;
// Definition of properties
[modifier] dataType propertyName { get; set; }
// Definition of methods
[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 of 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 within a separate file with the extension .cs
.
Composition of a class in C#
A class in C# is composed of three main elements: fields, properties, and methods.
- stringbirthDate
- stringdni
- stringName
- stringLastname
- stringGreet()
- stringSendEmail()
The fields represent the variables or data that are part of a class. These can be of different types, such as integers, text 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 establish rules and validations for data access, avoiding 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.
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 code and divide tasks into smaller, 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 Lastname { get; set; }
// Methods
public void Greet()
{
Console.WriteLine("Hello!");
}
}
In this example we have:
- Class Declaration
- Created fields, public
dni
and privatebirthDate
. - Defined properties, public
Name
and privateLastname
. - 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("John", 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
Representation of a Person
This Person
class defines a person with the Name
and Age
properties. It includes a constructor to initialize these fields and a Greet
method that prints a personalized greeting.
public class Person
{
// Fields
public string Name { get; set; } // Property for the person's name
public int Age { get; set; } // Property for the person's age
// Constructor Method
public Person(string name, int age)
{
Name = name; // Assigns the provided name to the Name field
Age = age; // Assigns the provided age to the Age field
}
// Method
public void Greet()
{
Console.WriteLine($"Hello, I'm {Name} and I'm {Age} years old!"); // Prints a greeting with the person's name and age
}
}
Representation of a Product
The Product
class represents a product with the Name
and Price
properties. It has a constructor to initialize these fields and a ShowInformation
method that prints the product details.
public class Product
{
// Fields
public string Name { get; set; } // Property for the product's name
public decimal Price { get; set; } // Property for the product's price
// Constructor Method
public Product(string name, decimal price)
{
Name = name; // Assigns the provided name to the Name field
Price = price; // Assigns the provided price to the Price field
}
// Method
public void ShowInformation()
{
Console.WriteLine($"Product: {Name}, Price: {Price}"); // Prints the product information
}
}