C# Class
A class in C# is a user-defined reference type that describes the data and behavior shared by its objects. The class acts as a blueprint, while each object is a separate instance created from that blueprint.
The class keyword is used to declare a class. A class can contain fields, properties, constructors, methods, events, and other members.
C# Class Declaration Syntax
The basic syntax for declaring a C# class is shown below.
access_modifier class ClassName
{
// Fields, properties, constructors, and methods
}
The access modifier is optional. When a top-level class does not specify an access modifier, it is internal by default. Class names conventionally use PascalCase, such as Book, CustomerAccount, or StudentRecord.
Example of a C# Class
In the following example, a class named Book defines data for a book and a method that prints the book details. The Program class contains the Main method from which Book objects are created.
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
The output displays the first book twice because the last statement calls book1.printBookDetails() again. To print the second object’s values, that statement would need to call book2.printBookDetails().
Members of the Book Class
Class Name and Body
The declaration begins with the class keyword followed by the class name Book. All members of the class are enclosed within curly braces.
Fields in the Book Class
The variables title and author are public fields of type string. Each Book object receives its own values for these instance fields.
Fields directly store data. In application code, properties are often preferred because they provide controlled access to that data.
Book Class Constructor
public Book(string Title, string Author){} is a constructor. A constructor has the same name as the class and has no return type. It runs when a new object is created and initializes the object’s fields using the supplied arguments.
A class can define multiple constructors with different parameter lists. This is known as constructor overloading. When no constructor is declared, C# supplies a parameterless constructor only when the class has no other instance constructor.
Book Class Method
The method printBookDetails() has the access modifier public. It accepts no arguments because its parentheses are empty. Its return type is void, which means it does not return a value.
Create an Object of a C# Class
An object is created from a class by using the new operator. The following statement creates an object of type Book.
Book book1 = new Book("C# Tutorial", "TutorialKart");
Book book1 declares a variable named book1 whose type is Book. The expression new Book("C# Tutorial", "TutorialKart") creates the object and invokes the constructor that accepts two string arguments. The resulting object reference is assigned to book1.
Access C# Class Members with the Dot Operator
Accessible fields, properties, and methods of an object are referenced with the dot operator. The following statement calls the printBookDetails() method on book1.
book1.printBookDetails();
Similarly, a public field can be read or assigned through the object reference.
Console.WriteLine(book1.title);
book1.author = "New Author";
C# Fields and Properties
A field is a variable declared directly in a class. A property provides accessor methods, usually get and set, for reading and updating a value. Properties are commonly used in public class designs because validation or other logic can be added later without changing how callers access the value.
class Book
{
public string Title { get; set; }
public string Author { get; set; }
public Book(string title, string author)
{
Title = title;
Author = author;
}
}
The declarations Title { get; set; } and Author { get; set; } are auto-implemented properties. C# automatically provides their underlying storage.
C# Class Access Modifiers
Access modifiers control where a class or class member can be used. Common modifiers include:
public: accessible from any code that can reference the containing type or assembly.private: accessible only within the containing class.protected: accessible within the containing class and derived classes.internal: accessible within the same assembly.protected internal: accessible within the same assembly or from a derived class.private protected: accessible within the containing class or derived classes in the same assembly.
A top-level class can be declared public or internal. A nested class can use the full set of class-member access modifiers.
Instance Members and Static Members in a C# Class
Instance members belong to individual objects. Static members belong to the class itself and are shared rather than stored separately in every object.
class Book
{
public static int BookCount;
public string Title;
public Book(string title)
{
Title = title;
BookCount++;
}
}
Title is accessed through an object, while BookCount is accessed through the class name, as in Book.BookCount.
C# Class and Object Difference
| Class | Object |
|---|---|
| Defines a type and its members. | Represents an instance of that type. |
Declared with the class keyword. | Usually created with the new operator. |
| Describes the data and behavior objects can have. | Stores the actual instance data. |
| One class declaration can be used repeatedly. | Multiple independent objects can be created from one class. |
Important Characteristics of C# Classes
- A class is a reference type.
- A class can contain fields, properties, constructors, methods, events, indexers, operators, and nested types.
- A class can be declared inside another class as a nested class.
- A class can implement one or more interfaces.
- A class can inherit from one base class.
- A class can define multiple constructors and methods through overloading.
- Class members can be instance members or static members.
- Access modifiers control the visibility of classes and their members.
Common Mistakes When Working with C# Classes
- Calling a method on the wrong object reference, such as using
book1whenbook2was intended. - Adding a return type to a constructor. Constructors must not declare any return type, including
void. - Trying to access a private member from outside its class.
- Accessing an instance member through the class name instead of through an object.
- Assuming two object variables contain separate objects after assigning one variable to the other. Class variables store references.
- Exposing mutable fields publicly when a property or method would provide safer access.
C# Class FAQs
Is a C# class a value type or a reference type?
A C# class is a reference type. A class variable stores a reference to an object rather than containing the complete object data directly.
Can a C# class have more than one constructor?
Yes. A class can declare multiple constructors as long as their parameter lists differ. This is called constructor overloading.
Can a C# class be created without the new operator?
Ordinary class instances are typically created with new. Objects may also be supplied by frameworks, deserializers, dependency-injection containers, reflection APIs, or factory methods, so application code does not always contain the direct new expression.
What is the default access modifier of a C# class?
A top-level class is internal by default. A nested class is private by default.
Can a C# class inherit from multiple classes?
No. A C# class can inherit directly from only one base class, but it can implement multiple interfaces.
TutorialKart.com