C# Class

A class is a blueprint that defines what properties and behavior, the objects of this class should have.

class keyword is used to declare a class.

Example – C# Class

In the following example, we defined a class named Book. Ofcourse there is another class named Program where our main function is. But, we will focus on the class Book and make our discussions on it.

Program.cs

using System;

namespace CSharpExamples {
    class Book{
        public string author;
        public string title;

        public Book(string Title, string Author){
            title = Title;
            author = Author;
        }

        public void printBookDetails(){
            Console.WriteLine("\n---Book Details---\n==================");
            Console.WriteLine("Title  : "+title);
            Console.WriteLine("Author : "+author);
        }
    }
    class Program {
        static void Main(string[] args) {
            Book book1 = new Book("C# Tutorial", "TutorialKart");
            book1.printBookDetails();

            Book book2 = new Book("Java Tutorial", "Author1");
            book1.printBookDetails();
        }
    }
}

Output

---Book Details---
==================
Title  : C# Tutorial
Author : TutorialKart

---Book Details---
==================
Title  : C# Tutorial
Author : TutorialKart

Class

We used class keyword followed by class name Book. Then the definition of the class is enclosed between the curly braces.

Properties

We declared two public variables: title and author of datatype string. These are called properties of class.

Constructor

public Book(string Title, string Author){} is the constructor in which we assigned the arguments to the class properties. You can also have an empty constructor with no arguments passed.

Methods

We defined one method named printBookDetails() with access modifier public. The method accepts no arguments, hence empty parenthesis. And returns nothing, hence void.

ADVERTISEMENT

Create Class Object

We can create a new class object using new keyword.

In the above example, we created a new object of class type Book, using the following line of code.

Book book1 = new Book("C# Tutorial", "TutorialKart");

Book book1 declares that book1 is of type Book. new Book() creates a new object and assigns the object to book1Book("C# Tutorial", "TutorialKart") calls the constructor with the arguments of type (string, string).

Call a method on the Class Object

To call any method of the class object, you can use the class object reference, dot operator and then the method name with arguments if any.

book1.printBookDetails();

Information about a C# class

  • A class can be defined inside another class.
  • A class can have an access modifier.
  • A class can have multiple properties of different access types and datatypes.
  • A class can have multiple methods that return or not return any values and accept or do not accept arguments.