0
0
CsharpHow-ToBeginner · 3 min read

How to Create a Class in C# - Simple Guide

In C#, you create a class using the class keyword followed by the class name and curly braces to define its body. Inside the class, you can add fields, methods, and properties to describe its behavior and data.
📐

Syntax

A class in C# is defined using the class keyword, followed by the class name and a pair of curly braces { }. Inside these braces, you can add variables (called fields), methods (functions), and properties.

  • class: Keyword to declare a class.
  • ClassName: The name you give your class, usually starting with a capital letter.
  • { }: Curly braces that contain the class members.
csharp
class ClassName
{
    // Fields, methods, properties go here
}
💻

Example

This example shows how to create a simple class named Car with a field, a method, and how to create an object from it to use its method.

csharp
using System;

class Car
{
    public string brand; // Field to store brand name

    public void Honk()
    {
        Console.WriteLine("Beep beep!");
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car(); // Create an object of Car
        myCar.brand = "Toyota"; // Set the brand
        Console.WriteLine("My car brand is " + myCar.brand);
        myCar.Honk(); // Call the method
    }
}
Output
My car brand is Toyota Beep beep!
⚠️

Common Pitfalls

Some common mistakes when creating classes in C# include:

  • Forgetting to use public to make fields or methods accessible outside the class.
  • Not creating an object (instance) of the class before using its members.
  • Using incorrect capitalization for class names (by convention, class names start with uppercase).

Here is an example showing a wrong and right way:

csharp
// Wrong: Trying to access a field without creating an object
class Person
{
    public string name;
}

// This will cause an error:
// Console.WriteLine(Person.name); // Error: Cannot access instance member without object

// Right way:
class Person
{
    public string name;
}

class Program
{
    static void Main()
    {
        Person p = new Person();
        p.name = "Alice";
        Console.WriteLine(p.name); // Correct
    }
}
Output
Alice
📊

Quick Reference

  • class: Keyword to declare a class.
  • public: Access modifier to allow access from other classes.
  • Fields: Variables inside a class to hold data.
  • Methods: Functions inside a class to perform actions.
  • Object: An instance of a class created with new.

Key Takeaways

Use the class keyword followed by a name and curly braces to create a class.
Inside a class, define fields and methods to describe its data and behavior.
Create an object of the class with new to use its members.
Use public to make class members accessible outside the class.
Class names should start with a capital letter by convention.