0
0
C Sharp (C#)programming~5 mins

Class declaration syntax in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A class groups related data and actions together. It helps organize code like a blueprint for objects.

When you want to model a real-world thing with properties and behaviors.
When you need to create multiple similar objects with shared structure.
When organizing code into logical units for easier understanding and reuse.
When building programs that use object-oriented design.
When you want to hide details and expose only what is needed.
Syntax
C Sharp (C#)
class ClassName
{
    // Fields, properties, methods, constructors
}

Class names usually start with a capital letter.

Curly braces { } define the class body where you put data and actions.

Examples
Simple class named Car with no content yet.
C Sharp (C#)
class Car
{
    // Car details go here
}
Class Person with two fields: Name and Age.
C Sharp (C#)
class Person
{
    public string Name;
    public int Age;
}
Class Dog with a method Bark that prints a sound.
C Sharp (C#)
class Dog
{
    public void Bark()
    {
        Console.WriteLine("Woof!");
    }
}
Sample Program

This program defines a Book class with two fields and a method to show info. In Main, it creates a book object, sets its data, and prints it.

C Sharp (C#)
using System;

class Book
{
    public string Title;
    public string Author;

    public void DisplayInfo()
    {
        Console.WriteLine($"Title: {Title}, Author: {Author}");
    }
}

class Program
{
    static void Main()
    {
        Book myBook = new Book();
        myBook.Title = "The Little Prince";
        myBook.Author = "Antoine de Saint-Exupéry";
        myBook.DisplayInfo();
    }
}
OutputSuccess
Important Notes

Class members can be fields (data) or methods (actions).

Use public to allow access from outside the class.

Classes are templates; you create objects (instances) from them.

Summary

Classes group data and behavior into one unit.

Use class ClassName { } to declare a class.

Inside, define fields and methods to describe the object.