Site icon NOTE BAHADUR

Unit 3: Creating Types in C#

Classes

A Class is a user-defined blueprint or template that defines the data (fields) and behavior (methods) of objects. It is one of the fundamental concepts of Object-Oriented Programming (OOP) in C#.

A class specifies what an object will contain and how it will behave. Objects are created from classes, just as many houses can be built from the same blueprint.

Purpose

Classes are used to:

Why Classes are Used

Without classes, programs become difficult to organize as they grow larger. Classes help developers:

Working Principle

Real-World Analogy

Imagine a Car.

The class defines:

Each actual car (Toyota, Honda, Tesla) is an object created from the same class.

      

Basic Syntax

class ClassName

{

    // Fields

    // Constructors

    // Methods

    // Properties

}

Declaring a Class

class Student

{

    public string Name;

    public int Age;

    public void Display()

    {

        Console.WriteLine(Name);

        Console.WriteLine(Age);

    }

}

Creating an Object

Objects are created using the new keyword.

Syntax

ClassName objectName = new ClassName();

Example

Student s1 = new Student();

Accessing Members

Use the dot (.) operator.

objectName.MemberName

Example

s1.Name = “Ram”;

s1.Age = 20;

s1.Display();

Complete Program

using System;

class Student

{

    public string Name;

    public int Age;

    public void Display()

    {

        Console.WriteLine(“Name : ” + Name);

        Console.WriteLine(“Age  : ” + Age);

    }

}

class Program

{

    static void Main()

    {

        Student s1 = new Student();

        s1.Name = “Ram”;

        s1.Age = 20;

        s1.Display();

    }

}

Output

Name : Ram

Age  : 20

Explanation

  1. A class named Student is created.
  2. It contains two fields.
  3. It contains one method.
  4. The Main() method creates an object.
  5. Values are assigned.
  6. The Display() method prints the values.

Memory Representation

Components of a Class

ComponentDescription
FieldsStore data
MethodsPerform tasks
ConstructorsInitialize objects
PropertiesProvide controlled access to fields
IndexersAllow object indexing
EventsNotify changes
Nested ClassesClass inside another class

Important Notes

Advantages

Limitations

Real-World Applications

Classes are widely used in:

Common Student Mistakes

❌ Incorrect

Student.Name = “Ram”;

Reason: Name is not static. It belongs to an object.

✔ Correct

Student s = new Student();

s.Name = “Ram”;

❌ Incorrect

Student s;

s.Name = “Ram”;

Reason: Object is declared but not created.

✔ Correct

Student s = new Student();

Best Practices

Viva Questions

  1. What is a class?
  2. Why are classes called blueprints?
  3. What is an object?
  4. What is the new keyword?
  5. Where are objects stored in memory?
  6. Is a class a value type or reference type?

Key Points for Exam

Constructors

A Constructor is a special member function of a class that is automatically executed when an object of the class is created. It is primarily used to initialize the object’s data members.

Purpose

Constructors are used to:

Why Constructors are Used

Without constructors, every object would require manual initialization after creation, increasing the chance of errors and inconsistent object states.

Characteristics

Constructor Execution Flow

Syntax

class Student

{

    public Student()

    {

    }

}

Types of Constructors

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor (user-defined pattern)
  4. Static Constructor (covered in Part 2)

Default Constructor

A default constructor takes no parameters and initializes the object with predefined values.

Example

using System;

class Student

{

    string name;

    public Student()

    {

        name = “Unknown”;

    }

    public void Display()

    {

        Console.WriteLine(name);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Display();

    }

}

Output

Unknown

Explanation

Parameterized Constructor

A parameterized constructor accepts arguments, allowing different objects to be initialized with different values.

Syntax

ClassName(parameter_list)

{

}

Example

using System;

class Student

{

    string name;

    int age;

    public Student(string n, int a)

    {

        name = n;

        age = a;

    }

    public void Display()

    {

        Console.WriteLine(“Name : ” + name);

        Console.WriteLine(“Age  : ” + age);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student(“Sita”, 21);

        s.Display();

    }

}

Output

Name : Sita

Age  : 21

Working Principle

  1. Object creation begins.
  2. Memory is allocated.
  3. Matching constructor is selected based on arguments.
  4. Constructor initializes fields.
  5. Control returns to the calling code.
  6. The object is ready for use.

Constructor Call Diagram

Constructor Overloading

A class can have multiple constructors with different parameter lists.

Example

using System;

class Student

{

    public Student()

    {

        Console.WriteLine(“Default Constructor”);

    }

    public Student(string name)

    {

        Console.WriteLine(“Student : ” + name);

    }

}

class Program

{

    static void Main()

    {

        Student s1 = new Student();

        Student s2 = new Student(“Hari”);

    }

}

Output

Default Constructor

Student : Hari

Comparison Table

FeatureDefault ConstructorParameterized Constructor
ParametersNoYes
InitializationFixed valuesUser-supplied values
FlexibilityLowHigh
Invocationnew ClassName()new ClassName(args)

Advantages

Limitations

Real-World Applications

Constructors are commonly used to initialize:

Common Student Mistakes

❌ Incorrect

public void Student()

{

}

Reason: This is a method, not a constructor, because it has a return type.

✔ Correct

public Student()

{

}

❌ Incorrect

int Student()

{

    return 0;

}

Reason: Constructors cannot return a value.

✔ Correct

Student()

{

}

Best Practices

Viva Questions

  1. What is a constructor?
  2. Why does a constructor have no return type?
  3. When is a constructor executed?
  4. Can constructors be overloaded?
  5. What is the difference between a constructor and a method?
  6. What is a parameterized constructor?

Key Points for Exam

Deconstructors (Deconstruction)

Deconstruction is a C# feature that allows an object to be broken down into multiple individual variables using a special Deconstruct() method.

It provides a convenient way to extract values from an object in a single statement.

Purpose

Deconstruction is used to:

Why It Is Used

Normally, individual properties must be accessed separately.

Example:

string name = student.Name;

int age = student.Age;

Using deconstruction:

(string name, int age) = student;

This is shorter, cleaner, and easier to read.

Working Principle

Syntax

class ClassName

{

    public void Deconstruct(out Type1 value1,

                            out Type2 value2)

    {

        value1 = …;

        value2 = …;

    }

}

How Deconstruction Works

  1. An object is created.
  2. The object contains a Deconstruct() method.
  3. The compiler automatically calls Deconstruct().
  4. Values are assigned to output variables.
  5. Individual variables become available.

Example 1: Basic Deconstruction

using System;

class Student

{

    public string Name;

    public int Age;

    public Student(string n, int a)

    {

        Name = n;

        Age = a;

    }

    public void Deconstruct(out string name, out int age)

    {

        name = Name;

        age = Age;

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student(“Ram”, 20);

        (string studentName, int studentAge) = s;

        Console.WriteLine(studentName);

        Console.WriteLine(studentAge);

    }

}

Output

Ram

20

Explanation

Example 2: Three-Value Deconstruction

using System;

class Employee

{

    public string Name;

    public int Age;

    public string Department;

    public Employee(string n, int a, string d)

    {

        Name = n;

        Age = a;

        Department = d;

    }

    public void Deconstruct(out string name,

                            out int age,

                            out string dept)

    {

        name = Name;

        age = Age;

        dept = Department;

    }

}

class Program

{

    static void Main()

    {

        Employee e = new Employee(“Hari”, 25, “IT”);

        (string name, int age, string department) = e;

        Console.WriteLine(name);

        Console.WriteLine(age);

        Console.WriteLine(department);

    }

}

Output

Hari

25

IT

Memory Representation

Advantages

Limitations

Real-World Applications

Deconstruction is useful in:

Comparison Table

FeatureTraditional AccessDeconstruction
Number of statementsMultipleOne
ReadabilityModerateHigh
Code sizeLongerShorter
Object requiredYesYes

Common Student Mistakes

❌ Incorrect

(string n, int a) = student;

without defining:

Deconstruct(…)

Reason: The compiler cannot find a Deconstruct() method.

✔ Correct

public void Deconstruct(out string name,

                        out int age)

{

    name = Name;

    age = Age;

}

❌ Incorrect

public int Deconstruct(…)

Reason: Deconstruct() must have a void return type.

✔ Correct

public void Deconstruct(…)

Best Practices

Viva Questions

  1. What is deconstruction in C#?
  2. What is the purpose of the Deconstruct() method?
  3. Can multiple values be returned using deconstruction?
  4. What is the return type of Deconstruct()?
  5. How is deconstruction different from a constructor?

Key Points for Exam

thisReference

The this keyword is a reference variable that refers to the current object of a class.

It is used to access the current object’s members and resolve naming conflicts between instance variables and method or constructor parameters.

Purpose

The this keyword is used to:

Why It Is Used

When parameter names are the same as field names, the compiler cannot distinguish between them without this.

Working Principle

Syntax

this.memberName

Example 1: Accessing Current Object

using System;

class Student

{

    string name;

    public Student(string name)

    {

        this.name = name;

    }

    public void Display()

    {

        Console.WriteLine(this.name);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student(“Sita”);

        s.Display();

    }

}

Output

Sita

Explanation

Example 2: Constructor Chaining Using this

A constructor can call another constructor in the same class using the this keyword.

using System;

class Student

{

    string name;

    int age;

    public Student() : this(“Unknown”, 0)

    {

    }

    public Student(string name, int age)

    {

        this.name = name;

        this.age = age;

    }

    public void Display()

    {

        Console.WriteLine(“Name : ” + name);

        Console.WriteLine(“Age  : ” + age);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Display();

    }

}

Output

Name : Unknown

Age  : 0

Constructor Chaining Diagram

Example 3: Passing Current Object

using System;

class Student

{

    public void Show()

    {

        Helper.Display(this);

    }

}

class Helper

{

    public static void Display(Student s)

    {

        Console.WriteLine(“Current object received.”);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Show();

    }

}

Output

Current object received.

Uses of this

UseDescription
Access current objectthis.name
Resolve naming conflictsField vs parameter
Constructor chaining: this(…)
Pass current objectMethod(this)
Return current objectreturn this;

Comparison Table

Featurethisbase
Refers toCurrent objectBase class object
Used insideSame classDerived class
Constructor chainingYesNo
Access parent membersNoYes

Advantages

Limitations

Real-World Applications

The this keyword is commonly used in:

Common Student Mistakes

❌ Incorrect

public static void Show()

{

    Console.WriteLine(this);

}

Reason: this cannot be used in a static method.

✔ Correct

public void Show()

{

    Console.WriteLine(this);

}

❌ Incorrect

name = name;

Reason: The parameter is assigned to itself; the field remains unchanged.

✔ Correct

this.name = name;

Best Practices

Viva Questions

  1. What is the this keyword?
  2. Why is this required when parameter names match field names?
  3. Can this be used in static methods? Why or why not?
  4. What is constructor chaining?
  5. How can this be used to pass the current object?

Key Points for Exam

Properties

A Property is a special member of a class that provides a controlled way to read, write, or compute the value of a private field.

Properties act as an interface between the class’s private data and the outside world. They support the principle of Encapsulation by hiding the implementation details while allowing safe access to data.

Purpose

Properties are used to:

Why Properties are Used

Suppose a Student class has an Age field. If the field is declared public, any user can assign an invalid value such as -10.

Using a property, we can validate the value before assigning it.

Working Principle

Syntax

class ClassName

{

    private DataType fieldName;

    public DataType PropertyName

    {

        get

        {

            return fieldName;

        }

        set

        {

            fieldName = value;

        }

    }

}

Components of a Property

ComponentPurpose
private fieldStores the actual data
getReturns the value
setAssigns a value
valueImplicit parameter used inside set

Example 1: Property with Get and Set

using System;

class Student

{

    private string name;

    public string Name

    {

        get

        {

            return name;

        }

        set

        {

            name = value;

        }

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Name = “Ram”;

        Console.WriteLine(s.Name);

    }

}

Output

Ram

Explanation

  1. name is private.
  2. External code cannot access it directly.
  3. The property Name provides controlled access.
  4. set stores the value.
  5. get retrieves the value.

Example 2: Property with Validation

using System;

class Student

{

    private int age;

    public int Age

    {

        get

        {

            return age;

        }

        set

        {

            if (value >= 0)

                age = value;

            else

                Console.WriteLine(“Invalid Age”);

        }

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Age = 20;

        Console.WriteLine(s.Age);

        s.Age = -5;

    }

}

Output

20

Invalid Age

Explanation

Auto-Implemented Properties

When no extra validation is required, C# allows auto-implemented properties.

Syntax

public string Name

{

    get;

    set;

}

Example

using System;

class Student

{

    public string Name

    {

        get;

        set;

    }

    public int Age

    {

        get;

        set;

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Name = “Sita”;

        s.Age = 21;

        Console.WriteLine(s.Name);

        Console.WriteLine(s.Age);

    }

}

Output

Sita

21

Read-Only Property

A read-only property contains only a get accessor.

public int RollNo

{

    get;

}

The value can typically be assigned through a constructor.

Write-Only Property

A write-only property contains only a set accessor.

private string password;

public string Password

{

    set

    {

        password = value;

    }

}

Property Types

Property TypeDescription
Read-WriteHas both get and set
Read-OnlyHas only get
Write-OnlyHas only set
Auto-ImplementedCompiler creates the backing field automatically

Memory Representation

Properties vs Public Fields

FeaturePublic FieldProperty
EncapsulationNoYes
ValidationNoYes
SecurityLowHigh
RecommendedNoYes
FlexibilityLimitedHigh

Advantages

Limitations

Real-World Applications

Properties are used in:

Common Student Mistakes

❌ Incorrect

public int Age;

when validation is required.

✔ Correct

private int age;

public int Age

{

    get { return age; }

    set

    {

        if (value >= 0)

            age = value;

    }

}

❌ Incorrect

set

{

    age = Age;

}

Reason: This causes infinite recursion because Age calls the property itself.

✔ Correct

set

{

    age = value;

}

Best Practices

Viva Questions

  1. What is a property?
  2. Why are properties preferred over public fields?
  3. What is the difference between get and set?
  4. What is an auto-implemented property?
  5. What is the purpose of the value keyword?

Key Points for Exam

Indexers

An Indexer is a special member of a class that allows an object to be accessed like an array using an index.

Instead of calling methods such as Get() or Set(), indexers allow array-like syntax.

Purpose

Indexers are used to:

Why Indexers are Used

Without an indexer:

student.GetName(0);

With an indexer:

student[0];

The second approach is shorter and easier to understand.

Working Principle

Syntax

public DataType this[int index]

{

    get

    {

        …

    }

    set

    {

        …

    }

}

Example: Indexer

using System;

class Student

{

    private string[] names = new string[3];

    public string this[int index]

    {

        get

        {

            return names[index];

        }

        set

        {

            names[index] = value;

        }

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s[0] = “Ram”;

        s[1] = “Sita”;

        s[2] = “Hari”;

        Console.WriteLine(s[0]);

        Console.WriteLine(s[1]);

        Console.WriteLine(s[2]);

    }

}

Output

Ram

Sita

Hari

Explanation

Memory Representation

Indexers vs Properties

FeaturePropertyIndexer
Name      Has a nameUses this
Parameters            NoYes
Access  obj.Nameobj[0]
Purpose  Access a single             valueAccess indexed values

Advantages

Limitations

Real-World Applications

Indexers are commonly used in:

Common Student Mistakes

❌ Incorrect

public string Index[int i]

{

}

Reason: Indexers do not have a custom name.

✔ Correct

public string this[int i]

{

    get;

    set;

}

❌ Incorrect

Console.WriteLine(s[5]);

when the array size is only 3.

Reason: Causes an IndexOutOfRangeException.

✔ Correct

Console.WriteLine(s[2]);

Best Practices

Viva Questions

  1. What is an indexer?
  2. Why does an indexer use the this keyword?
  3. How is an indexer different from a property?
  4. Can an indexer have get and set accessors?
  5. Where are indexers commonly used?

Key Points for Exam

Summary Table

TopicKey Idea
ClassesBlueprint for creating objects
ConstructorsInitialize objects automatically
DeconstructionExtract multiple values using Deconstruct()
this ReferenceRefers to the current object
PropertiesControlled access to private fields
IndexersAllow array-like access to objects

Practical/Laboratory Preparation

Be able to write programs that:

Last-Minute Revision Checklist

Static Constructors

A Static Constructor is a special constructor that is used to initialize static members of a class. It is executed automatically only once, before the first object is created or before any static member is accessed.

Unlike instance constructors, a static constructor initializes data that belongs to the class itself rather than individual objects.

Purpose

Static constructors are used to:

Why It Is Used

Suppose a class contains a static variable that stores the name of a university. Since this value is common to all objects, it should be initialized only once.

Without a static constructor, the static variable would have to be initialized manually.

Working Principle

Characteristics

Syntax

class ClassName

{

    static ClassName()

    {

        // Initialization code

    }

}

Example 1: Static Constructor

using System;

class University

{

    public static string UniversityName;

    static University()

    {

        UniversityName = “Tribhuvan University”;

        Console.WriteLine(“Static Constructor Executed”);

    }

    public void Display()

    {

        Console.WriteLine(“University: ” + UniversityName);

    }

}

class Program

{

    static void Main()

    {

        University u1 = new University();

        u1.Display();

        University u2 = new University();

        u2.Display();

    }

}

Output

Static Constructor Executed

University: Tribhuvan University

University: Tribhuvan University

Explanation

  1. The class is accessed for the first time.
  2. The static constructor runs automatically.
  3. UniversityName is initialized.
  4. The second object does not execute the static constructor again.

Memory Representation

Static Constructor vs Instance Constructor

FeatureStatic ConstructorInstance Constructor
KeywordstaticNone
ParametersNot allowedAllowed
CalledAutomatically onceEvery object creation
PurposeInitialize static membersInitialize instance members
Number AllowedOneMultiple (overloaded)

Advantages

Limitations

Real-World Applications

Static constructors are commonly used for:

Common Student Mistakes

❌ Incorrect

static Student(int x)

{

}

Reason: Static constructors cannot have parameters.

✔ Correct

static Student()

{

}

❌ Incorrect

Student.Student();

Reason: Static constructors cannot be called directly.

✔ Correct

They execute automatically when the class is first used.

Best Practices

Viva Questions

  1. What is a static constructor?
  2. When is a static constructor executed?
  3. Can a static constructor have parameters?
  4. How many static constructors can a class have?
  5. What is the difference between static and instance constructors?

Key Points for Exam

Static Classes

A Static Class is a class that contains only static members and cannot be instantiated.

A static class acts as a container for methods and data that are shared across the application.

Purpose

Static classes are used to:

Why It Is Used

Some operations do not require objects. For example, mathematical calculations are independent of any particular object.

Instead of:

Calculator c = new Calculator();

c.Add();

We can directly write:

Calculator.Add();

Working Principle

Syntax

static class ClassName

{

    public static void MethodName()

    {

    }

}

Example

using System;

static class Calculator

{

    public static int Add(int a, int b)

    {

        return a + b;

    }

}

class Program

{

    static void Main()

    {

        Console.WriteLine(Calculator.Add(10, 20));

    }

}

Output

30

Explanation

Characteristics

Static Class Diagram

Static Class vs Normal Class

FeatureStatic ClassNormal Class
Object CreationNot allowedAllowed
Instance MembersNot allowedAllowed
Static MembersAllowedAllowed
InheritanceCannot inheritCan inherit
ConstructorStatic onlyInstance and static

Advantages

Limitations

Real-World Applications

Static classes are commonly used for:

Common Student Mistakes

❌ Incorrect

Calculator c = new Calculator();

Reason: Static classes cannot be instantiated.

✔ Correct

Calculator.Add(5, 10);

❌ Incorrect

static class Student

{

    public int Age;

}

Reason: Static classes cannot contain instance fields.

✔ Correct

public static int Age;

Best Practices

Viva Questions

  1. What is a static class?
  2. Why can’t static classes be instantiated?
  3. Can a static class contain instance methods?
  4. Can a static class inherit another class?
  5. Give examples of static classes.

Key Points for Exam

Finalizers

A Finalizer is a special method that is automatically executed by the .NET Garbage Collector before an object is permanently removed from memory.

A finalizer is also known as a destructor in C# syntax.

Purpose

Finalizers are used to:

Why It Is Used

The .NET Garbage Collector automatically frees managed memory. However, unmanaged resources require explicit cleanup.

Working Principle

Syntax

class Student

{

    ~Student()

    {

        // Cleanup code

    }

}

Example

using System;

class Student

{

    ~Student()

    {

        Console.WriteLine(“Finalizer Executed”);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        Console.WriteLine(“Program Running”);

    }

}

Possible Output

Program Running

Finalizer Executed

Note: The exact time when the finalizer runs is not deterministic because it depends on the .NET Garbage Collector.

Explanation

Characteristics

Finalizer vs Constructor

FeatureConstructorFinalizer
PurposeInitialize objectClean up object
ExecutionObject creationBefore garbage collection
ParametersAllowedNot allowed
Called byProgrammer (new)Garbage Collector
NumberMultipleOne

Advantages

Limitations

Real-World Applications

Finalizers may be used when working with:

Common Student Mistakes

❌ Incorrect

Student.~Student();

Reason: Finalizers cannot be called directly.

✔ Correct

The Garbage Collector invokes the finalizer automatically.

❌ Incorrect

~Student(int x)

{

}

Reason: Finalizers cannot have parameters.

✔ Correct

~Student()

{

}

Best Practices

Viva Questions

  1. What is a finalizer?
  2. Who calls a finalizer?
  3. Can a finalizer have parameters?
  4. What is the difference between a constructor and a finalizer?
  5. Why is the execution time of a finalizer unpredictable?

Key Points for Exam

Dynamic Binding

Dynamic Binding (also called Late Binding or Runtime Polymorphism) is the process of determining which method to execute at runtime rather than at compile time.

In C#, dynamic binding is mainly achieved through method overriding, the dynamic keyword, and polymorphism.

Purpose

Dynamic binding is used to:

Why It Is Used

Consider a drawing application where different shapes (Circle, Rectangle, Triangle) have different ways of drawing themselves. Instead of writing separate code for each shape, dynamic binding allows a common interface while selecting the correct implementation at runtime.

Working Principle

         

Dynamic Binding vs Static Binding

FeatureStatic BindingDynamic Binding
Decision TimeCompile TimeRuntime
PolymorphismCompile-timeRuntime
SpeedFasterSlightly Slower
Method SelectionCompilerCLR at Runtime

Syntax

class Base

{

    public virtual void Show()

    {

    }

}

class Derived : Base

{

    public override void Show()

    {

    }

}

Example 1: Dynamic Binding Using Method Overriding

using System;

class Animal

{

    public virtual void Sound()

    {

        Console.WriteLine(“Animal makes a sound”);

    }

}

class Dog : Animal

{

    public override void Sound()

    {

        Console.WriteLine(“Dog barks”);

    }

}

class Cat : Animal

{

    public override void Sound()

    {

        Console.WriteLine(“Cat meows”);

    }

}

class Program

{

    static void Main()

    {

        Animal a;

        a = new Dog();

        a.Sound();

        a = new Cat();

        a.Sound();

    }

}

Output

Dog barks

Cat meows

Explanation

  1. a is a reference of type Animal.
  2. It first points to a Dog object.
  3. The overridden Sound() method in Dog executes.
  4. Later it points to a Cat object.
  5. The Cat version of Sound() executes.

The method is selected during runtime, demonstrating dynamic binding.

Example 2: Using the dynamic Keyword

The dynamic keyword defers type checking until runtime.

using System;

class Program

{

    static void Main()

    {

        dynamic value;

        value = 100;

        Console.WriteLine(value);

        value = “Hello”;

        Console.WriteLine(value);

        value = 3.14;

        Console.WriteLine(value);

    }

}

Output

100

Hello

3.14

Explanation

Runtime Method Selection Diagram

Advantages

Limitations

Real-World Applications

Dynamic binding is used in:

Common Student Mistakes

❌ Incorrect

public void Show()

{

}

when runtime polymorphism is intended.

✔ Correct

public virtual void Show()

{

}

and

public override void Show()

{

}

❌ Incorrect

dynamic x = “ABC”;

Console.WriteLine(x.Lengthh);

Reason: Lengthh is misspelled. The error occurs at runtime because dynamic bypasses compile-time checking.

✔ Correct

dynamic x = “ABC”;

Console.WriteLine(x.Length);

Best Practices

Viva Questions

  1. What is dynamic binding?
  2. What is the difference between static and dynamic binding?
  3. What is runtime polymorphism?
  4. What is the purpose of the virtual keyword?
  5. What is the dynamic keyword?

Key Points for Exam

Operator Overloading

Operator Overloading is a feature in C# that allows existing operators to have user-defined meanings when applied to objects of a class.

For example, the + operator normally adds numbers. With operator overloading, it can also combine two objects.

Purpose

Operator overloading is used to:

Why It Is Used

Suppose we have two Complex numbers.

Without operator overloading:

Complex c3 = c1.Add(c2);

With operator overloading:

Complex c3 = c1 + c2;

The second form is more natural and easier to understand.

Working Principle

Syntax

public static ReturnType operator +(Type a, Type b)

{

}

Rules for Operator Overloading

Example: Overloading the + Operator

using System;

class Complex

{

    public int Real;

    public int Imaginary;

    public Complex(int r, int i)

    {

        Real = r;

        Imaginary = i;

    }

    public static Complex operator +(Complex c1, Complex c2)

    {

        return new Complex(

            c1.Real + c2.Real,

            c1.Imaginary + c2.Imaginary

        );

    }

    public void Display()

    {

        Console.WriteLine(Real + ” + ” + Imaginary + “i”);

    }

}

class Program

{

    static void Main()

    {

        Complex c1 = new Complex(2, 3);

        Complex c2 = new Complex(4, 5);

        Complex c3 = c1 + c2;

        c3.Display();

    }

}

Output

6 + 8i

Explanation

  1. Two Complex objects are created.
  2. The + operator calls the overloaded method.
  3. A new Complex object is returned.
  4. The result is displayed.

Example: Overloading the == Operator

using System;

class Student

{

    public int Roll;

    public Student(int r)

    {

        Roll = r;

    }

    public static bool operator ==(Student s1, Student s2)

    {

        return s1.Roll == s2.Roll;

    }

    public static bool operator !=(Student s1, Student s2)

    {

        return s1.Roll != s2.Roll;

    }

    public override bool Equals(object obj)

    {

        return obj is Student s && Roll == s.Roll;

    }

    public override int GetHashCode()

    {

        return Roll.GetHashCode();

    }

}

class Program

{

    static void Main()

    {

        Student s1 = new Student(1);

        Student s2 = new Student(1);

        Console.WriteLine(s1 == s2);

    }

}

Output

True

Commonly Overloaded Operators

OperatorPurpose
+Addition
Subtraction
*Multiplication
/Division
%Modulus
==Equality
!=Inequality
<Less Than
>Greater Than
<=Less Than or Equal
>=Greater Than or Equal

Operator Overloading Flow

Advantages

Limitations

Real-World Applications

Operator overloading is useful in:

Common Student Mistakes

❌ Incorrect

public Complex operator +(Complex a, Complex b)

Reason: Operator methods must be static.

✔ Correct

public static Complex operator +(Complex a, Complex b)

❌ Incorrect

Overloading == without overloading !=.

Reason: These operators should be overloaded together for consistent behavior.

✔ Correct

Implement both == and !=, and also override Equals() and GetHashCode().

Best Practices

Viva Questions

  1. What is operator overloading?
  2. Why must overloaded operators be static?
  3. Which operators can be overloaded?
  4. Why should == and != be overloaded together?
  5. Give a practical use of operator overloading.

Key Points for Exam

Inheritance

Inheritance is an Object-Oriented Programming (OOP) feature that allows one class to acquire the properties and methods of another class.

The existing class whose members are inherited is called the Base Class (Parent Class or Super Class), while the new class that inherits those members is called the Derived Class (Child Class or Sub Class).

Inheritance promotes code reusability, reduces code duplication, and supports the “is-a” relationship.

Purpose

Inheritance is used to:

Why It Is Used

Suppose a university management system has a Person class containing common information such as Name and Age.

Instead of writing the same code in Student, Teacher, and Staff classes, these classes can inherit from Person.

This saves development time and improves code organization.

Working Principle

       

Important Definitions

TermDefinition
Base ClassClass whose members are inherited
Derived ClassClass that inherits from another class
Parent ClassAnother name for Base Class
Child ClassAnother name for Derived Class
:Inheritance operator in C#

Syntax

class BaseClass

{

    // Base members

}

class DerivedClass : BaseClass

{

    // Additional members

}

General Working Process

Base Class and Derived Class

Base Class

A Base Class is a class whose members are inherited by another class.

Example

class Person

{

    public string Name;

    public void Display()

    {

        Console.WriteLine(Name);

    }

}

Derived Class

A Derived Class inherits members from the base class and can also define additional members.

Example

class Student : Person

{

    public int Roll;

}

Complete Program: Base and Derived Class

using System;

class Person

{

    public string Name;

    public void Display()

    {

        Console.WriteLine(“Name : ” + Name);

    }

}

class Student : Person

{

    public int Roll;

    public void ShowRoll()

    {

        Console.WriteLine(“Roll : ” + Roll);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Name = “Ram”;

        s.Roll = 15;

        s.Display();

        s.ShowRoll();

    }

}

Output

Name : Ram

Roll : 15

Explanation

  1. Person is the base class.
  2. Student inherits Person.
  3. Student automatically gets the Name field and Display() method.
  4. Student adds its own Roll field and ShowRoll() method.
  5. The object accesses both inherited and its own members.

Memory Representation

Members Inherited

A derived class can inherit:

A derived class cannot directly access:

Single Inheritance

Single Inheritance is a type of inheritance in which one derived class inherits from only one base class.

It is the simplest and most commonly used form of inheritance.

Diagram

    

Syntax

class Person

{

}

class Student : Person

{

}

Complete Program: Single Inheritance

using System;

class Person

{

    public void DisplayPerson()

    {

        Console.WriteLine(“Person Information”);

    }

}

class Student : Person

{

    public void DisplayStudent()

    {

        Console.WriteLine(“Student Information”);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.DisplayPerson();

        s.DisplayStudent();

    }

}

Output

Person Information

Student Information

Working Principle

  1. Person is created first.
  2. Student inherits all accessible members.
  3. The Student object can call both inherited and own methods.

Real-World Example

Every Student is a Person, but every Person is not necessarily a Student.

This is known as an “is-a” relationship.

Advantages

Limitations

Multilevel Inheritance

Multilevel Inheritance is a type of inheritance in which a class inherits from another derived class, forming a chain of inheritance.

Diagram

Syntax

class Person

{

}

class Student : Person

{

}

class GraduateStudent : Student

{

}

Complete Program

using System;

class Person

{

    public void ShowPerson()

    {

        Console.WriteLine(“Person”);

    }

}

class Student : Person

{

    public void ShowStudent()

    {

        Console.WriteLine(“Student”);

    }

}

class GraduateStudent : Student

{

    public void ShowGraduate()

    {

        Console.WriteLine(“Graduate Student”);

    }

}

class Program

{

    static void Main()

    {

        GraduateStudent g = new GraduateStudent();

        g.ShowPerson();

        g.ShowStudent();

        g.ShowGraduate();

    }

}

Output

Person

Student

Graduate Student

Explanation

Memory Hierarchy

Single vs Multilevel Inheritance

FeatureSingle InheritanceMultilevel Inheritance
Parent ClassesOneChain of classes
LevelsTwoThree or more
ComplexityLowMedium
ReusabilityGoodHigher

Real-World Applications

Inheritance is widely used in:

Example: University Management System

Person

├── Student

├── Teacher

└── Staff

This design avoids duplication of common attributes like Name, Address, and Phone.

Common Student Mistakes

❌ Incorrect

class Student inherits Person

{

}

Reason: C# uses the : operator, not the inherits keyword.

✔ Correct

class Student : Person

{

}

❌ Incorrect

Attempting to access a private base class member:

class Person

{

    private int age;

}

class Student : Person

{

    public void Show()

    {

        Console.WriteLine(age);

    }

}

Reason: Private members are not directly accessible in derived classes.

✔ Correct

Use a protected member or a public property/method to provide controlled access.

Best Practices

Viva Questions

  1. What is inheritance?
  2. What is the difference between a base class and a derived class?
  3. What is the purpose of inheritance?
  4. Explain the “is-a” relationship with an example.
  5. What is single inheritance?
  6. What is multilevel inheritance?
  7. Which operator is used to inherit a class in C#?
  8. Can a derived class access private members of the base class?

Key Points for Exam

Hierarchical Inheritance

Hierarchical Inheritance is a type of inheritance in which multiple derived classes inherit from a single base class.

In this type of inheritance, one parent class provides common properties and methods to several child classes.

Purpose

Hierarchical inheritance is used to:

Why It Is Used

Consider a university system:

Instead of writing common information repeatedly, all three classes inherit from the Person class.

Working Principle

   

Syntax

class Person

{

}

class Student : Person

{

}

class Teacher : Person

{

}

class Staff : Person

{

}

Complete Program

using System;

class Person

{

    public void DisplayPerson()

    {

        Console.WriteLine(“Person Details”);

    }

}

class Student : Person

{

    public void Study()

    {

        Console.WriteLine(“Student is studying.”);

    }

}

class Teacher : Person

{

    public void Teach()

    {

        Console.WriteLine(“Teacher is teaching.”);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        Teacher t = new Teacher();

        s.DisplayPerson();

        s.Study();

        Console.WriteLine();

        t.DisplayPerson();

        t.Teach();

    }

}

Output

Person Details

Student is studying.

Person Details

Teacher is teaching.

Explanation

Memory Diagram

 

Advantages

Limitations

Multiple Inheritance

Multiple Inheritance is a type of inheritance in which one class inherits from more than one base class.

Diagram

Does C# Support Multiple Inheritance?

No.

C# does not support multiple inheritance through classes.

The following code is invalid.

class A

{

}

class B

{

}

class C : A, B

{

}

Why Doesn’t C# Support It?

The main reason is to avoid the Diamond Problem.

Diamond Problem

   Suppose:

The compiler cannot determine which version should be used.

This ambiguity is called the Diamond Problem.

Alternative in C#

Instead of multiple inheritance through classes, C# uses Interfaces.

Example:

interface ITeacher

{

    void Teach();

}

interface IResearcher

{

    void Research();

}

class Professor : ITeacher, IResearcher

{

    public void Teach()

    {

        Console.WriteLine(“Teaching…”);

    }

    public void Research()

    {

        Console.WriteLine(“Researching…”);

    }

}

Output

Teaching…

Researching…

Multiple Inheritance vs Interfaces

FeatureMultiple InheritanceInterfaces
Supported in C#❌ No (Classes)✅ Yes
AmbiguityPossibleAvoided
Multiple BehaviorsLimitedSupported
RecommendedNoYes

Hybrid Inheritance

Hybrid Inheritance is a combination of two or more types of inheritance.

Diagram

   

Hybrid Inheritance in C#

Hybrid inheritance cannot be implemented using classes alone because it would require multiple inheritance.

However, it can be achieved using interfaces.

Example

using System;

interface IPrintable

{

    void Print();

}

interface IScannable

{

    void Scan();

}

class Printer : IPrintable, IScannable

{

    public void Print()

    {

        Console.WriteLine(“Printing…”);

    }

    public void Scan()

    {

        Console.WriteLine(“Scanning…”);

    }

}

class Program

{

    static void Main()

    {

        Printer p = new Printer();

        p.Print();

        p.Scan();

    }

}

Output

Printing…

Scanning…

Explanation

Types of Inheritance Summary

TypeSupported in C# ClassesSupported Using Interfaces
Single✅ Yes✅ Yes
Multilevel✅ Yes✅ Yes
Hierarchical✅ Yes✅ Yes
Multiple❌ No✅ Yes
Hybrid❌ Directly No✅ Yes

Advantages of Inheritance

Limitations of Inheritance

Real-World Applications

Inheritance is widely used in:

Banking System

Account

├── SavingAccount

├── CurrentAccount

└── LoanAccount

Hospital Management

Person

├── Doctor

├── Nurse

└── Patient

University Management

Person

├── Student

├── Teacher

└── Staff

Vehicle Management

Vehicle

├── Car

├── Bus

└── Bike

Comparison Table

TypeNumber of Parent ClassesSupported in C# Classes
Single1✅ Yes
MultilevelChain✅ Yes
Hierarchical1 Parent, Many Children✅ Yes
MultipleMany Parents❌ No
HybridCombinationVia Interfaces

Common Student Mistakes

❌ Incorrect

class C : A, B

{

}

Reason: Multiple inheritance through classes is not supported in C#.

✔ Correct

class C : A

{

}

interface IX

{

}

interface IY

{

}

class D : IX, IY

{

}

❌ Incorrect

Using inheritance where there is no “is-a” relationship.

Example:

Student inherits Library

Reason: A Student is not a Library.

✔ Correct

Student inherits Person

because a Student is a Person.

Best Practices

Viva Questions

  1. What is hierarchical inheritance?
  2. Why does C# not support multiple inheritance through classes?
  3. Explain the Diamond Problem.
  4. How can multiple inheritance be achieved in C#?
  5. What is hybrid inheritance?
  6. Which inheritance types are supported directly by C# classes?
  7. When should interfaces be preferred over inheritance?

Memory Trick

Remember the order of inheritance types with the mnemonic:

“SMHMH”

Revision Checklist

📘 Examination Tip

These inheritance topics are highly examinable:


Abstract Classes and Methods

An Abstract Class is a special type of class that cannot be instantiated (cannot create objects) and is designed to be inherited by other classes.

An abstract class acts as a blueprint for derived classes. It can contain both abstract methods (without implementation) and non-abstract methods (with implementation).

Purpose

Abstract classes are used to:

Why It Is Used

Consider a university management system where all people (students, teachers, staff) have a Display() method, but each displays different information.

An abstract class can define the common structure while allowing derived classes to provide their own implementation.

Working Principle

    

Characteristics

Syntax

abstract class ClassName

{

    public abstract void MethodName();

    public void NormalMethod()

    {

    }

}

Abstract Method

An Abstract Method is a method declared without a body. It must be implemented by the derived class using the override keyword.

Syntax

public abstract void Display();

Complete Program

using System;

abstract class Person

{

    public abstract void Display();

    public void ShowMessage()

    {

        Console.WriteLine(“Welcome to the University”);

    }

}

class Student : Person

{

    public override void Display()

    {

        Console.WriteLine(“Student Details”);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.ShowMessage();

        s.Display();

    }

}

Output

Welcome to the University

Student Details

Explanation

  1. Person is an abstract class.
  2. It contains an abstract method Display().
  3. Student inherits from Person.
  4. Student overrides the Display() method.
  5. The inherited normal method and overridden method are both executed.

Example: Multiple Derived Classes

using System;

abstract class Shape

{

    public abstract void Draw();

}

class Circle : Shape

{

    public override void Draw()

    {

        Console.WriteLine(“Drawing Circle”);

    }

}

class Rectangle : Shape

{

    public override void Draw()

    {

        Console.WriteLine(“Drawing Rectangle”);

    }

}

class Program

{

    static void Main()

    {

        Shape s1 = new Circle();

        Shape s2 = new Rectangle();

        s1.Draw();

        s2.Draw();

    }

}

Output

Drawing Circle

Drawing Rectangle

Memory Diagram

Abstract Class vs Normal Class

FeatureAbstract ClassNormal Class
Object CreationNot AllowedAllowed
Abstract MethodsYesNo
Normal MethodsYesYes
ConstructorAllowedAllowed
PurposeBase BlueprintGeneral Class

Abstract Class vs Interface

FeatureAbstract ClassInterface
FieldsYesNo (except constants)
ConstructorsYesNo
Method ImplementationYesDefault implementations are possible in modern C#, but traditionally no
Multiple InheritanceNoYes

Exam Note: For many university syllabi based on C# 7/.NET Framework, interfaces are generally taught as containing method declarations without implementations.

Advantages

Limitations

Real-World Applications

Abstract classes are used in:

Common Student Mistakes

❌ Incorrect

Person p = new Person();

Reason: Objects of abstract classes cannot be created.

✔ Correct

Person p = new Student();

❌ Incorrect

class Student : Person

{

}

Reason: The abstract method is not implemented.

✔ Correct

class Student : Person

{

    public override void Display()

    {

        Console.WriteLine(“Student”);

    }

}

Best Practices

Viva Questions

  1. What is an abstract class?
  2. Can an abstract class have constructors?
  3. Can an abstract class contain normal methods?
  4. What is an abstract method?
  5. Why can’t objects of abstract classes be created?

Key Points for Exam

base Keyword

The base keyword is used to access members (fields, methods, properties, or constructors) of the immediate base class from a derived class.

It helps distinguish between members of the base class and members of the derived class.

Purpose

The base keyword is used to:

Why It Is Used

Suppose a derived class overrides a method but still needs to execute the original implementation from the base class. The base keyword allows access to that implementation.

Working Principle

   

Syntax

Accessing a Base Class Method

base.MethodName();

Accessing a Base Class Constructor

class Student : Person

{

    public Student() : base()

    {

    }

}

Example 1: Calling a Base Class Method

using System;

class Person

{

    public void Display()

    {

        Console.WriteLine(“Person Information”);

    }

}

class Student : Person

{

    public void Show()

    {

        base.Display();

        Console.WriteLine(“Student Information”);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Show();

    }

}

Output

Person Information

Student Information

Explanation

Example 2: Calling a Base Class Constructor

using System;

class Person

{

    public Person(string name)

    {

        Console.WriteLine(“Name : ” + name);

    }

}

class Student : Person

{

    public Student(string name, int roll)

        : base(name)

    {

        Console.WriteLine(“Roll : ” + roll);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student(“Ram”, 10);

    }

}

Output

Name : Ram

Roll : 10

Constructor Execution Flow

Example 3: Accessing a Hidden Base Member

using System;

class Person

{

    public string Name = “Person”;

}

class Student : Person

{

    public new string Name = “Student”;

    public void Show()

    {

        Console.WriteLine(base.Name);

        Console.WriteLine(Name);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Show();

    }

}

Output

Person

Student

this vs base

Featurethisbase
Refers ToCurrent objectImmediate base class
Constructor ChainingYesYes
Access Current MembersYesNo
Access Base MembersNoYes

Advantages

Limitations

Real-World Applications

The base keyword is commonly used in:

Common Student Mistakes

❌ Incorrect

base.Name = “Ram”;

when Name is private in the base class.

Reason: Private members are not accessible in derived classes.

✔ Correct

Use a protected field or a public property.

❌ Incorrect

Student() : base

{

}

Reason: Parentheses are required when calling a constructor.

✔ Correct

Student() : base()

{

}

Best Practices

Viva Questions

  1. What is the base keyword?
  2. How is base different from this?
  3. Can base call constructors?
  4. Why is base.Display() used?
  5. Can base access private members?

Key Points for Exam

📘 Examination Tip

These topics are commonly tested:

Method Overloading

Method Overloading is a feature of C# that allows multiple methods in the same class to have the same name but different parameter lists.

The compiler distinguishes overloaded methods based on the number, type, or order of parameters. Method overloading is an example of compile-time polymorphism (static polymorphism).

Purpose

Method overloading is used to:

Why It Is Used

Suppose a calculator application needs to add:

Instead of creating methods like AddInt(), AddThreeInt(), and AddDouble(), we can use the same method name Add() with different parameter lists.

Working Principle

Rules for Method Overloading

Methods can be overloaded by changing:

Methods cannot be overloaded by changing only:

Syntax

class ClassName

{

    ReturnType MethodName(Parameter1)

    {

    }

    ReturnType MethodName(Parameter1, Parameter2)

    {

    }

    ReturnType MethodName(ParameterType1, ParameterType2)

    {

    }

}

Example 1: Overloading by Number of Parameters

using System;

class Calculator

{

    public int Add(int a, int b)

    {

        return a + b;

    }

    public int Add(int a, int b, int c)

    {

        return a + b + c;

    }

}

class Program

{

    static void Main()

    {

        Calculator obj = new Calculator();

        Console.WriteLine(obj.Add(10, 20));

        Console.WriteLine(obj.Add(10, 20, 30));

    }

}

Output

30

60

Explanation

Example 2: Overloading by Data Type

using System;

class Calculator

{

    public int Multiply(int a, int b)

    {

        return a * b;

    }

    public double Multiply(double a, double b)

    {

        return a * b;

    }

}

class Program

{

    static void Main()

    {

        Calculator obj = new Calculator();

        Console.WriteLine(obj.Multiply(5, 6));

        Console.WriteLine(obj.Multiply(2.5, 4.0));

    }

}

Output

30

10

Example 3: Overloading by Order of Parameters

using System;

class Demo

{

    public void Display(int number, string name)

    {

        Console.WriteLine(number + ” ” + name);

    }

    public void Display(string name, int number)

    {

        Console.WriteLine(name + ” ” + number);

    }

}

class Program

{

    static void Main()

    {

        Demo d = new Demo();

        d.Display(1, “Ram”);

        d.Display(“Hari”, 2);

    }

}

Output

1 Ram

Hari 2

Execution Flow

Invalid Overloading Example

class Test

{

    public int Show()

    {

        return 10;

    }

    public double Show()

    {

        return 20;

    }

}

Why is this invalid?

The compiler considers only the parameter list, not the return type. Therefore, these methods have identical signatures and cause a compilation error.

Method Overloading vs Method Overriding

FeatureMethod OverloadingMethod Overriding
PolymorphismCompile-timeRuntime
ClassSame classBase and derived classes
ParametersDifferentSame
Return TypeUsually same (cannot differ alone)Same or compatible
KeywordsNone requiredvirtual and override

Real-World Applications

Method overloading is used in:

Advantages

Limitations

Common Student Mistakes

❌ Incorrect

public int Sum(int a)

{

    return a;

}

public double Sum(int a)

{

    return a;

}

Reason: Only the return type is different, which is not allowed.

✔ Correct

public int Sum(int a)

{

    return a;

}

public int Sum(int a, int b)

{

    return a + b;

}

Best Practices

Viva Questions

  1. What is method overloading?
  2. Is method overloading compile-time or runtime polymorphism?
  3. Can methods be overloaded using only different return types?
  4. What are the rules for method overloading?
  5. Differentiate method overloading and method overriding.

Key Points for Exam

Object Type

Object is the ultimate base class of all types in C#. Every class, struct, interface, array, delegate, and built-in type ultimately derives from System.Object.

Because every type inherits from Object, an Object reference can store a value of any type.

Purpose

The Object type is used to:

Why It Is Used

Sometimes an application needs to store different types of data in a single collection or variable. Since every type derives from Object, this is possible.

Working Principle

  

Common Methods of Object

MethodPurpose
ToString()Returns string representation
Equals()Compares objects
GetHashCode()Returns hash code
GetType()Returns runtime type
ReferenceEquals()Checks reference equality (static method)

Syntax

object variable;

Example 1: Storing Different Types

using System;

class Program

{

    static void Main()

    {

        object value;

        value = 100;

        Console.WriteLine(value);

        value = “Hello”;

        Console.WriteLine(value);

        value = 3.14;

        Console.WriteLine(value);

    }

}

Output

100

Hello

3.14

Explanation

The same object variable stores:

because every type inherits from System.Object.

Example 2: Using GetType()

using System;

class Program

{

    static void Main()

    {

        object value = 100;

        Console.WriteLine(value.GetType());

        value = “DotNet”;

        Console.WriteLine(value.GetType());

    }

}

Output

System.Int32

System.String

Example 3: Boxing and Unboxing

using System;

class Program

{

    static void Main()

    {

        int number = 50;

        object obj = number;      // Boxing

        int result = (int)obj;    // Unboxing

        Console.WriteLine(result);

    }

}

Output

50

Boxing and Unboxing Diagram

Object vs dynamic

Featureobjectdynamic
Type CheckingCompile timeRuntime
Casting RequiredYesUsually No
PerformanceBetterSlightly Slower
Error DetectionCompile-timeRuntime

Advantages

Limitations

Real-World Applications

The Object type is commonly used in:

Common Student Mistakes

❌ Incorrect

object obj = 10;

int x = obj;

Reason: An explicit cast is required during unboxing.

✔ Correct

object obj = 10;

int x = (int)obj;

Best Practices

Viva Questions

  1. What is System.Object?
  2. Why is Object called the root of all classes?
  3. What are boxing and unboxing?
  4. Name four common methods of Object.
  5. Differentiate object and dynamic.

Key Points for Exam

📘Examination Tip

These topics are frequently examined:

Structs

A Struct (Structure) is a user-defined value type in C# that groups related data members and methods into a single unit.

Unlike classes, structs are value types, meaning they are stored directly (typically on the stack when used as local variables, though actual storage depends on context) and copied by value when assigned.

Structs are suitable for representing small, lightweight objects such as coordinates, points, dates, colors, and measurements.

Purpose

Structs are used to:

Why It Is Used

Suppose we need to represent the position of a student on a classroom seating chart.

Instead of storing separate variables:

Row = 5

Column = 8

we can create a structure named SeatPosition.

SeatPosition

————-

Row

Column

————-

This makes the program more organized.

Working Principle

Characteristics of Structs

Syntax

struct StructName

{

    // Fields

    // Properties

    // Methods

}

Example 1: Simple Structure

using System;

struct Student

{

    public int Roll;

    public string Name;

}

class Program

{

    static void Main()

    {

        Student s;

        s.Roll = 10;

        s.Name = “Ram”;

        Console.WriteLine(“Roll : ” + s.Roll);

        Console.WriteLine(“Name : ” + s.Name);

    }

}

Output

Roll : 10

Name : Ram

Explanation

Example 2: Structure with Constructor

using System;

struct Rectangle

{

    public int Length;

    public int Width;

    public Rectangle(int l, int w)

    {

        Length = l;

        Width = w;

    }

    public int Area()

    {

        return Length * Width;

    }

}

class Program

{

    static void Main()

    {

        Rectangle r = new Rectangle(10, 5);

        Console.WriteLine(“Area = ” + r.Area());

    }

}

Output

Area = 50

Explanation

Example 3: Array of Structures

using System;

struct Student

{

    public int Roll;

    public string Name;

}

class Program

{

    static void Main()

    {

        Student[] students = new Student[2];

        students[0].Roll = 1;

        students[0].Name = “Ram”;

        students[1].Roll = 2;

        students[1].Name = “Sita”;

        foreach (Student s in students)

        {

            Console.WriteLine(s.Roll + ” ” + s.Name);

        }

    }

}

Output

1 Ram

2 Sita

Memory Representation

Changing s2 does not affect s1 because structs are copied by value.

Structure vs Class

FeatureStructClass
TypeValue TypeReference Type
MemoryCopied by valueReference copied
InheritanceCannot inherit from classes/structsSupports inheritance
Default Base TypeSystem.ValueTypeSystem.Object
Suitable ForSmall dataComplex objects
PerformanceEfficient for small valuesBetter for large, shared objects

Struct vs Class Diagram

  

Passing Struct to Methods

By default, structs are passed by value.

using System;

struct Number

{

    public int Value;

}

class Program

{

    static void Change(Number n)

    {

        n.Value = 100;

    }

    static void Main()

    {

        Number num;

        num.Value = 50;

        Change(num);

        Console.WriteLine(num.Value);

    }

}

Output

50

Explanation

The Change() method receives a copy of the structure. Therefore, the original value remains unchanged.

Passing Struct by Reference

using System;

struct Number

{

    public int Value;

}

class Program

{

    static void Change(ref Number n)

    {

        n.Value = 100;

    }

    static void Main()

    {

        Number num;

        num.Value = 50;

        Change(ref num);

        Console.WriteLine(num.Value);

    }

}

Output

100

Real-World Applications

Structs are commonly used in:

Example: Coordinate System

Advantages

Limitations

Common Student Mistakes

❌ Incorrect

struct Student : Person

{

}

Reason: Structs cannot inherit from classes.

✔ Correct

struct Student

{

}

or implement interfaces if required.

❌ Incorrect

Student s;

Console.WriteLine(s.Roll);

Reason: Local struct variables must have all fields assigned before use.

✔ Correct

Student s;

s.Roll = 1;

s.Name = “Ram”;

Console.WriteLine(s.Roll);

Best Practices

Viva Questions

  1. What is a struct?
  2. Is a struct a value type or reference type?
  3. Can a struct inherit from a class?
  4. What is the default base type of a struct?
  5. When should you use a struct instead of a class?
  6. What happens when one struct is assigned to another?
  7. Can a struct contain methods and constructors?

Revision Checklist

Key Points for Exam

📘 Examination Tip

The following questions are frequently asked on structs:

Access Modifiers

Access Modifiers are C# keywords that control the visibility and accessibility of classes, methods, properties, fields, constructors, and other members.

They help protect data by allowing only authorized code to access specific members, supporting the principle of encapsulation in Object-Oriented Programming (OOP).

Purpose

Access modifiers are used to:

Why It Is Used

Suppose a banking application has an Account class. The account balance should not be modified directly by users. Instead, access should be controlled through methods such as Deposit() and Withdraw().

Working Principle

Types of Access Modifiers

ModifierAccessible Within ClassDerived ClassSame AssemblyOther Assembly
private
protected❌*
internal
protected internal✅ (derived classes)
public

*Only through inheritance.

1. Private

private members are accessible only within the class where they are declared.

Syntax

private int age;

Example

using System;

class Student

{

    private int marks = 90;

    public void Display()

    {

        Console.WriteLine(“Marks: ” + marks);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Display();

        // s.marks = 100; // Error

    }

}

Output

Marks: 90

Explanation

The marks field is private and cannot be accessed directly outside the Student class.

2. Public

public members are accessible from anywhere in the program.

Example

using System;

class Student

{

    public string Name = “Ram”;

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        Console.WriteLine(s.Name);

    }

}

Output

Ram

3. Protected

protected members are accessible within the same class and by derived classes.

Example

using System;

class Person

{

    protected string Name = “Hari”;

}

class Student : Person

{

    public void Show()

    {

        Console.WriteLine(Name);

    }

}

class Program

{

    static void Main()

    {

        Student s = new Student();

        s.Show();

    }

}

Output

Hari

4. Internal

internal members are accessible only within the same assembly (project).

Syntax

internal class Student

{

}

Example Scenario

5. Protected Internal

protected internal members are accessible either from derived classes or from any code within the same assembly.

Syntax

protected internal int Roll;

Access Modifier Hierarchy

Comparison Table

ModifierSame ClassDerived ClassSame ProjectOutside Project
private
protected❌*
internal
protected internal✅ (derived)
public

Real-World Applications

ScenarioModifier
Account Balanceprivate
Student Namepublic
Base Class Memberprotected
Internal Library Classesinternal
Shared Framework Componentsprotected internal

Advantages

Common Student Mistakes

❌ Incorrect

class Student

{

    private int marks = 80;

}

Student s = new Student();

Console.WriteLine(s.marks);

Reason: Private members cannot be accessed outside their class.

✔ Correct

class Student

{

    private int marks = 80;

    public int GetMarks()

    {

        return marks;

    }

}

Best Practices

Viva Questions

  1. What is an access modifier?
  2. Name the access modifiers in C#.
  3. What is the difference between private and public?
  4. When should protected be used?
  5. What is the purpose of internal?

Key Points for Exam

Interfaces

An Interface is a reference type in C# that defines a contract containing member declarations that implementing classes must provide.

An interface specifies what a class must do, not how it should do it.

Purpose

Interfaces are used to:

Why It Is Used

Suppose different payment methods—Credit Card, Mobile Wallet, and Bank Transfer—all process payments differently. An interface ensures that every payment class provides a Pay() method.

Working Principle

     

Characteristics

Syntax

interface IShape

{

    void Draw();

}

class Circle : IShape

{

    public void Draw()

    {

    }

}

Example 1: Basic Interface

using System;

interface IAnimal

{

    void Sound();

}

class Dog : IAnimal

{

    public void Sound()

    {

        Console.WriteLine(“Dog Barks”);

    }

}

class Program

{

    static void Main()

    {

        Dog d = new Dog();

        d.Sound();

    }

}

Output

Dog Barks

Explanation

Example 2: Multiple Interfaces

using System;

interface IPrinter

{

    void Print();

}

interface IScanner

{

    void Scan();

}

class MultiFunctionMachine : IPrinter, IScanner

{

    public void Print()

    {

        Console.WriteLine(“Printing…”);

    }

    public void Scan()

    {

        Console.WriteLine(“Scanning…”);

    }

}

class Program

{

    static void Main()

    {

        MultiFunctionMachine m = new MultiFunctionMachine();

        m.Print();

        m.Scan();

    }

}

Output

Printing…

Scanning…

Explanation

The MultiFunctionMachine class implements two interfaces, demonstrating how C# achieves multiple inheritance of behavior.

Interface Diagram

       

Interface vs Abstract Class

FeatureInterfaceAbstract Class
Object CreationNot AllowedNot Allowed
ConstructorsNoYes
FieldsNo (except constants)Yes
Multiple InheritanceYesNo
PurposeDefine a contractShare implementation and define a contract

Exam Note: In many university courses based on C# 7/.NET Framework, interfaces are taught as containing member declarations without implementations.

Advantages

Limitations

Real-World Applications

Interfaces are widely used in:

Common Student Mistakes

❌ Incorrect

interface IAnimal

{

    void Sound();

}

IAnimal a = new IAnimal();

Reason: Interfaces cannot be instantiated.

✔ Correct

IAnimal a = new Dog();

❌ Incorrect

class Dog : IAnimal

{

}

Reason: The Sound() method is not implemented.

✔ Correct

class Dog : IAnimal

{

    public void Sound()

    {

        Console.WriteLine(“Dog Barks”);

    }

}

Best Practices

Viva Questions

  1. What is an interface?
  2. Why are interfaces used?
  3. Can an interface be instantiated?
  4. Can a class implement multiple interfaces?
  5. Differentiate an interface from an abstract class.

Key Points for Exam

📘 Examination Tip

These topics are commonly tested in semester examinations:

Enums (Enumerations)

An Enumeration (Enum) is a user-defined value type in C# that consists of a set of named integral constants.

Instead of using numeric values such as 0, 1, 2, 3, enums allow programmers to use meaningful names such as Sunday, Monday, Tuesday, making programs easier to understand and maintain.

Purpose

Enums are used to:

Why It Is Used

Suppose a grading system stores student grades.

Without an enum:

1 = Distinction

2 = First Division

3 = Second Division

It is difficult to remember what each number means.

Using an enum:

Distinction

FirstDivision

SecondDivision

The program becomes more readable.

Working Principle

Syntax

enum EnumName

{

    Constant1,

    Constant2,

    Constant3

}

Example 1: Simple Enum

using System;

enum Day

{

    Sunday,

    Monday,

    Tuesday,

    Wednesday,

    Thursday,

    Friday,

    Saturday

}

class Program

{

    static void Main()

    {

        Day today = Day.Friday;

        Console.WriteLine(today);

    }

}

Output

Friday

Explanation

Default Numeric Values

By default, enum members start from 0.

enum Month

{

    January,

    February,

    March

}

Equivalent values are:

Enum MemberValue
January0
February1
March2

Example 2: Custom Values

using System;

enum Status

{

    Pending = 1,

    Approved = 2,

    Rejected = 3

}

class Program

{

    static void Main()

    {

        Status s = Status.Approved;

        Console.WriteLine(s);

        Console.WriteLine((int)s);

    }

}

Output

Approved

2

Explanation

Example 3: Enum in Switch Statement

using System;

enum TrafficSignal

{

    Red,

    Yellow,

    Green

}

class Program

{

    static void Main()

    {

        TrafficSignal signal = TrafficSignal.Green;

        switch (signal)

        {

            case TrafficSignal.Red:

                Console.WriteLine(“Stop”);

                break;

            case TrafficSignal.Yellow:

                Console.WriteLine(“Wait”);

                break;

            case TrafficSignal.Green:

                Console.WriteLine(“Go”);

                break;

        }

    }

}

Output

Go

Memory Representation

Enum vs Constants

FeatureEnumConstants
Group Related Values
ReadabilityHighMedium
Type SafetyBetterLimited
Fixed Set of ValuesYesNo

Real-World Applications

Enums are commonly used in:

Example:

Order Status

Pending

Processing

Delivered

Cancelled

Advantages

Limitations

Common Student Mistakes

❌ Incorrect

Day d = 1;

Reason: An integer cannot be assigned directly to an enum variable.

✔ Correct

Day d = (Day)1;

or

Day d = Day.Monday;

❌ Incorrect

Console.WriteLine(Day.8);

Reason: Enum members must be valid identifiers.

Best Practices

Viva Questions

  1. What is an enum?
  2. What is the default value of the first enum member?
  3. Can enum values be assigned manually?
  4. Why are enums preferred over numeric constants?
  5. How do you convert an enum to an integer?

Key Points for Exam

Generics

Generics are a C# feature that enables classes, methods, interfaces, delegates, and collections to work with different data types while maintaining compile-time type safety.

Instead of writing separate code for different data types, generics allow a single implementation that can be reused with many types.

Purpose

Generics are used to:

Why It Is Used

Without generics, separate classes may be required for integers, strings, or other types.

With generics:

Box<int>

Box<string>

Box<double>

The same class works with different data types.

Working Principle

   

Generic Type Parameter

The most common generic type parameter is T.

Other commonly used names:

ParameterMeaning
TType
TKeyKey Type
TValueValue Type
TResultResult Type

Syntax

Generic Class

class ClassName<T>

{

}

Generic Method

public void Display<T>(T value)

{

}

Example 1: Generic Class

using System;

class Box<T>

{

    public T Value;

    public void Show()

    {

        Console.WriteLine(Value);

    }

}

class Program

{

    static void Main()

    {

        Box<int> b1 = new Box<int>();

        b1.Value = 100;

        b1.Show();

        Box<string> b2 = new Box<string>();

        b2.Value = “DotNet”;

        b2.Show();

    }

}

Output

100

DotNet

Explanation

Example 2: Generic Method

using System;

class Demo

{

    public void Display<T>(T value)

    {

        Console.WriteLine(value);

    }

}

class Program

{

    static void Main()

    {

        Demo d = new Demo();

        d.Display(100);

        d.Display(“Hello”);

        d.Display(3.14);

    }

}

Output

100

Hello

3.14

Example 3: Generic Collection

using System;

using System.Collections.Generic;

class Program

{

    static void Main()

    {

        List<string> names = new List<string>();

        names.Add(“Ram”);

        names.Add(“Sita”);

        names.Add(“Hari”);

        foreach (string name in names)

        {

            Console.WriteLine(name);

        }

    }

}

Output

Ram

Sita

Hari

Generic Class Diagram

   

Generics vs Non-Generics

FeatureGenericsNon-Generics
Type SafetyHighLow
Type CastingUsually Not RequiredOften Required
Boxing/UnboxingReducedCommon
ReusabilityHighLower
PerformanceBetterLower

Real-World Applications

Generics are widely used in:

Advantages

Limitations

Common Student Mistakes

❌ Incorrect

Box box = new Box();

Reason: A generic type requires a type argument.

✔ Correct

Box<int> box = new Box<int>();

❌ Incorrect

List numbers = new List();

Reason: The generic type parameter is missing.

✔ Correct

List<int> numbers = new List<int>();

Best Practices

Viva Questions

  1. What are generics?
  2. Why are generics used?
  3. What is the purpose of T?
  4. What are the advantages of generic collections?
  5. Differentiate generic and non-generic collections.

Key Points for Exam

📘 Examination Tip

These topics are frequently asked in university examinations:

Important Questions

Group B (Short Questions – 5 Marks)

Classes and Constructors

  1. Define a class. Explain the syntax of a class with an example.
  2. What is a constructor? Explain its characteristics.
  3. Differentiate between constructors and methods.
  4. Explain the purpose of the this keyword.
  5. What is a static constructor? How is it different from an instance constructor?
  6. What is a finalizer? When is it executed?
  7. Differentiate between constructors and finalizers.

Properties and Indexers

  1. What is a property? Explain different types of properties.
  2. Differentiate between fields and properties.
  3. What is an indexer? Explain with a suitable example.
  4. Differentiate between arrays and indexers.

Static Members

  1. Explain static classes with an example.
  2. Differentiate between static and non-static classes.
  3. Explain the uses of static members.

Dynamic Binding

  1. What is dynamic binding?
  2. Explain compile-time binding and runtime binding.
  3. Differentiate between static binding and dynamic binding.

Operator Overloading

  1. What is operator overloading?
  2. State the advantages of operator overloading.
  3. Write the syntax for operator overloading.

Inheritance

  1. What is inheritance?
  2. Explain different types of inheritance supported in C#.
  3. State the advantages of inheritance.
  4. Differentiate between single inheritance and multiple inheritance.
  5. Explain the base keyword with an example.

Abstract Classes

  1. What is an abstract class?
  2. What is an abstract method?
  3. Differentiate between abstract class and interface.
  4. Why can’t an abstract class be instantiated?

Overloading

  1. What is method overloading?
  2. Explain compile-time polymorphism.
  3. Differentiate between method overloading and method overriding.
  4. Can methods be overloaded by changing only the return type? Justify your answer.

Object Type

  1. Explain the Object class in C#.
  2. What is boxing and unboxing?
  3. Differentiate between object and dynamic.

Structs

  1. What is a structure (struct)?
  2. Differentiate between structure and class.
  3. Explain value types and reference types.
  4. State the advantages of structs.

Access Modifiers

  1. What are access modifiers?
  2. Explain private, public, and protected.
  3. Differentiate between private and protected.
  4. What is the purpose of the internal access modifier?

Interfaces

  1. What is an interface?
  2. Explain the advantages of interfaces.
  3. Differentiate between interface and abstract class.
  4. Can a class implement multiple interfaces? Explain.

Enums

  1. What is an enumeration (enum)?
  2. State the advantages of enums.
  3. Explain how enum values are assigned.

Generics

  1. What are generics?
  2. Explain the advantages of generics.
  3. Differentiate between generic and non-generic collections.
  4. What is the purpose of the generic type parameter T?

Group C (Long Questions – 10 Marks)

Classes and Constructors

  1. Explain classes and objects in C#. Write a program to demonstrate the use of constructors.
  2. Explain different types of constructors with suitable C# programs.
  3. Explain the this keyword with suitable examples.

Properties and Indexers

  1. Explain properties in detail with suitable examples.
  2. What are indexers? Explain their working with a complete C# program.
  3. Differentiate between fields, properties, and indexers.

Static Members

  1. Explain static constructors and static classes with suitable examples.
  2. Compare static members and instance members with examples.

Finalizers

  1. Explain finalizers and garbage collection in C# with suitable examples.

Dynamic Binding

  1. Explain dynamic binding in C#. Write a suitable example demonstrating runtime polymorphism.

Operator Overloading

  1. What is operator overloading? Explain its syntax and implementation with a complete C# program.

Inheritance

  1. Explain inheritance in C#. Discuss its advantages and limitations with examples.
  2. Explain different types of inheritance supported by C# with diagrams and examples.
  3. Write a C# program demonstrating inheritance and the use of the base keyword.

Abstract Classes

  1. Explain abstract classes and abstract methods with suitable C# programs.
  2. Compare abstract classes and interfaces with examples.

Method Overloading

  1. Explain method overloading with suitable C# programs.
  2. Differentiate between method overloading and method overriding with examples.

Object Type

  1. Explain the Object class and boxing/unboxing with suitable examples.
  2. Discuss the importance of System.Object in C#.

Structs

  1. Explain structures in C#. Compare structures and classes with suitable examples.
  2. Write a C# program demonstrating structures and explain how they differ from classes.

Access Modifiers

  1. Explain all access modifiers in C# with suitable examples.
  2. Compare private, protected, internal, protected internal, and public.

Interfaces

  1. Explain interfaces in C# with suitable examples.
  2. Write a C# program to demonstrate multiple interface implementation.
  3. Compare interfaces and abstract classes.

Enums

  1. Explain enumerations in C# with suitable examples.
  2. Write a C# program demonstrating the use of enums in a switch statement.

Generics

  1. Explain generics in C# with suitable examples.
  2. Write a C# program demonstrating a generic class and a generic method.
  3. Compare generic and non-generic collections.

⭐ Most Important Questions (High Probability)

If you are revising just before the exam, prioritize these:

  1. Explain inheritance with a suitable C# program.
  2. Explain abstract classes and abstract methods with examples.
  3. Differentiate between interface and abstract class.
  4. Explain operator overloading with a complete program.
  5. Explain method overloading and compare it with method overriding.
  6. Explain access modifiers with examples.
  7. Explain structures and compare them with classes.
  8. Explain properties and indexers with suitable examples.
  9. Explain generics with a generic class and generic method.
  10. Explain boxing and unboxing with examples.
  11. Explain static constructors and static classes.
  12. Write a program demonstrating inheritance and the base keyword.
  13. Explain interfaces and implement multiple interfaces using a C# program.
  14. Explain enums with a suitable program.
  15. Explain constructors and different types of constructors.

🔥 Expected Programming Questions (Lab/Long Questions)

Exit mobile version