Imagine you want to store information about many books: title, author, and pages. Why is using a class better than separate variables?
Think about how you keep related things together in real life, like a folder for papers.
Classes help group related information and actions together. This keeps code clean and easy to manage, especially when handling many items.
Look at this code and choose the output it produces.
class Book { public string Title; public string Author; public Book(string title, string author) { Title = title; Author = author; } } class Program { static void Main() { Book b = new Book("1984", "Orwell"); System.Console.WriteLine(b.Title + " by " + b.Author); } }
The constructor sets the Title and Author fields. The WriteLine prints them in order.
The program creates a Book object with Title "1984" and Author "Orwell". It prints them joined by " by ".
Find the reason this code causes a compile error.
class Car { string model; public Car(string m) { model = m; } } class Program { static void Main() { Car c = new Car("Tesla"); System.Console.WriteLine(c.model); } }
Think about the default access level of class fields in C#.
In C#, fields are private by default. Trying to access c.model outside the class causes an error.
Choose the code that correctly defines a class with a method that prints a message.
Remember C# method syntax requires return type and semicolons.
Option D correctly defines a public method with void return type and proper syntax. Others have errors like missing semicolon, wrong method signature, or invalid print function.
Analyze this code. How many objects are created and what is printed?
class Person { public string Name; public Person(string name) { Name = name; } } class Program { static void Main() { Person p1 = new Person("Alice"); Person p2 = p1; p2.Name = "Bob"; System.Console.WriteLine(p1.Name); } }
Think about what happens when you assign one object variable to another.
p1 and p2 point to the same object. Changing p2.Name changes p1.Name. Only one object is created. Output is Bob.