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

Static members vs instance members in C Sharp (C#) - Hands-On Comparison

Choose your learning style9 modes available
Static members vs instance members
📖 Scenario: Imagine you are creating a simple program to manage a library. You want to keep track of the total number of books in the library as well as details about each individual book.
🎯 Goal: You will build a class Book that has both static and instance members. The static member will count the total books, and the instance members will store details about each book. You will then display the total number of books and details of each book.
📋 What You'll Learn
Create a class Book with instance members Title and Author.
Add a static member TotalBooks to count how many books have been created.
Increment TotalBooks each time a new Book object is created.
Create at least two Book objects with different titles and authors.
Print the total number of books using the static member.
Print the details of each book using instance members.
💡 Why This Matters
🌍 Real World
Tracking shared data like total counts or settings across many objects is common in software like inventory systems or user management.
💼 Career
Understanding static vs instance members is essential for writing clean, efficient, and maintainable object-oriented code in professional C# development.
Progress0 / 4 steps
1
Create the Book class with instance members
Create a class called Book with two public instance string members: Title and Author. Do not add any static members yet.
C Sharp (C#)
Need a hint?

Instance members belong to each object. Use public string Title; and public string Author; inside the class.

2
Add a static member to count total books
Inside the Book class, add a public static integer member called TotalBooks initialized to 0. Also add a constructor that takes title and author as parameters, sets the instance members, and increments TotalBooks by 1.
C Sharp (C#)
Need a hint?

Static members belong to the class itself. Use public static int TotalBooks = 0;. The constructor sets instance members and increases the static count.

3
Create Book objects and use members
In the Main method, create two Book objects: one with title "1984" and author "George Orwell", and another with title "Pride and Prejudice" and author "Jane Austen". Store them in variables book1 and book2.
C Sharp (C#)
Need a hint?

Use new Book("1984", "George Orwell") to create the first book and assign it to book1. Do the same for book2.

4
Print total books and details of each book
Print the total number of books using Book.TotalBooks. Then print the title and author of book1 and book2 using their instance members.
C Sharp (C#)
Need a hint?

Use Console.WriteLine to print the static member TotalBooks and the instance members Title and Author of each book.