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 functionalities into a single entity, making it easier to reuse code and maintain our applications. They are the foundation 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
{
// Field definition
[modifier] dataType fieldName;
// Property definition
[modifier] dataType propertyName { get; set; }
// Method definition
[modifier] returnType methodName(parameters)
{
// Method code
}
}
- ClassName: This is the unique name given to the class.
- Modifier: It 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: These are the unique identifiers for the fields, properties, and methods, respectively.
- returnType: Specifies the data type that the method returns as a result.
- parameters: These 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 .cs
extension.
Composition of a class in C#
A class in C# consists of three main elements: fields, properties, and methods.
- 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 how 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 are a layer of abstraction that simplifies the handling of fields and provides us with 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 break tasks into smaller, manageable parts.
Basic Example
To create a class in C#, we use the keyword class
followed by the name we want to give to our class. Let’s look at 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 privatebirthDate
. - Defined properties
Name
public andSurname
private. - Defined a method
Greet()
.
Using Classes
Object Creation
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
Representing a Person
This class Person
defines a person with the properties Name
and Age
. It includes a constructor to initialize these fields and a method Greet
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 am {Name} and I am {Age} years old!"); // Prints a greeting with the person's name and age
}
}
Representing a Product
The class Product
represents a product with the properties Name
and Price
. It has a constructor to initialize these fields and a method ShowInformation
that prints the details of the product.
public class Product
{
// Fields
public string Name { get; set; } // Property for the product name
public decimal Price { get; set; } // Property for the product 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
}
}