• .Net
    • C#
  • Technical
    • Technical Issues
    • How to Install GitHub Copilot on Visual Studio 2022
  • Home
  • C#
  • Interview
  • Top 50+ C# Interview Questions and Answers With Examples [2025]
  • Dot Net Framwork
  • History in C#
  • Feature in C#
  • Basic Example in C#
  • KeyWord in C#
  • Operator in C#
  • Data Types in C#
  • Varaible in C#
  • if Statement in C#
  • if-else Statement in C#
  • if-else-if Statement in C#
  • nested if Statement in C#
  • switch Statement in C#
  • ternary Operator in C#
  • for loop in C#
  • while loop in C#
  • do while loop in C#
  • foreach loop in C#
  • break Statement in C#
  • countinue Statement in C#
  • goto Statement in C#
  • Function in C#
  • ref Function in c#
  • out Function in c#
  • in Function in C#
  • Array in C#
  • Passing Array to Function in C#
  • Passing One Dimensional Array to Function in C#
  • Passing Two Dimensional Array to Function in C#
  • Passing Three Dimensional Array to Function in C#
  • Multidimensional Array in C#
  • Jagged Array in C#
  • Params in C#
  • Classes in C#
  • Static in C#
  • Struct in C#
  • Enum in C#
  • Properties in C#
  • Inheritance in C#
  • Overloading in C#
  • Overriding in C#
  • Base in C#
  • Polymorphism in C#
  • Sealed in C#
  • Interface in C#
  • NameSpace in C#
  • Acces Modifiers in C#
  • Encapsulation in C#
  • Abstract in C#
  • Length in C#
  • Clone in C#
  • Compare in C#
  • CompareTo in C#
  • Concat in C#
  • Contains in C#
  • Copy in C#
  • EndWith in C#
  • Equals in C#
  • Format in C#
  • IndexOf in C#
  • Insert in C#
  • IsNullOrEmpty in C#
  • IsNullOrWhiteSpace in C#
  • Join in C#
  • LastIndexOf in C#
  • Remove in C#
  • Replace in C#
  • Split in C#
  • StartsWith in C#
  • SubString in C#
  • ToLower in C#
  • ToString in C#
  • ToUpper in C#
  • Trim in C#
  • TrimEnd in C#
  • TrimStart in C#
  • Try/Catch in C#
  • CustomException in C#
  • List in C#
  • HashTable in C#
  • SortedSet in C#
  • Stack in C#
  • Queue in C#
  • Distionary in C#
  • SortedDictionary in C#
  • SortedList in C#
  • LinkedList in C#
  • DateTime in C#
  • TimeSpan in C#
  • DateOnly in C#
  • TimeOnly in C#
  • FileStream in C#
  • TextWriter in C#
  • TextReader in C#
  • StreamWriter in C#
  • StreamReader in C#
  • BinaryWriter in C#
  • BinaryReader in C#
  • FileInfo in C#
  • DirectoryInfo in C#
  • Serialization in C#
  • DeSerialization in C#
  • Serialization and DeSerialization with Memory Stream in C#
  • Serialization and DeSerialization with XML in C#
  • Serialization and DeSerialization with JSON in C#
  • What is Serialization and DeSerialization in C#
  • Events In C#
  • Delegate In C#
  • Reflection In C#
  • Write and WrteLine in C#
  • Boxing and UnBoxing in C#
  • string and StringBuilder in C#
  • HashTable and Dictionary in C#
  • Array and ArrayList in C#
  • What is typeof Operator in C#
  • Cannot assign null to an implicitly-typed variable in C#
  • How initialize empty array in C#
  • No overload for method ToDictionary takes 0 arguments in C#
  • How to store list in dictionary in C#
  • How to manage null value in function in C#
  • how to convert json object to dictionary in C#
  • How To Remove Numbers And SpecialCharacter From String Using Regex.Replace in C#
  • How to get Number of Days in Month Using C#
  • What is difference between var and dynamic in C#
  • Generic in C#
  • Generics Collection in C#
  • Generics Method in C#
  • Generics Constraints in C#
  • Partial Class in C#
  • Anonymous Method in C#
  • Nullable Types in C#
  • Iterators in C#
  • Covariance and Contravariance in C#
  • C# Anonymous Types
  • Query Expression in C#
  • Lambda Expressions in C#
  • C# Interview Questions and Answers
  • C# OOP Interview Questions and Answers
  • C# version 1.0

Top 50+ C# Interview Questions and Answers With Examples [2025]

1. What is C# history?

C# (pronounced "C Sharp") is a programming language that is latest, flexible. It is made by Microsoft. C# is an object-oriented programming language that support four main pillar of OOP Abstraction, Encapsulation, Inheritance, Polymorphism. It run on .NET Framework. It's history start from late 1990s.

2. What are C# main feactures?

C#, which is also called C Sharp, is a programming language that was made by Anders Hjelsberg. C# combines the computational power of C++ and the ease of Visual Basic, Microsoft’s event-driven programming language and environment. C is the building block from which C# is made. Microsoft came out with C# in the year 2000. It was made to meet the growing demand for online applications that Visual Basic (VB) and C++ can’t meet. Because of this, so The programmers who know how to work with C and C++ can quickly learn how to use C# and by using C# you can make website and desktop application very easily in versatile way and you can also use web services that make capable two or more systems to exchange data over network. Data are exchanged either using XML or JSON.

    • Here, below are some main features of C#

    • 1 - Object-Oriented

    • 2 - Type Safety

    • 3 - Garbage Collection

    • 4 - Cross-Platform Development (C# 9.0 and later)

    • 5 - Managed Code

    • 6 - Rich Standard Library

3. What is Dot Net Framework?

Dot NET Framework is a software development framework for making and running applications on Windows. Dot Framework is part of the .NET platform and provide us a collection of technologies for building website, software and apps for Linux, macOS, Windows, iOS, Android. It has a common runtime (CLR - Common Language Runtime) and a large number of class library that supports more then 60 programming languages, including C#. .NET Framework is the original implementation of .NET. It supports running websites, services, desktop apps, and more on Windows.

4. What is Common Language Runtime (CLR)?

The management of the execution of.NET applications is the responsibility of the CLR. It provides a range of services including garbage collection, exception handling and security. It is a program execution engine that loads and executes the program. It converts the program into native code. It acts as an interface between the framework and operating system. It does exception handling, memory management, and garbage collection. Moreover, it provides security, type-safety, interoperability, and portablility. A list of CLR components are given below:

5. What is Base Class Library (BCL)?

The BCL contains a set of classes, interfaces and value types that provide the essential functionality for your.NET applications. It's about collections, files, networking, security, and more.

6. What are keywords in C#?

Keywords that we use in C# programming language have special meanings and these Keywords as they are special in programming so we cannot used it as identifiers specially like variable name, method name, and class names in you code.

  • We define vairable with string keyword in C#.

      Here, in below example

    • string - a keyword

    • fruitName - variable name

// Define a string variable

string fruitName;

7. What are operators in C#?

In C#, operators are symbols or keywords used to perform various operations on data, such as arithmetic calculations, logical comparisons, and assignments.

Here we have defined some example of operator:

  • 1. Arithmetic Operators:
Symbol Name Description Example Output
+ Addition Adds two numbers a + b = c 5 + 2 = 10
- Subtraction Subtracts two numbers a - b = c 5 - 2 = 3
* Multiplication Multiplies two numbers a * b = c 5 * 2 = 10
/ Division Divides one number by another a / b = c 10 / 2 = 5
% Modulus (remainder after division) Returns the division remainder a % b = c 5 % 2 = 1

Arithmetic Operators Example

using System;
public class CSharpTutorial
{
public static void Main(string[] args)
{
int a = 5;
int b = 2;

// Adds two numbers

Console.WriteLine("{0} + {1} = {2}",a,b,a + b);

// Subtracts two numbers

Console.WriteLine("{0} - {1} = {2}",a,b,a - b);

// Multiplies two numbers

Console.WriteLine("{0} * {1} = {2}",a,b,a * b);

// Divides one number by another

Console.WriteLine("{0} / {1} = {2}",a,b,a / b);

// Modulus (remainder after division)

Console.WriteLine("{0} % {1} = {2}",a,b,a % b);
}


Output

5 + 2 = 7
5 - 2 = 3
5 * 2 = 10
5 / 2 = 2
5 % 2 = 1

8. What are data types in C#?

The behavior of storing data in variable are described with data types. It is responsibility of a specific data type to store a specific value. For example number values are store in integer type data types.

  • 1. Primitive Data Types:
    • Integral Types:
    • Floating-Point Types:
    • Character Type:
    • Boolean Type:
  • 2. Reference Data Types:
    • 1. String Type:

9. How many types of data types in C#?

C# mainly categorized data types in two types: Value types and Reference types.

Feature Value Type Reference Type
Definition Stores the actual value directly in memory Stores a reference (address) to the memory location where the value is stored
Memory Location Stored on the stack Stored on the heap (reference stored on the stack)
Copying Behavior When assigned to a new variable, a copy of the value is created When assigned to a new variable, the reference is copied (both variables point to the same object)
Modification Changes to one copy do not affect the other Changes through one reference affect all references to the object
Examples int, float, char, bool, struct, enum class, object, array, string
Default Value Has a default value (e.g., int = 0, bool = false) null if not initialized
Performance Faster because it's stored on the stack and managed directly Slower because accessing the heap takes more time
Garbage Collection Not applicable; values are removed automatically when they go out of scope Managed by the garbage collector

10. What are Variables in C#?

Variables in C# are used for storing data this data can be in shape of number, characters, text and true, false and decimal. for example for example: int - stores integers (whole numbers), without decimals, such as 123 or -123. double - stores floating point numbers, with decimals, such as 19.99 or -19.99 and char store character like 'A' and string store text like "Apple Red!"

11. What is break statement in C#?

In C#, the break statement is a control flow statement that is used to exit a loop or switch statement prematurely. It allows you to terminate the execution of the innermost loop or switch block and continue with the code immediately following the loop or switch statement

Here, we have defined a basic example of break statement.

using System;
class CSharpProgram
{
static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{

// Exit the loop when i is 3

break;
}
Console.WriteLine("The value of i is: {0}", i);
}
}
}


Output

The value of i is: 1
The value of i is: 2

12. What is continue statement in C#?

The continue statement is used to skip the current iteration of a loop. This continue statement usually we used with for, while, do-while statement. when continue statement skipped the current iteration then control goes to next iteration. It is typically used within loops to control the flow of execution based on a specific condition.

Here, we have defined a basic example of continue statement.

using System;
class CSharpProgram
{
static void Main(string[] args)
{
for (int i = 1; i<= 10; i++)
{
if (i% 2 == 0)
{

// Skip to print if even number

continue;
}
Console.WriteLine("The value of i is : {0}", i);
}
}
}


Output

The value of i is : 1
The value of i is : 3
The value of i is : 5
The value of i is : 7
The value of i is : 9

13. What is goto statement in C#?

In C#, the goto statement allows you to transfer control to a labeled statement within the same method or block of code.

Here, we have defined a basic example of goto statement.

using System;
class CSharpProgram
{
static void Main(string[] args)
{
int i= 0;

// label of goto statement

start:
Console.WriteLine("The value of i is: " + i);
i++;
if (i< 5)

// jump to start label until i is less then 5

goto start;
Console.WriteLine("Done");
}
}


Output

The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
Done

14. What is function in C#

In C#, a function is a block of code that performs a specific task and can be called from other parts of your program. Functions are a fundamental concept in C# and are often referred to as methods.

Functions in C# are known as methods and are defined within a class or struct. They can have parameters, which are variables passed into the method, and they can return a value or be void (returning no value).

C# Function with Examples

15. What is ref parameter in C#

In C#, the ref keyword is used to indicate that a method parameter is a reference parameter.

Reference parameters allow you to pass a reference to a variable as an argument to a method, rather than passing a copy of the variable's value. This means that any changes made to the parameter within the method will affect the original variable outside the method as well.

C# ref parameter

16. What is out parameter in C#

The out keyword is used to declare output parameters in method or function signatures. The output parameter is a parameter that is used to return multiple values from a method. The output parameters are used to pass data out of a method. But a normal function is used for passing the data inside function.

C# out parameter

17. What is in parameter in C#

in is used to state that the parameter passed cannot be modified by the method. An any attempt to modified will give you compile-time error. in parameter was introduced in C# 7.2.

C# in keyword parameter

17. What is array in C#

Array is such type of collection that have the capability to stores a fixed-sized elements of the same data type. But have the difference with mixed data types like array List that can store mixed data types.

In array you can store multiple values of the same data type for example you can store multiple values of int data type of same variable and similarly In array you can also access multiple values of the same type under a single variable name.

Suppose we need to record the 7 different numbers. Instead of creating 7 separate variables, we can simply create an array:

C# Arrays with Examples

18. Can we pass array to function?

A function can receive a parameter. Similarly a function can also receive an array. We can pass an array as parameter to function. In this activity, when we pass an array to a function we actually passes a reference to the array. we give permission to a function that it can access and can modify the elements of the array.

19. What is multidimensional array in C#?

If you have date in the shape of tables, matrices, grids then multidimensional arrays are useful. We declared the multidimensional array by adding commas in the square brackets. We can declare two-dimensional, three-dimensional, four-dimensional array in such a way respectively [,], [, ,], [, , ,].

20. What is jagged array in C#?

In C#, a jagged array is an array of arrays. Unlike rectangular (multidimensional) arrays, jagged arrays allow each element of the outer array to be an array of different lengths. This flexibility makes jagged arrays useful for representing irregular data structures where the inner arrays can have varying sizes. Each row (dimension) has a different length or size in jagged arrays, but in a multidimensional array, each row (dimension) has fixed or the same length because because each row is essentially a separate array.

Here, we have defined a basic example of jagged array.

// Jagged array declaration

int[][] jaggedIntArray = new int[3][];

// Initialize jagged array

jaggedIntArray[0] = new int[] { 1, 2, 3 };
jaggedIntArray[1] = new int[] { 4, 5, 6, 7 };
jaggedIntArray[2] = new int[] { 8, 9 };

// Access elements

Console.WriteLine(jaggedIntArray[0][0]); // Output: 1
Console.WriteLine(jaggedIntArray[1][2]); // Output: 6
Console.WriteLine(jaggedIntArray[2][1]); // Output: 9

21. What are params in C#?

In C#, "params" is a keyword used in method parameter to indicate that a method can accept a different number of parameters of the same type. This feature is often used when you want to create methods that can accept an undecided number of parameters.

using System;
class CSharpTutorial
{
static void Main(string[] args)
{

// Creating Object

CSharpTutorial csharp = new CSharpTutorial();

// You can pass multiple integers as arguments

csharp.ExampleMethod(1, 2, 3);

// You can pass a single integer

csharp.ExampleMethod(4);

// You can even call it with no arguments

csharp.ExampleMethod();
}
private void ExampleMethod(params int[] numbers)
{
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}


Output

1
2
3
4

22. What are the types of classes in C#?

    • Here, below are types of classes in C#

    • 1 - Abstract class

    • 2 - Partial class

    • 3 - Sealed class

    • 4 - Static class

23. What is class in C#?

A class is basic pillar of OOP that is called when instance of a class is created. A class can have fields, properties, method, constructor and destructor etc. When we create an instance of class. This instance of class is used to access of fields, methods, properties, constructor (constructor can zero argument or multiple argument) and destructor. A class is reference type and stores in heap.

Here, below is a Fruit class diagram that explain the concept of class in C#

C# Classes Examples

24. What is constructor in C#?

Constructor is special method that called when object/instance of class is created

// Constructor

public Fruit(int price, string name, bool Isavailable )
{
FruitPrice = price;
FruitName = name;
FruitIsInMarket = Isavailable;
}

25. What is destructor in C#?

Destructor is also a special method that called when object/instance of class is destroyed.

~Fruit()
{
Console.WriteLine("Fruit Instance is Destroyed");
}

26. What is static class in C#?

In C#, a static is a keyward that is used with fields, methods, properties and classes when we make these members static they are globally accessble in all over the application.

Static Class Example

public static class Fruit
{
public static void FruitColor()
{
// ...
}
}

// Usage of a static class method

Fruit.FruitColor();

Rules for Making Static Class

Here we have defined some rules of making static class.

  • 1. Declaration

    A static class must be declared using the static keyword.

  • 2. Static Members:

    All members (methods, properties, fields) of a static class must also be static.

  • 3. Instantiation:

    Static classes cannot be instantiated; you cannot create an object of a static class.

  • 4. Instance Members:

    Static classes cannot contain instance members (non-static fields or methods).

  • 5. Static Methods:

    A static class can contain static methods, which can be called without creating an instance.

  • 5. Static Constructor:

    A static class can have a static constructor for initialization purposes, which is called automatically before any static members are accessed.

  • 5. Accessibility:

    Static classes are sealed class and therefore, cannot be inherited. A static class cannot inherit from other classes.

27. What is static method in C#?

A Static method is also accessible all over the application globally. When we want that a method will be accessible in all over the application with creating the instance of class then we make it static.

Static Method Example

public class MathUtils
{
public static double Add(double a, double b)
{
return a + b;
}
}

// Call the static method

double result = MathUtils.Add(1.2, 2.6);

Rules for making Static Methods

Here we have defined some rules of making static method.

  • 1. Accessibility Modifiers

    Static methods can have access modifiers (e.g., public, private) that determine their visibility outside the class

  • 2. Inheritance:

    Static methods are not polymorphic. You cannot override a static method in a derived class; however, you can hide it by declaring a static method with the same name.

  • 3. No this Keyword:

    Inside a static method, you cannot use the this keyword since there is no instance context.

  • 4. Calling:

    You can call static methods using the class name, or from other static methods within the same class without needing to specify the class name.

  • 5. No Access to Instance Members:

    Static methods cannot access instance variables or instance methods directly. They can only interact with static members.

28. What is static constructor in C#?

A non-static class can contain a zero-argument static constructor. It can be defined with the static keyword and without access modifiers like public, private, and protected.

Static Constructor Example

public class Fruit
{

// static constructor

static Fruit()
{

// Initialization code for static members

}

// instance constructor

public Fruit()
{

// Initialization code for non-static members

}
}
Note:The static constructor gets called when you create an instance for the first time.

Static Constructor Example

// First static constructor and then instance constructor called

Fruit sw1 = new Fruit();

// only instance constructor called

Fruit sw2 = new Fruit();

Rules for making Static Constructors

Here we have defined some rules of making static constructor.

  • 1. Declaration

    A static constructor is defined with the static keyword and does not have any parameters.

  • 2. Initialization Timing:

    It is called automatically before any static members are accessed or any instance of the class is created.

  • 3. Single Invocation:

    The static constructor is called only once per type, regardless of how many instances of the class are created.

  • 4. No Parameters:

    They cannot take parameters, which means they can’t be overloaded.

  • 5. Inheritance:

    If a derived class has a static constructor, the base class's static constructor is called first.

29. What is struct in C#?

A struct a value type and it store it's data in stack. Classes are reference type and it store it's data in heap. The structs are usually used for small data structures. The structs are specially used when we don't need features of classes like inheritance.

Suppose we want to store the name and color of a fruit. We can create two variables: name and color and store value. However, suppose we want to store the same information of multiple fruit.

In this case, creating variables for an individual fruit might be a tedious task. To overcome this we can create a struct that stores name and color. Now, this struct can be used for every fruit.

30. What is enum in C#?

The enum is also called enumeration. It is a value type. Enum is used to define the set of named constant values.

Simple Enum :

We use the enum keyword to create an enum. For example,

    • Here, in below example of enum

    • enum - enum is keword that is used to make constant members (enum).

    • Fruit - Fruit name of enum

    • apple,banana,mango - apple, banana and mango are enum members

Simple Enum Example

enum Fruit
{
apple,
banana,
mango,
}

31. What is property in C#?

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties allow you to define getter and setter methods for private fields.Properties are often used to enforce data encapsulation (mean sensitive data remain hidden from user) and provide a clean and consistent interface to access an object's data.

32. What is inheritance in C#?

You can create a base class (parent class). You can derive a new class (child class) from this existing base class (parent class). When you inherit a child class with base class you also inherit it's members (fields, methods, properties etc.). you can also add these members and also can modify them as needed.Inheritance promotes code reuse, simplifies code maintenance, and improves code organization.

33. How many types of inheritance in C#?

  • Types of inheritance

    There are the following types of inheritance:

    1. Single Inheritance

    In single inheritance, a single derived class inherits from a only single base class. In below diagram, Fruit is parent class that has one to one relationship with orange derive class.So Fruit is Super class and Orange is Sub class.

    Single Inheritance in C#
  • Single Inheritance : Example

    In below example, we have Fruit (base class) that have two methods with named FruitTaste(), FruitColor(). We have inherited Orange derived class with Fruit base class and this Orange class have two methods with named hasTaste() and hasColor() and you can also access Fruit base class methods here in Orange derived class.

using System;
public class CSharpProgram
{
public static void Main(string[] args)
{
Orange objfruit = new Orange();
objfruit.FruitTaste();
objfruit.hasTaste();
objfruit.FruitColor();
objfruit.hasColor();
}
}

// base class (parent class)

public class Fruit
{
public void FruitTaste()
{
Console.WriteLine("Fruit has taste. ");
}
public void FruitColor()
{
Console.WriteLine("Fruit has color.");
}
}

// derived class (child class)

public class Orange : Fruit
{
public void hasTaste()
{
Console.WriteLine("Orange has tangy, sweet, and tart taste. ");
}
public void hasColor()
{
Console.WriteLine("Orange has dark orange color. ");
}
}


Output

Fruit has taste.
Orange has tangy, sweet, and tart taste.
Fruit has color.
Orange has dark orange color.

2. Multilevel Inheritance

In single inheritance, a derived class inherits from a base class and then this base class also acts as a derived class which is inherits from a another base class. In, below diagram, Blood Orange is dervied class that is inherited with Oranges (derived class) and then Oranges (derived class) is inherited with Fruit (base class).

Multilevel Inheritance in C#
  • Multilevel Inheritance : Example

    In below example, we have Fruit base class which are inherited with Oranges derived class and this Fruit class has method with named hasTaste() and Oranges derived class has method with named hasSweetToSourTaste() then the Oranges derived class is inherited with Blood_Orange dervied class that have method with named hasRedColor().

using System;
public class CSharpProgram
{
public static void Main(string[] args)
{
Blood_Orange bloodorange = new Blood_Orange();
bloodorange.hasTaste();
bloodorange.hasSweetToSourTaste();
bloodorange.hasRedColor();
}
}

// base class (parent class)

public class Fruit
{
public void hasTaste()
{
Console.WriteLine("Fruit has taste. ");
}
}

// derived class (child class)

public class Oranges : Fruit
{
public void hasSweetToSourTaste()
{
Console.WriteLine("Oranges have tangy, sweet, and tart, sour taste. ");
}
}

// derived class (child class)

public class Blood_Orange : Oranges
{
public void hasRedColor()
{
Console.WriteLine("Blood Orange has red color of it's Juice. ");
}
}


Output

Fruit has taste.
Oranges have tangy, sweet, and tart, sour taste.
Blood Orange has red color of it's Juice.

3. Hierarchical Inheritance

In hierarchical inheritance, multiple derived classes inherit from a single base class.In, below diagram we have Fruit class that base classs which are inherited with Mango and Orange Sub class (derived classes).

Hierarchical Inheritance in C#
  • Hierarchical Inheritance : Example

    In below example, we have Fruit base class which are inherited with Mango and Orange sub class and this Mango and Orange class has two methods with named haSweetToTartTaste() and hasSweetToCreamyTaste() respectively.

using System;
public class CSharpProgram
{
public static void Main(string[] args)
{
Orange orange = new Orange();
Mango mango = new Mango();
orange.hasSweetToTartTaste();
mango.hasSweetToCreamyTaste();
}
}

// base class (parent class)

public class Fruit
{
public void hasTaste()
{
Console.WriteLine("Fruit has taste. ");
}
}

// derived class (child class)

public class Mango : Fruit
{
public void hasSweetToCreamyTaste()
{
Console.WriteLine("Mango has sweet and creamy taste.");
}
}

// derived class (child class)

public class Orange : Fruit
{
public void hasSweetToTartTaste()
{
Console.WriteLine("Orange has tangy, sweet, and tart, sour taste. ");
}
}


Output

Orange has tangy, sweet, and tart, sour taste.
Mango has sweet and creamy taste.

4. Multiple Inheritance

In multiple inheritance, a single derived class inherits from multiple base classes. C# doesn't support multiple inheritance. However, we can achieve multiple inheritance through interfaces. In below diagram, Vegitables and Fruits are two sub classes of Food base class which have many to many relationship with each other.

Multiple Inheritance in C#
  • Multiple Inheritance : Example

    In below example, we have Food base class which are inherited with Vegetables and Fruits sub classes that have two methods with named IsVegetables() and IsFruit() respectively. AS Fruits and Vegetables have many to many relationship which can not be implemented directly so we did it with interface.

using System;
public class CSharpProgram
{
public static void Main(string[] args)
{
Food food = new Food();
food.IsVegetables();
food.IsFruit();
}
}
public class Food : IFruits , IVegetables
{
public void IsVegetables()
{
Console.WriteLine("Vegetables are the edible parts of a plant.Such as the leaves, stem, roots, and bulbs.");
}
public void IsFruit()
{
Console.WriteLine("Fruits come from the flowering part of a plant and contain seeds.");
}
}

// Vegetables interface

interface IVegetables
{
void IsVegetables();
}

// Fruits interface

interface IFruits
{
void IsFruit();
}


Output

Vegatables are for cooking and eating.
Fruits are for eating.

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance. The combination of multilevel and hierarchical inheritance is an example of Hybrid inheritance.

Hybrid Inheritance in C#
  • Hybrid Inheritance : Example

    In below example, we have Food (base class) Which has method with named forEat() that is inherited with Fruit (derived class) which has method with named isFood() that are inherited with Mango and Orange sub class and this Mango and Orange classes have two methods with named haSweetToTartTaste() and hasSweetToCreamyTaste() respectively.

using System;
public class CSharpProgram
{
public static void Main(string[] args)
{
Orange orange = new Orange();
Mango mango = new Mango();
orange.forEat();
orange.isFood();
orange.hasSweetToTartTaste();
mango.forEat();
mango.isFood();
mango.hasSweetToCreamyTaste();
}
}

// base class (parent class)

public class Food
{
public void forEat()
{
Console.WriteLine("Food is for eating.");
}
}

// derive class (child class)

public class Fruit : Food
{
public void isFood()
{
Console.WriteLine("Fruit is a Food. ");
}
}

// derived class (child class)

public class Mango : Fruit
{
public void hasSweetToCreamyTaste()
{
Console.WriteLine("Mango has sweet and creamy taste.");
}
}

// derived class (child class)

public class Orange : Fruit
{
public void hasSweetToTartTaste()
{
Console.WriteLine("Orange has tangy, sweet, and tart, sour taste. ");
}
}


Output

Food is for eating.
Fruit is a Food.
Orange has tangy, sweet, and tart, sour taste.
Food is for eating.
Fruit is a Food.
Mango has sweet and creamy taste.

34. What is method overloading in C#?

When you define multiple methods in a class with the same name but with different parameter lists. This method parameter must differ in the numbers, types, and order of parameters. It is called method overloading. Method overloading is a form of polymorphism.

Method Overloading Example

using System;
public class CSharpProgram
{
public static void Main(string[] args)
{
FruitUtility objfruitutil = new FruitUtility();
int result1 = objfruitutil.AddFruitPrice();
int result2 = objfruitutil.AddFruitPrice(5,3);
double result3 = objfruitutil.AddFruitPrice(2.3,2.2,3.4);
string result4 = objfruitutil.AddFruitPrice("Sweet", "Apple");
Console.WriteLine(result1);
Console.WriteLine(result2);
Console.WriteLine(result3);
Console.WriteLine(result4);
}
}
public class FruitUtility
{

// Method with no parameters

public int AddFruitPrice()
{
return 0;
}

// Method with two integer parameters

public int AddFruitPrice(int price1, int price2)
{
return price1 + price2;
}

// Method with three double parameters

public double AddFruitPrice(double price1, double price2, double price3)
{
return price1 + price2 + price3;
}

// Method with a different parameter type

public string AddFruitPrice(string a, string b)
{
return a + b;
}
}


Output

0
8
7.9
SweetApple

35. What is method overriding in C#?

when you have a derive class (child class) and base class (parent classs). You can implement the base class (parent class) methods in derived class (child class). In base class we use virtual keyword for defining the method. We use override keyword for implementing the base class method in derive class. Overriding is feature of Object Oriented Programming .

Method Overriding Example

// Base class (parent class)

public class Fruit
{
public virtual void Taste()
{
Console.WriteLine("Fruits have unique taste.");
}
}

// Derive class (child class)

public class WaterMelon: Fruit
{
public override void Taste()
{
Console.WriteLine("WaterMelon has mixture of sweet, sour and bitter taste.");
}
}

// Derive class (child class)

public class Mango: Fruit
{
public override void Taste()
{
Console.WriteLine("Mango has sweet and creamy taste.");
}
}

36. What is base keyword in C#?

When you have inheritance between two or more classes. One is base classs (parent class). Another is derived class (child class). You want to access the members such as fields, properties, and methods, within a derived class. In this type of situation you can use base keyword in derived class to access members of base class.

base Keword Example

using System;
public class CSharpProgram
{
public static void Main(string[] args)
{

//Child class instance

Apple objFruit1 = new Apple();
Apple objFruit2 = new Apple("Apple");
Apple objFruit3 = new Apple("Apple", "Honeycrisp");
Apple objFruit4 = new Apple("Red", "Golden Delicious", 3.16);
objFruit1.getFruit("Apple");
}
}

// Base class (parent class)

public class Fruit
{

// Base class field.

public string Color = "Red";

// Base class constructor.

public Fruit()
{
Console.WriteLine("Fruit name is Apple and variety is RedDelicious");
}
public Fruit(string name)
{
Console.WriteLine("Fruit name is {0}", name);
}
public Fruit(string name, string variety)
{
Console.WriteLine("Fruit name is {0} and and variety is {1} ", name, variety);
}
public Fruit(string name, string variety, double price)
{
Console.WriteLine("Fruit name is {0} and variety is {1} and price is {2}$", name, variety, price);
}

// Base class method.

public virtual void getFruit(string fruitName)
{

// Base class method code

Console.WriteLine("Fruit name is {0} and it's color is {1}", fruitName, Color);
}
}

// Derive class (child class)

public class Apple: Fruit
{

// Derive class constructor.

public Apple(): base()
{
Console.WriteLine("RedDelicious apple has sweet, tart eating taste");
}
public Apple(string name): base(name)
{
Console.WriteLine("{0} has sweet, tart eating taste", name);
}
public Apple(string name, string variety): base(name, variety)
{
Console.WriteLine("{0} {1} has sweet, tart eating taste", name, variety);
}
public Apple(string name, string variety, double price): base(name,variety,price)
{
Console.WriteLine("{0} {1} has sweet, tart eating taste and it's price is {2}$", name, variety, price);
}

// Derive class method.

public override void getFruit(string fruitName)
{
base.getFruit("Apple");
Console.WriteLine("{0} has sweet, tart eating taste and it's color is {1}", fruitName, base.Color);
}
}


Output

Fruit name is Apple and variety is RedDelicious
RedDelicious apple has sweet, tart eating taste
Fruit name is : Apple
Apple has sweet, tart eating taste
Fruit name is Apple and and variety is Honeycrisp
Apple Honeycrisp has sweet, tart eating taste
Fruit name is Red and variety is Golden Delicious and price is 3.16$
Red Golden Delicious has sweet, tart eating taste and it's price is 3.16$
Fruit name is Apple and it's color is Red
Apple has sweet, tart eating taste and it's color is Red

37. What is polymorphism in C#?

Polymorphism mean many forms that we usually archived with static binding and dynamic binding. which also called late binding and early binding.

The below are two types of Polymorphism in C#:

1. Compile-Time Polymorphism (Static Binding):
2. Run-Time Polymorphism (Dynamic Binding):
C# Polymorphism Example
  • Compile-Time Polymorphism (Static Binding):

    When compiler decide which method or operator to call based on the number and types of arguments or operands, It is called compile time polymorphism. It usually occurs in from of method overloading or operator overloading.

    So, the best example of compile-time polymorhism is method overloading.

    Method Overloading:

    When you define multiple methods in a class with the same name but with different parameter lists. This method parameter must differ in the numbers, types, and order of parameters. It is called method overloading. Method overloading is a form of polymorphism.

    Note: In method overloading different methods can have the same name but will be differ in number, type and size.

    Example

    Here, below code is an example of method overloadding. Here we have FruitUtility class and this class have some methods with named AddFruitPrice that are same in it's name but are different in number, types and order.

    So this FruitUtility class is an example of method overloading.

using System;
public class CSharpProgram
{
public static void Main(string[] args)
{
FruitUtility objfruitutil = new FruitUtility();
int result1 = objfruitutil.AddFruitPrice();
int result2 = objfruitutil.AddFruitPrice(5,3);
double result3 = objfruitutil.AddFruitPrice(2.3,2.2,3.4);
string result4 = objfruitutil.AddFruitPrice("Sweet", "Apple");
Console.WriteLine(result1);
Console.WriteLine(result2);
Console.WriteLine(result3);
Console.WriteLine(result4);
}
}
public class FruitUtility
{

// Method with no parameters

public int AddFruitPrice()
{
return 0;
}

// Method with two integer parameters

public int AddFruitPrice(int price1, int price2)
{
return price1 + price2;
}

// Method with three double parameters

public double AddFruitPrice(double price1, double price2, double price3)
{
return price1 + price2 + price3;
}

// Method with a different parameter type

public string AddFruitPrice(string a, string b)
{
return a + b;
}
}


Output

0
8
7.9
SweetApple
  • Run-Time Polymorphism (Dynamic Binding):

    This type of polymorphism is resolved at runtime. It occurs when you have method overriding, where you have a derive class (child class) and base class (parent classs). You can implement the base class (parent class) methods in derived class (child class).

    In base class we use virtual keyword for defining the method. We use override keyword for implementing the base class method in derive classs. It is feature of Object Oriented Programming.

    Method Overriding:

    when you have a derive class (child class) and base class (parent classs). You can implement the base class (parent class) methods in derived class (child class). In base class we use virtual keyword for defining the method.

    We use override keyword for implementing the base class method in derive class. It is feature of Object Oriented Programming.

    Note: A method in derived class overrides the method in base class if the method in derived class has the same name, same return type and same parameters as that of the base class.

    Example

    Here, bleow code is an example of method overriding, We have Fruit class that have Taste virtual method.

    We have inherited this Fruit class with WaterMelon subclass class. So in WaterMelon subclass Class Taste method is overriding.

// Base class (parent class)

public class Fruit
{
public virtual void Taste()
{
Console.WriteLine("Fruits have unique taste.");
}
}

// Derive class (child class)

public class WaterMelon: Fruit
{
public override void Taste()
{
Console.WriteLine("WaterMelon has mixture of sweet, sour and bitter taste.");
}
}

// Derive class (child class)

public class Mango: Fruit
{
public override void Taste()
{
Console.WriteLine("Mango has sweet and creamy taste.");
}
}

38. What is sealed class in C#?

When you have class as base class and you want that any other derived class can not inherit this base class then we declared the base class as sealed class. The sealed keyword also can be used with method, property or event in the derived class to prevent further overriding. This is often done to protect the integrity of a class or to prevent unintentional modifications to its behavior.

How you can use the sealed keyword in C#?

  • Sealing a Class:

    You can declare a class as sealed class, When you make a class sealed it can not be further overriding, you can not further use it as a base class for other classes.

    Example

      Here, in below example of sealed class

    • public - Here, below public is access modifier.

    • sealed - sealed is keword that tells that this class can not be inherited with any other class.

    • class - class is keword.

    • Fruit - Fruit is name of class.

public sealed class Fruit
{
// Class members
}

39. What is interface in C#?

Multiple inheritance is not supported in C#. So for accomplishing multiple inheritance (many to many relationship) we use interface. For making interface we use interface keyword and give a interface name. Interface have method without body. A set of method, properties signatures are defined in interface that can be implement only in that class which derived from this interface. A class which implement to interface that will have methods with body.

In below diagram, Vegitables and Fruits are two sub classes of Food base class which have many to many relationship with each other.

C# Interface with Example
  • Interface : Example

    In below example, we have Vegetables and Fruits two sub classes that is inherited with Food base class which have two methods with named ForCookingAndEating() and ForEating() respectively. AS Fruits and Vegetables have many to many relationship which can not be implemented directly so we did it with interface.

    Interfaces cannot contain any method or property implementations. They only provide method signatures, properties, events, or indexers. Implementing classes are responsible for providing the actual implementation.

Rules for using Interface in C#

  • An interface is defined using the interface keyword.

  • It can contain method signatures, properties, events, and indexers, but cannot contain any implementation.

  • A class or struct that implements an interface must provide an implementation for all its members.

  • A class can implement multiple interfaces, separating them with commas.

  • Interfaces can inherit from other interfaces. A class implementing the derived interface must implement members of both the derived and base interfaces.

  • Members of an interface are implicitly public and cannot have any access modifiers.

  • Interfaces can define properties and events, which classes must implement.

  • Interfaces cannot contain fields. Only members (methods, properties, events, indexers) are allowed.

  • As of C# 8.0, interfaces can contain static members, but they are typically not implemented by the implementing class.

  • Since C# 8.0, you can use nullable reference types in interfaces to indicate whether members can be null.

using System;
public class CSharpProgram
{
public static void Main(string[] args)
{
Food food = new Food();
food.IsVegetables();
food.IsFruit();
}
}
public class Food : IFruits , IVegetables
{
public void IsVegetables()
{
Console.WriteLine("Vegetables are the edible parts of a plant.Such as the leaves, stem, roots, and bulbs.");
}
public void IsFruit()
{
Console.WriteLine("Fruits come from the flowering part of a plant and contain seeds.");
}
}

// Vegetables interface

interface IVegetables
{
void IsVegetables();
}

// Fruits interface

interface IFruits
{
void IsFruit();
}


Output

Vegatables are for cooking and eating.
Fruits are for eating.

40. What is namespace in C#?

A namespace is a container of group related classes, structs, enums, interfaces, and other types. You can organize related classes in a specific namespace. Namespaces help avoid naming conflicts between types and provide a hierarchical structure for organizing your code.

Some Important Features of Namespace

  • Syntax of Declaring Namespace

      Here, in below example of integer type field

    • namespace - Here, namespace is keyword.

    • FruitUtility - FruitUtility is name of namespace.

NameSapce Syntax : Example

namespace FruitUtility
{

// Types and members go here

}

41. What is access modifiers in C#?

Access modifiers are keywords used to specify the declared accessibility of a member or a type. With access modifier we defined the boundary of fields, methods, constructor, properties and events. With access modifier we told a program either it's code will accessible within same class or within another classs ot it will be accessible within sname assembly or within another assembly. So we set the boundary of accessibility of code with access modifier.

Access modifiers with it's visibility and accessibility:

  • Public (public):

    The most permissive access modifier, public allows a type or member to be accessed from anywhere inside code.

    Here in below example, we have Fruit class which have fruitName public field and Color() public method which is accessible outside class.

Example

using System;
namespace FruitApplication
{
public class CSharpTutorial
{
public static void Main(string[] args)
{

// creating object of Fruit class

Fruit fruit = new Fruit();

// accessing fruitName field and printing it

Console.WriteLine("FruitName: " + fruit.fruitName);

// accessing Color method from Fruit

fruit.Color();
Console.ReadLine();
}
}
class Fruit
{

// Fields (attributes or variables)

public string fruitName = "Mango";

// Methods (functions or behaviors)

public void Color()
{
Console.WriteLine("Fruit has Color");
}
}
}


Output

FruitName: Mango
Fruit has Color
  • Private (private):

    The least permissive access modifier, private restricts access to the containing type only. Private members are not visible to other types or outside the current class.

    Here in below example, we have Fruit class which have fruitName private field and Color() private method which is accessible inside the class only. If you will try to acces outside the class you will get below error.

Example

using System;
namespace FruitApplication
{
public class CSharpTutorial
{
public static void Main(string[] args)
{

// creating object of Fruit class

Fruit fruit = new Fruit();

// accessing fruitName field and printing it

Console.WriteLine("FruitName: " + fruit.fruitName);

// accessing Color method from Fruit

fruit.Color();
Console.ReadLine();
}
}
class Fruit
{

// Fields (attributes or variables)

private string fruitName = "Mango";

// Methods (functions or behaviors)

private void Color()
{
Console.WriteLine("Fruit has Color");
}
}
}


Output

Error CS0122 'Fruit.fruitName' is inaccessible due to its protection level
Error CS0122 'Fruit.Color()' is inaccessible due to its protection level
  • Protected (protected):

    Members with the protected access modifier can be accessed within the containing class and by derived classes. They are not accessible outside of the class hierarchy.

    In below example, Fruit class has protected member fruitName and method Color() that are only accessible within it's own class or it's inherited class CSharpTutorial.

Example

using System;
namespace FruitApplication
{
class CSharpTutorial : Fruit
{
public static void Main(string[] args)
{

// creating object of CSharpTutorial class

CSharpTutorial csharpTutorial = new CSharpTutorial();

// accessing fruitName field and printing it

Console.WriteLine("FruitName: " + csharpTutorial.fruitName);

// accessing Color method from Fruit

csharpTutorial.Color();
Console.ReadLine();
}
}
class Fruit
{

// Fields (attributes or variables)

protected string fruitName = "Mango";

// Methods (functions or behaviors)

protected void Color()
{
Console.WriteLine("Fruit has Color");
}
}
}


Output

FruitName: Mango
Fruit has Color
  • Internal (internal):

    The internal modifier allows access within the same assembly (or module) but not from outside assemblies. Types and members marked as internal can be seen and used by code in the same assembly.

    In below example, we have assembly with named FruitFirstApplication which an internal member.We have anohter assembly with named FruitSencondApplication. We have included assembly with this syntax using FruitFirstApplication in application so that we can uyse it in second assembly FruitSencondApplication. Fruit1 class is now accessible within assembly FruitSencondApplication.

Example
using System;
using FruitFirstApplication;
namespace FruitFirstApplication
{
class Fruit1
{

// Fields (attributes or variables)

internal string fruitName = "Apple";
}
}
namespace FruitSencondApplication
{
class CSharpTutorial
{
public static void Main(string[] args)
{

// creating object of Fruit1 class

Fruit1 fruit = new Fruit1();

// accessing fruitName field and printing it

Console.WriteLine("FruitName: " + fruit.fruitName);
}
}
}


Output

FruitName: Apple
  • Protected Internal (protected internal):

    The protected internal allows access within the containing class and by derived classes that are in the same assembly.

    In below example We have Fruit1 class in FruitFirstApplication assembly and Fruit1 class has protected internal field with name fruitName. This protected internal fruitName field is accessible within same assembly and within another assembly where it is dervied.

Example

using FruitFirstApplication;
namespace FruitFirstApplication
{
class Fruit1
{

// Fields (attributes or variables)

protected internal string fruitName = "Apple";
}
}
namespace FruitSencondApplication
{
class CSharpTutorial : Fruit1
{
public static void Main(string[] args)
{

// creating object of CSharpTutorial class

CSharpTutorial csharp = new CSharpTutorial();

// accessing fruitName field and printing it

Console.WriteLine("FruitName: " + csharp.fruitName);
}
}
}


Output

FruitName: Apple
  • Private Protected (private protected):

    The private protected allows access within the containing class and by derived classes that are in the same assembly. It was introduced in C# 7.2. It restricts access outside the assembly.

    In below example, Fruit1 class and CSharpTutorial class are defined within same assembly and fruitName field of Fruit1 class are private protected which mean this field can only access within same assembly (FruitFirstApplication) and it we will try to access it from another assembly it will give us an error.

Example

namespace FruitFirstApplication
{
class Fruit1
{

// Fields (attributes or variables)

private protected string fruitName = "Apple";
}
class CSharpTutorial : Fruit1
{
public static void Main(string[] args)
{

// creating object of CSharpTutorial class

CSharpTutorial csharp = new CSharpTutorial();

// accessing fruitName field and printing it

Console.WriteLine("FruitName: " + csharp.fruitName);
}
}
}


Output

FruitName: Apple

42. What is encapsulation in C#?

When you have such type of data in which you need the grouping of related operation into single unit, You can use encapsulation. Access modifier (such as Private, Public, Protected, Interval etc.) can be used for achieving the encapsulation. The encapsulation is used most commonly for data hiding.

C# Encapsulation Example

Real-World Example of Encapsulation:

1. Capsule is one of the real-world examples of encapsulation, as the capsule binds all its medicinal materials within it. In the same way, C# Encapsulation, i.e., units (class, interface, enums, structs, etc) encloses all its data member and member functions within it.

2. Another real-world example of encapsulation can be your fruit backet. The backet contains different fruits like a Mango, Oranges, Apple, etc it. To get any fruit, you need to open that backet. Similarly, in C#, an encapsulation unit contains its data and behavior within it, and in order to access them, you need an object of that unit.

C# Encapsulation Example

3. Another real-world example of encapsulation can be your sweet backet. The backet contains different sweets like a Rasgulla, Apple cake, Red velvet, etc it. To get any sweet, you need to open that backet. Similarly, in C#, an encapsulation unit contains its data and behavior within it, and in order to access them, you need an object of that unit.

C# Encapsulation Example

In below example, We have Fruit class which have FruitName, FruitPrice properties and these properties will use here for hiding data. We have encapsulated name and price fields in FruitName, FruitPrice properties.

using System;
class CSharpTutorial
{
static void Main(string[] args)
{
Fruit fruit = new Fruit();
fruit.FruitName = "Mango";
fruit.FruitPrice = 100;
Console.WriteLine("Fruit Name is = {0}", fruit.FruitName);
Console.WriteLine("Fruit Price is = {0}", fruit.FruitPrice);
}
}

// parent class

public class Fruit
{
private string? fruitName;
private int fruitPrice;

//FruitName and FruitPrice Properties

public string FruitName
{
get { return name; }
set { name = value; }
}
public int FruitPrice
{
get { return price; }
set { price = value; }
}
}


Output

Fruit Name is = Mango
Fruit Price is = 100

43. What is abstract class in C#?

When you have a class, method, property that doe not required implementation in current class you can make the that class, method, property abstract, Once we have defined abstract class, method and properties in base class then this abstract class, method and porperty can be overridden or implemented in derived (child) classes.

Note: The abstract class, method, property is declared with abstract keyword in the base class and has no body.

Detail of abstract classes methods and properties:

  • Abstract Class and Method:

    We can not create the instance of abstract class directly. It serves as a blueprint for other classes (derived classes) to inherit from. Abstract classes can contain both abstract and non-abstract members. Abstract methods within an abstract class are meant to be overridden by derived classes, while non-abstract methods can have implementations and are inherited as is.

    In below example, We have abstract class Fruit which have one abstract method with named FruitColor() and also have non-abstract method with named FruitTaste().

Example

// create an abstract class

public abstract class Fruit
{

// abstract method

public abstract string FruitColor();

// non-abstract method

public void FruitTaste()
{
Console.WriteLine("Fruits have taste");
}
}
  • Abstract Method Implementation:

    Abstract methods are declared within an abstract class and do not have a method body. They are intended to be implemented by any non-abstract derived class. When you inherit from an abstract class and override its abstract methods, you provide the specific implementation.

    In below example, We have abstract class Fruit which have one abstract method with named FruitColor() and also have non-abstract method with named FruitTaste(). We have a Mango sub class also which is inherited with Fruit class. This Mango sub class has overridden the abstract method FruitColor().

Example

// create an abstract class

public abstract class Fruit
{

// abstract method

public abstract string FruitColor();

// non-abstract method

public void FruitTaste()
{
Console.WriteLine("Fruits have taste");
}
}

// non-abstract property

public string Color { get; set; }

// inheriting from abstract class

public class Mango: Fruit
{
public override string FruitColor()
{
return Color;
}
}
  • Abstract Properties and Indexers:

    Similar to abstract methods, you can declare abstract properties and indexers within an abstract class. These properties and indexers must be implemented in derived classes.

    In below example, we have a Fruit abstract class which have abstract property with named ColorName()

Example

// create an abstract class

public abstract class Fruit
{

// abstract property

public abstract string ColorName { get; set; }
}
  • Using Abstract Classes and Members:

    When you create a derived class from an abstract class, you must provide concrete implementations for all abstract members. You can also choose to override non-abstract members if needed.

    In below example, we have abstract class with named Fruit and this abstract class has abstract property with named ColorName. We have Mango sub class which is inherited with Fruit base class. In Mango sub class we have implemention of ColorName property.

Example

// create an abstract class

public abstract class Fruit
{

// abstract property

public abstract string ColorName { get; set; }
}

// inheriting from abstract class

public class Mango: Fruit
{

// abstract property Implementation

private string color;
public override string ColorName
{
public get { return color; }
public set { color = value; }
}
}

    Rules for using Abstract Class in C#

  • Declaration

    An abstract class is declared using the abstract keyword.

  • Abstract Members

    An abstract class can contain abstract members (methods, properties, etc.) that do not have an implementation. These must be implemented by any non-abstract derived class.

  • Concrete Members:

    An abstract class can also contain concrete (non-abstract) members that have implementations, which can be inherited by derived classes.

  • Inheritance:

    A derived class must implement all abstract members of the base abstract class unless it is also declared as abstract.

  • Instantiation:

    You cannot create an instance of an abstract class directly.

  • Constructor:

    Abstract classes can have constructors, which can be called by derived classes.

  • Access Modifiers:

    Abstract members can have access modifiers (e.g., public, protected, etc.), controlling their visibility in derived classes.

  • Interface Implementation:

    An abstract class can implement interfaces, allowing it to provide some base functionality while requiring derived classes to fulfill the interface contract.

  • Polymorphism:

    Abstract classes support polymorphism. You can use a reference of an abstract class type to refer to an instance of a derived class.

44. What is the difference between abstract class and an interface in C#?

Feature Abstract Class Interface
Definition A class that cannot be instantiated and is meant to be inherited by other classes. A contract that defines a set of methods, properties, events, or indexers that a class must implement.
Inheritance A class can inherit only one abstract class (single inheritance). A class can implement multiple interfaces (multiple inheritance).
Method Implementation Can have both abstract methods (without implementation) and concrete methods (with implementation). Cannot have method implementations (until C# 8.0). Starting from C# 8.0, interfaces can have default method implementations.
Access Modifiers Abstract class members can have access modifiers (public, private, protected, etc.). Interface members are always public by default; no access modifiers allowed.
Constructors Can have constructors. Cannot have constructors.
Default Value Has a default value (e.g., int = 0, bool = false) null if not initialized
Fields Can have fields (variables). Cannot have fields.
Properties Can have both auto-implemented and normal properties with logic. Can have only property definitions; C# 8.0 introduced default implementation for properties.
Static Members Can have static members (fields, methods, etc.). Cannot have static members (except for static methods starting from C# 8.0).
Usage Used when you want to provide a common base class with some shared functionality. Used when you want to define a contract that multiple unrelated classes can implement.
Multiple Inheritance Not supported (can only inherit from one abstract class). Supported (a class can implement multiple interfaces).

45. What is partial class in C#?

When you have a class that is too large to manage, you can split it into multiple files using partial classes. A partial class is a class that is divided into multiple files, each containing a part of the class definition. All parts must use the partial keyword. The compiler combines all parts into a single class during compilation.

Rules for making Partial Classes

  • Definition in Separate Files:

    Partial classes are defined across multiple files. Each part of the partial class must use the partial keyword.

  • Same Namespace, Class Name:

    All parts of the partial class must belong to the same namespace and have the same class name. This ensures that the compiler can merge them into a single class.

  • Getting and Changing Fields:

    Members (fields, properties, methods, etc.) of the partial class can be spread across the files where the class is defined. This allows developers to logically group related members together.

  • Accessibility Modifiers Must Match:

    If a member is defined with a specific access modifier in one part of the partial class, it must have the same access modifier in all other parts.

  • Modifiers Can Differ:

    Other modifiers like static, abstract, virtual, etc., can differ across different parts of the partial class. However, they must be compatible with each other (for example, you can't have one part of the class as static and another as non-static.

  • Order of Definition Doesn't Matter:

    The order in which the parts of the partial class are defined doesn't matter. The compiler merges them together to create a single class.

  • One Part Can Inherit:

    If a partial class is inheriting from a base class or implementing an interface, any part of the partial class can include the inheritance/interface implementation. However, you can't redefine the base class or interface in the other parts.

  • Field Initializers:

    If one part of the partial class contains field initializers (initializing fields at their declaration), those initializations will be performed before the constructor body of the other parts executes.

Partial Method With Example

using System;
public class CSharpProgram
{
public static void Main(string[] args)
{
Fruit objFruit = new Fruit();

// Calling a method

objFruit.GetFruit();
}
}

// FruitFileMethodOne.cs

public partial class Fruit
{

// methods with signature and body

partial void GetFruitName();
public int GetFruitPrice() {}
}

// FruitFileMethodTwo.cs

public partial class Fruit
{

// Implementation of the partial method

public bool GetFruitIsInMarket() {}
partial void GetFruitName()
{
Console.WriteLine("Fruit Name is: {0}" + Mango);
}
}


Output

Apple

46. what is difference between string.Comapre and string.ComapreTo in C#?

Feature string.Compare string.CompareTo
Definition A static method of the String class used to compare two strings. An instance method of the String class used to compare the current string instance with another string.
Usage string.Compare(string strA, string strB). stringInstance.CompareTo(string other).
Return Type Returns an int:
- 0 if both strings are equal
- > 0 if the first string is greater
- < 0 if the first string is lesser
Returns an int:
- 0 if both strings are equal
- > 0 if the instance is greater
- < 0 if the instance is lesser
Comparison Type Supports culture-specific and case-sensitive or case-insensitive comparisons using overloads. Uses the default ordinal comparison (case-sensitive).
Static/Instance Static (doesn't require an instance of the string). Instance-based (called on a string instance).
Null Handling Handles null values without throwing an exception. If both strings are null, they are considered equal. Throws a NullReferenceException if the instance is null.
Customization Supports overloads for custom comparison, including CultureInfo, StringComparison, and case sensitivity. No customization options; uses default comparison settings.
Example int result = string.Compare("apple", "banana"); int result = "apple".CompareTo("banana");

47. What is try catch finally in C#?

The try-catch block in C# is used for exception handling. When you write a piece of code it can be crash any time due to incorrect data and can throw error but try-catch block allow us to catch these exception and display it in page. The below is syntax of try-catch block in C#.

Example
using System;
public class CSharpProgram
{
public static void Main(string[] args)
{
try
{

// Code that may throw an exception

int a = 12;
int b = 0;
int result = a/b;
Console.WriteLine("Result: " + result);
}
catch (Exception ex)
{

// Handle the exception

Console.WriteLine("An exception occurred: " + ex.Message);
}
finally
{

// Optional: Code that always runs, regardless of whether an exception occurred or not

Console.WriteLine("Finally block executed");
}
}
}


Output
An exception occurred: Attempted to divide by zero.
Finally block executed

    In the example above:

  • try:

    The try block contains the code that may throw an exception. In this case, we're trying to divide 10 by 0, which will result in a DivideByZeroException.

  • catch:

    The catch block is used to catch and handle exceptions. In this example, we catch the base Exception class, which can catch any exception type. You can catch specific exceptions by specifying their types instead of Exception. Inside the catch block, you can log the error, perform cleanup, or take appropriate actions to handle the exception.

  • finally:

    The finally block is optional and is used for code that should always run, regardless of whether an exception occurred or not. This is useful for cleanup tasks like closing files or releasing resources.

48. Difference between SortedList and SortedDictionary in C#.?

Feature SortedList SortedDictionary
Underlying Structure Uses an array of key-value pairs internally. Uses a balanced binary tree (Red-Black Tree) internally.
Order Maintains elements in ascending order of keys. Maintains elements in ascending order of keys.
Index-Based Access Supports index-based access (myList[index]). No direct index-based access; access by key only.
Insertion Performance O(n) in the worst case due to shifting elements. O(log n) due to tree rebalancing.
Lookup Performance O(log n) using binary search. O(log n) using tree search.
Deletion Performance O(n) due to shifting elements. O(log n) due to tree restructuring.
Memory Usage Lower memory overhead as it stores elements in a flat array. Higher memory overhead due to maintaining tree structure.
Flexibility Less flexible; better for small or static collections. More flexible; better for large or dynamic collections.
When to Use When you need fast lookup and index-based access for small datasets. When you need frequent insertions and deletions in large datasets.
Example int result = string.Compare("apple", "banana"); int result = "apple".CompareTo("banana");
Example int result = string.Compare("apple", "banana"); int result = "apple".CompareTo("banana");

49. What is the difference between Array and ArrayList?

Feature Array ArrayList
Namespace System System.Collections
Type Safety Type-safe; stores elements of a single specified type. Not type-safe; stores elements as objects (boxing/unboxing required).
Size Fixed size; size is defined at the time of creation and cannot change. Dynamic size; can grow or shrink automatically as elements are added/removed.
Performance Fast because it’s type-safe and does not require boxing/unboxing. Slower due to boxing/unboxing and type checking.
Data Type Homogeneous; all elements must be of the same type. Heterogeneous; can store different types of objects.
Generic Support No generic support. No generic support (Use List for a type-safe generic alternative).
Index-Based Access Supports direct index-based access (myArray[index]). Supports direct index-based access (myList[index]).
Memory Usage Efficient in memory usage as it stores specific types. Higher memory usage due to storing elements as objects.
Methods Available Basic methods (Length, Copy, Sort, etc.). Rich set of methods (Add, Remove, Insert, Contains, etc.).
When to Use When you know the size and type of data at compile time. When you need a collection that can grow dynamically and store different types.

50. What is a Hash table class in C#?

The HashTable is related to System.Collections namespace. The HashTable contains on key-value pairs. Where each key is associated with a unique value.

51. What is the difference between Dispose() and Finalize() methods?

Feature Dispose() Finalize()
Purpose Explicitly release unmanaged resources like file handles, database connections, etc. Implicitly release unmanaged resources during garbage collection.
Defined In Defined by the IDisposable interface. Defined in the Object class (can be overridden).
How It’s Called Called manually by the user or using a using statement. Called automatically by the garbage collector.
When It’s Called Called when the object is no longer needed and you want to free resources immediately. Called by the garbage collector when it determines the object is no longer reachable.
Performance Better performance because it allows immediate resource release. Slower performance since it depends on the garbage collection cycle.
Reusability Can be implemented explicitly via IDisposable and called multiple times (if needed). Cannot be called directly; only garbage collector can call it.
Implementation Requires implementing IDisposable and defining the Dispose() method. Requires overriding the Finalize() method (using a destructor).
Exception Handling Exceptions in Dispose() should be handled explicitly. Exceptions in Finalize() are ignored and not propagated.
Best Practice Use Dispose() for deterministic cleanup of unmanaged resources. Use Finalize() only as a backup in case Dispose() is not called.

52. What is the Generics in C#?

C# Generics allow us to create a single class or method, interfaces, methods, and delegates that can be used with different types of data. Generics enable you to write more flexible and reusable code by allowing you to create components that can work with any data type.

53. What is the Events in C#?

In C#, an event is a mechanism that allows a class or object to notify other classes or objects when something happens. It is essentially a way of implementing the observer design pattern.

54. What is the Delegate in C#?

In C#, a delegate is a type that represents references to methods with a specific signature. It allows methods to be treated as objects, which can be store in variables, passed as arguments to other methods, or returned from methods. Delegates are similar to function pointers in C and C++ but are type-safe.

55. What is Boxing and Unboxing in C#?

Feature Boxing Unboxing
Definition Converting a value type (like int, float, etc.) to a reference type (like object). Converting a reference type (like object) back to a value type.
Direction Value type ➔ Object type Object type ➔ Value type
Performance Slower due to memory allocation on the heap. Slower due to type casting and heap-to-stack copying.
Example int x = 10; object obj = x; object obj = 10; int x = (int)obj;
Storage Location Allocated on the heap. Retrieved from the heap and stored on the stack.
Type Safety No type checking at compile time, but happens at runtime. Type checked at runtime; throws InvalidCastException if types don’t match.
Purpose Allows treating value types as objects (e.g., storing in non-generic collections). Retrieves the original value type from an object reference.
Example Code int num = 10; object obj = num; // Boxing object obj = 10; int num = (int)obj; // Unboxing

56. What is Write and WriteLine in C#?

Feature Write() WriteLine()
Namespace System System
Functionality Outputs the specified text or value without a newline at the end. Outputs the specified text or value followed by a newline (moves to the next line).
Cursor Position Cursor remains at the end of the output. Cursor moves to the beginning of the next line.
Performance Slightly faster since it does not add a newline. Slightly slower due to the extra newline operation.
Use Case Used when you want to display output on the same line. Used when you want to display output and move to the next line.
Example Console.Write("Hello"); Console.Write("World"); // Output: HelloWorld Console.WriteLine("Hello"); Console.WriteLine("World"); // Output: Hello ↵ World ↵

57. What is difference between string and StringBuilder in C#?

Feature string StringBuilder
Namespace System System.Text
Mutability Immutable – Once created, it cannot be changed. Any modification creates a new string object. Mutable – Can be modified without creating a new object.
Performance Slower for frequent modifications because new objects are created each time. Faster for frequent modifications because it modifies the existing object.
Memory Usage High memory usage due to the creation of new objects on modification. Lower memory usage since it modifies the same object.
Modification Creates a new object for each modification. Modifies the existing object directly.
Methods Provides methods like Concat, Replace, Substring, etc. Provides methods like Append, Insert, Remove, Replace, etc.
Use Case When the string content is unlikely to change. When the string content is frequently modified.
Example string s = "Hello"; s += " World"; // New object created StringBuilder sb = new StringBuilder("Hello"); sb.Append(" World"); // Same object modified

58. What is difference between var and dynamic in C#?

Feature var dynamic
Type Resolution Resolved at compile time. Resolved at runtime.
Declaration Requirement Compiler requires the type to be known at compile time. No need to know the type at compile time.
Type Safety Type-safe – Compiler checks for type compatibility. Not type-safe – No compile-time type checking; errors are detected at runtime.
Performance Faster – Type is known at compile time; no runtime overhead. Slower – Type checking happens at runtime.
Flexibility Less flexible – Type is fixed at compile time. More flexible – Can hold values of different types.
IntelliSense Support Full IntelliSense support (suggestions, autocompletion). Limited IntelliSense support (only available at runtime).
Use Case When type is known or can be inferred at compile time. When type is unknown or dynamic (e.g., working with COM objects, JSON, reflection).
Example var x = 10; // int, known at compile time x = "Hello"; // Error: Type mismatch dynamic x = 10; x = "Hello"; // No error – resolved at runtime

59. What is Nullable Types in C#?

In C#, nullable types are a feature introduced to allow value types (such as int, double, bool, etc.) to have a value of null, in addition to their normal range of values. This is particularly useful in scenarios where you need to represent the absence of a value or where a value might legitimately be undefined.

60. What is Iterators in C#?

In C#, iterators provide a convenient way to iterate over collections or sequences of data. They allow you to define custom iteration behavior for your classes, similar to how you use foreach with built-in collections like arrays or lists.

61. What is a Reflection in C#?

Reflection is the process of examining and manipulating the structure and behaviour of program at runtime.With Reflection anybody can determines types, methods, properties, Constructor and other members of your program dynamically, without necessarily knowing them at compile time. Reflection provides a powerful way to interact with types and objects in a flexible manner.you can use reflection to get information about events defined within a type, such as their names, event handlers, and other metadata.

62. What is a JIT compiler?

The JIT (Just-In-Time) compiler in C# is part of the .NET runtime that converts MSIL (Microsoft Intermediate Language) code into native machine code at runtime. This allows the program to run on the target machine efficiently by compiling code just before execution.

63. What is tuple in C#?

A Tuple in C# is a data structure that allows you to store a group of values of different types in a single object. It is defined using the Tuple class or the value tuple syntax ((type1, type2, ...)). Tuples are useful for returning multiple values from a method without using out parameters or custom classes.

var person = (Name: "John", Age: 30);
Console.WriteLine(person.Name); // Output: John

64. What is the difference between “is” and “as” operators in C#?

The is operator checks if an object is compatible with a specified type and returns a boolean (true or false). The as operator attempts to cast an object to a specified type and returns the object if successful; otherwise, it returns null instead of throwing an exception.

object obj = "Hello";
if (obj is string) { Console.WriteLine("It's a string"); }
string result = obj as string; // result = "Hello"

C-Sharp Tutorial is for student and prefessional who want to learn C# programming from basic to advance. We have discussed every topic of C# alonge with examples in this tutorial guide.

Learn Tutorials

  • History in C#
  • if Statement in C#
  • Function in C#
  • Array in C#
  • Classes in C#
  • List in C#

Latest News

May 01, 2025
How initialize empty array in CSharp
May 01, 2025
How to store list in dictionary in CSharp

Learn Tutorials

  • +92-307-501-226-7
  • info@c-sharptutorial.com
  • House # 18 Muslim Town Taxila, Rewalpandi
  • Opening Hours: 10:00 - 18:00
© 2025 All Rights Reserved. Design & Developed By C-Sharp Tutorial
  • Home
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Use
Choose Your Options
RTL Version
  • RTL Version
  • LTR Version
Boxed Version
  • Boxed
  • Full width
Want Sticky Header
  • No
  • Yes
Dark Verion
  • Yes
  • No
Purchase now $17
You will find much more options and styling in admin panel.
TOP