In this tutorial, we will explore the concepts of classes and objects in C#. Classes and objects are fundamental to object-oriented programming, which C# is heavily based on. By the end of this tutorial, you will understand how to define a class, create objects from that class, and use them to model real-world concepts.
What You Will Learn:
- Definition of classes and objects
- How to define a class
- How to create an object
- How to use class methods and properties
Prerequisites:
- Basic understanding of C# programming
- Familiarity with Visual Studio or any other C# IDE
In C#, a class is a blueprint for creating objects. An object is an instance of a class, and it can represent a person, a place, a bank account, an invoice, or any item that the program has to handle.
A class is defined using the class
keyword, followed by the name of the class. Here's an example of how to define a class.
public class Person
{
// class body
}
The class name, Person
in this case, follows the naming conventions for identifiers in C#.
You can create an object of a class using the new
keyword in C#. The new
keyword is used to instantiate an object of a class.
Person person1 = new Person();
In the code snippet above, person1
is an object of the Person
class.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void SayHello()
{
Console.WriteLine("Hello, my name is " + Name + " and I am " + Age + " years old.");
}
}
In the Person
class, Name
and Age
are properties, and the SayHello
method prints a message to the console.
Person person1 = new Person();
person1.Name = "John Doe";
person1.Age = 30;
person1.SayHello();
// Output: "Hello, my name is John Doe and I am 30 years old."
In this example, we create an object person1
from the Person
class, set the Name
and Age
properties, and call the SayHello
method.
In this tutorial, we've learned about classes and objects in C#, how to define a class, create an object, and use class properties and methods. This is a fundamental concept in object-oriented programming and is key to understanding how to structure and write effective C# code.
For further learning, consider exploring more about class constructors, encapsulation, inheritance, and polymorphism in C#.
Exercise 1:
Define a Car
class with properties for Make
, Model
, and Year
. Add a method Honk
that prints "Beep Beep!" to the console.
Solution:
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public void Honk()
{
Console.WriteLine("Beep Beep!");
}
}
Exercise 2:
Create a Car
object, set its properties, and call the Honk
method.
Solution:
Car myCar = new Car();
myCar.Make = "Toyota";
myCar.Model = "Corolla";
myCar.Year = 2020;
myCar.Honk();
// Output: "Beep Beep!"