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.
If you want to learn more about Objects, Classes, and Instances
check 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: 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.
- 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 privatebirthDate
. - Defined public property
Name
and private propertySurname
. - 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
Representation of a person
This Person
class 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
}
}
Representation of a product
The Product
class represents a product with the properties Name
and Price
. It has a constructor to initialize these fields and a method ShowInformation
that prints the product details.
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
}
}