Skip to main content

Creating a Class

Introduction to C# Classes

In C#, a class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods). The class is the most fundamental building block in C#, and is a key component of C# object-oriented programming.

Creating a Class in C#

Creating a class in C# involves defining a new type. A class is defined with the keyword class, followed by the name of the class and a pair of curly braces {}. All the code that belongs to the class is defined within these braces. Let's create a simple class called Person.

class Person
{
// Class members go here
}

Class Members

A class can contain several types of members:

  • Fields: These are variables that hold the state of the object.
  • Properties: These are accessors that read, write, or compute the value of a private field.
  • Methods: These are functions that perform operations on the object.

Fields

In our Person class, we might have fields for the person's name and age.

class Person
{
string name;
int age;
}

Properties

Properties are used to access the fields of a class. A property has a get accessor and a set accessor. The get accessor returns the value of the field, and the set accessor assigns a value to the field.

class Person
{
private string name;
private int age;

public string Name
{
get { return name; }
set { name = value; }
}

public int Age
{
get { return age; }
set { age = value; }
}
}

Methods

Methods define the behavior of a class. They are defined similarly to functions, but are associated with an object of the class. Let's add a method Introduce to our Person class that introduces the person.

class Person
{
private string name;
private int age;

public string Name
{
get { return name; }
set { name = value; }
}

public int Age
{
get { return age; }
set { age = value; }
}

public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}

Creating an Object

Once you've defined a class, you can create an object from that class. This is known as instantiation. To create an object, you use the new keyword followed by the name of the class.

Person person = new Person();

After creating an object, you can set its properties and call its methods.

person.Name = "John Doe";
person.Age = 25;
person.Introduce(); // Outputs: Hello, my name is John Doe and I am 25 years old.

Conclusion

That's it for our tutorial on creating a class in C#. We've covered how to define a class, add members to a class, and how to create an object from a class. Understanding classes and objects is fundamental to C# and object-oriented programming, so make sure you understand the concepts covered here. Happy coding!