Introduction

The DOT NET is a software framework. It is developed by Microsoft. It includes a large library and also provides language inter-operability across some programming languages. Language inter-operability refers the capability of two different languages to interact and operate on the same kind of data structures.

The programs written for DOT NET execute in a software environment. The name of the software environment is Common Language Runtime (CLR). It is the virtual machine component. The compiled code is converted into machine code at first. Then it is executed by computer’s CPU. The CLR provides additional services like exception handling, memory management, type safety, garbage collection, thread management etc.

The DOT NET Framework’s Base Class Library offers user interface, database connectivity, data access, cryptography, web application development, numeric algorithms, network communications etc. Programmers produce software by combining their own source code with the  DOT NET Framework and other libraries. The DOT NET Framework is projected to be used by most new applications created for the Windows platform. Microsoft also produces an integrated largely for DOT NET software called Visual Studio.

Intermediate .NET Interview Questions designed to assess your knowledge and proficiency in the .NET framework. Dive into topics such as Common Language Runtime (CLR), value types, reference types, Global Assembly Cache (GAC), JIT compiler, boxing/unboxing, ‘using’ statement, abstract classes, interfaces, ASP.NET ViewState, and the ASP.NET Page Life Cycle.

Intermediate Dotnet Interview Questions

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different types to be treated as objects of a common type. It is used to implement the “one interface, multiple methods” principle, where a single method can be defined with multiple implementations.

There are two types of polymorphism in C#:

  1. Compile-time polymorphism (or static polymorphism) :
  • This type of polymorphism is achieved through method overloading, where multiple methods with the same name but different parameter lists are defined in the same class. The correct method is called at compile-time based on the number and type of arguments passed to the method.
class PolymorphismExample
{
public void Display(int num)
{
Console.WriteLine("Integer value: {0}", num);
}
public void Display(float num)
{
Console.WriteLine("Float value: {0}", num);
}
public void Display(string str)
{
Console.WriteLine("String value: {0}", str);
}
}
  1. Run-time polymorphism (or dynamic polymorphism) :
  • This type of polymorphism is achieved through method overriding, where a derived class provides a new implementation for a method that is already defined in its base class. The correct method is called at run-time based on the actual type of the object at runtime.
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing Shape");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing Circle");
}
}
class Square : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing Square");
}
}

In C# and other languages that support OOP, polymorphism is a powerful feature that allows developers to write more generic and flexible code. It allows objects of different types to be treated as objects of a common type, making it possible to write code that can handle objects of different types in a uniform way.

For example, in the above example, we can create an array of Shape and add objects of Circle and Square classes to it. We can call the Draw() method on each element of the array, and it will call the overridden method of the actual type of the object.

Polymorphism helps to make the code more maintainable and easy to understand, as it allows you to write code that works with multiple types of objects in a consistent way, without the need to write separate code for each type of object.

  • A function in C# is a block of code that can be reused throughout a program. Functions are also known as methods in C#. A function can take zero or more parameters as input and can return a value or not.

Here is an example of a function in C#:

class MyFunctions
{
public int AddNumbers(int num1, int num2)
{
return num1 + num2;
}
}
  • This function is named AddNumbers and it takes two int parameters, num1 and num2. The function uses the return statement to return the sum of num1 and num2.

You can call this function by creating an instance of the class and call the method.

MyFunctions mf = new MyFunctions();
int result = mf.AddNumbers(5, 7);
Console.WriteLine(result);
  • This will output 12

You can also declare a function without a return type, like this:

class MyFunctions
{
public void PrintHello()
{
Console.WriteLine("Hello, World!");
}
}
  • This function is named PrintHello and it takes no parameters. It uses the Console.WriteLine() method to print the string “Hello, World!” when the function is called. You can call this function in the same way as before.
MyFunctions mf = new MyFunctions();
mf.PrintHello();
  • This will output “Hello, World!
  • C# also supports the use of optional parameters, default parameter values and parameter arrays. You can also declare a function as a static function which can be called without creating an instance of the class.
class MyFunctions
{
public static int AddNumbers(int num1, int num2)
{
return num1 + num2;
}
}

This function can be called using the class name instead of an instance.

int result = MyFunctions.AddNumbers(5, 7);
Console.WriteLine(result);
  • Functions in C# are a powerful tool for organizing and reusing code, and are an essential part of the C# programming language.



  • An object in C# is an instance of a class. A class is a blueprint or template that defines the properties, methods, and events of an object. Objects are created from classes, and each object has its own unique set of property values and can perform the methods and events defined in the class.

Here is an example of a simple class named “Car” in C#:

class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public void StartEngine()
{
Console.WriteLine("Vroom!");
}
}
  • This class defines three properties: Make, Model, and Year, and a method StartEngine. Each property has a get and set accessor which allows you to access the value of the property and change the value of the property.

To create an object from this class, you would use the new keyword, like this:

Car myCar = new Car();
  • This creates a new object of the class “Car” and assigns it to the variable myCar.

You can then use the dot notation to access the properties and methods of the object, like this:

myCar.Make = "Toyota";
myCar.Model = "Camry";
myCar.Year = 2020;
Console.WriteLine(myCar.Make + " " + myCar.Model + " " + myCar.Year);
myCar.StartEngine();

This will output:

Toyota Camry 2020
Vroom!

You can also create an object and initialize the properties at the same time using object initializer syntax

Car myCar = new Car() { Make = "Toyota", Model = "Camry", Year = 2020 };
  • In C#, objects are used to model real-world entities and their behaviors and properties, and they are a fundamental part of object-oriented programming (OOP). C# provides many features to work with objects, including inheritance, polymorphism, and encapsulation, which help to create robust and maintainable code.



  • The main method in C# is the entry point of a console application. It is the method that is executed when the program starts. The main method must be defined as a static method and must have a specific signature, as follows:
static void Main(String[] args)

Or

static int Main(String[] args)
  • The static keyword means that the method can be called without creating an instance of the class in which the method is defined. The void or int keyword
  • specifies the return type of the method. The Main method is defined as void if it does not return any value, and int if it returns a value.
  • The string[] args parameter is an array of strings that can be passed to the program when it is run from the command line. These arguments can be accessed within the Main method using the args parameter.

Here is an example of a simple Main method in C#:

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.ReadKey();
}
}
  • This program writes the string “Hello, World!” to the console and waits for the user to press a key before ending.
  • In C#, the Main method is the starting point of the program and it serves as a container for the program’s logic and instructions. Once the Main method completes, the program exits.
  • It’s worth noting that if you are creating a Windows Forms application or WPF application, the entry point of the program will be different, in this case, the Main method is not required and the entry point is the Application.Run(new Form()) method where Form is the class that inherits from the Form class.
  • In C#, Inheritance is a mechanism that allows one class to inherit the properties and methods of another class, known as the base class or parent class. This allows for code reusability and helps to organize related classes in a logical and hierarchical manner.

The syntax for creating a class that inherits from another class in C# is as follows:

class ChildClass : BaseClass
{
// Child class members
}
  • Here, “ChildClass” is the class that inherits from the “BaseClass“. The colon “:” symbol is used to indicate that the ChildClass is inheriting from the BaseClass.
  • It’s important to note that the child class can access all the public and protected members of the base class and can also override the methods of the base class if necessary.

There are three types of inheritance in C#:

  1. Single Inheritance :
  • A class inherits from only one class.
  1. Multi-level Inheritance :
  • A class inherits from a class which further inherits from another class.
  1. Multiple Inheritance :
  • A class inherits from more than one class.

C# does not support Multiple Inheritance directly, but it can be achieved using Interface.



In C#, the syntax for an if-else loop is as follows:

if (condition)
{
// code to be executed if the condition is true
}
else
{
// code to be executed if the condition is false
}
  • The condition is an expression that is evaluated to either true or false. If the condition is true, the code inside the first set of curly braces ({ }) is executed. If the condition is false, the code inside the second set of curly braces is executed.

You can add multiple conditions by adding else if statement:

if (condition1)
{
// code to be executed if condition1 is true
}
else if (condition2)
{
// code to be executed if condition1 is false and condition2 is true
}
else
{
// code to be executed if both condition1 and condition2 are false
}

You can also use the ternary operator ? to write a shorthand version of an if-else statement:

variable = condition ? value1 : value2;
  • It will assign value1 to variable if the condition is true and assign value2 to variable if the condition is false.



In C#, the syntax for a for loop is as follows:

for (initializer; condition; iterator)
{
// code to be executed while the condition is true
}
  • The initializer is the starting value of the loop counter, condition is an expression that is evaluated to either true or false and iterator is used to update the value of the loop counter after each iteration.
  • The loop starts with the initializer, then the condition is evaluated. If the condition is true, the code inside the curly braces is executed, then the iterator is executed. The process is repeated as long as the condition is true.

For example, the following code will print the numbers from 1 to 10:

for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}

You can also use the foreach loop to iterate over the elements of a collection, such as an array or a list:

foreach (var item in collection)
{
// code to be executed for each item in the collection
}
  • The var keyword is used to infer the type of the variable from the type of the collection.
  • In C#, the while loop is a control flow statement that repeatedly executes a block of code as long as a given condition is true.

The syntax for a while loop is as follows:

while (condition)
{
// code to be executed while the condition is true
}
  • The condition is an expression that is evaluated to either true or false. As long as the condition is true, the code inside the curly braces is executed. Once the condition becomes false, the loop is terminated and the program continues with the next statement after the loop.

For example, the following code will print the numbers from 1 to 10:

int i = 1;
while (i <= 10)
{
Console.WriteLine(i);
i++;
}
  • It’s important to note that, if the condition is always true, the loop will run indefinitely causing an infinite loop. It’s a good practice to include a way to terminate the loop inside the body of the loop.
  • In C#, the do-while loop is a control flow statement that repeatedly executes a block of code as long as a given condition is true.

The syntax for a do-while loop is as follows:

do
{
// code to be executed
} while (condition);
  • The condition is an expression that is evaluated to either true or false. The code inside the curly braces is executed at least once, before the condition is evaluated. If the condition is true, the code inside the curly braces is executed again, and the process repeats as long as the condition is true. Once the condition becomes false, the loop is terminated and the program continues with the next statement after the loop.

For example, the following code will print the numbers from 1 to 10:

int i = 1;
do
{
Console.WriteLine(i);
i++;
} while (i <= 10);
  • It’s important to note that, if the condition is always true, the loop will run indefinitely causing an infinite loop. It’s a good practice to include a way to terminate the loop inside the body of the loop.
  • It’s similar to While loop but the difference is that, in do-while loop, the loop body will execute at least once regardless of the condition. In While loop, if the condition is false, the loop body will not execute at all.
  • In C#, the switch statement is a control flow statement that allows you to choose between multiple options based on the value of a single expression. The expression is evaluated, and the corresponding case statement is executed. If no case statement matches the expression value, the default case statement is executed, if present.

The syntax for a switch statement is as follows:

switch (expression)
{
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// ...
default:
// code to be executed if no case matches the expression value
break;
}

For example, the following code will print the name of a color based on the value of the variable color:

string color = "green";
switch (color)
{
case "red":
Console.WriteLine("The color is red");
break;
case "green":
Console.WriteLine("The color is green");
break;
case "blue":
Console.WriteLine("The color is blue");
break;
default:
Console.WriteLine("Invalid color");
break;
}
  • It’s important to note that the break statement is used to exit a case statement and move to the next statement after the switch. If a break statement is not used, the execution will continue to the next case statement, regardless of whether it matches the expression value or not.
  • Also, it’s possible to use goto statement to jump to a labeled statement.
  • switch statement is generally more efficient than a large number of if-else statements when the number of cases is high.
  • Yes, you can have multiple abstract classes in a single program or project. An abstract class is a class that cannot be instantiated, but can be inherited by other classes. It is a way to define a common interface or set of behaviors for a group of related classes.
  • An abstract class is created by using the keyword ‘abstract‘ before the class keyword. An abstract class can have both abstract and non-abstract methods. The derived
  • class that inherits the abstract class, must provide implementation for all the abstract methods defined in the base abstract class.

Here is an example of multiple abstract classes in C#:

abstract class Shape
{
public abstract double Area();
}

abstract class Circle : Shape
{
public abstract double Circumference();
}

abstract class Square : Shape
{
public abstract double Perimeter();
}
  • In this example, we have three abstract classes Shape, Circle, and Square which inherits from Shape. Each class has its own abstract method and the derived class that inherits these classes must provide the implementation for them.
  • It is important to note that, it is not a good practice to create too many abstract classes as it can make the codebase complex and harder to understand. It’s recommended to use abstract classes only when it makes sense to group classes together that share common behavior or interface.

 

  • An abstract class is a class that cannot be instantiated and is typically used as a base class for other classes that implement its functionality. Abstract classes are defined using the abstract keyword in C#.

Here’s an example of an abstract class called Shape:

abstract class Shape
{
// properties and fields
public double Width { get; set; }
public double Height { get; set; }

// abstract method
public abstract double CalculateArea();

// non-abstract method
public double CalculatePerimeter()
{
return 2 * (Width + Height);
}
}
  • In this example, Shape is an abstract class with two properties (Width and Height), an abstract method CalculateArea() and non-abstract method CalculatePerimeter().
  • Abstract methods are methods that do not have an implementation and must be overridden by any class that inherits from the abstract class. In this example, the CalculateArea() method is abstract and does not have an implementation in the Shape class.

Here’s an example of how to create a derived class called Rectangle that inherits from the Shape class:

class Rectangle : Shape
{
public override double CalculateArea()
{
return Width * Height;
}
}
  • The Rectangle class inherits from the Shape class and overrides the CalculateArea() method to provide its own implementation. It can also call CalculatePerimeter() method from Shape class.
Rectangle rectangle = new Rectangle();
rectangle.Width = 4.5;
rectangle.Height = 7.5;
Console.WriteLine("Area of rectangle: " + rectangle.CalculateArea());
Console.WriteLine("Perimeter of rectangle: " + rectangle.CalculatePerimeter());
  • It is important to note that, you can’t create the object of an abstract class, you can only inherit it in other classes.



A constructor in C# is a special method used to initialize an object of a class, while a normal method is just a regular method that performs specific operations. Key differences include:

  1. Naming :
  • A constructor must have the same name as the class, while a normal method can have any name.
  1. Invocation :
  • A constructor is automatically called when an object is created, while a normal method must be explicitly called.
  1. Return type :
  • A constructor does not have a return type, while a normal method can have a return type or be a void method.
  1. Overloading :
  • Constructors can be overloaded, meaning multiple constructors with different parameters can be defined in a single class, while normal methods cannot be overloaded with the same name.



  • A constructor in C# is automatically called when an object of a class is created using the “new” operator.

The syntax for creating an object of a class and calling its constructor is as follows:

ClassName objectName = new ClassName();
  • The constructor is defined within the class and has the same name as the class. It is executed automatically when the object is created and can be used to initialize the object’s properties or fields.
  • If the class has multiple constructors, the appropriate constructor to be called can be selected by passing the required parameters when creating the object.

For example:

class Person
{
public string Name;
public int Age;

public Person(string name)
{
Name = name;
}

public Person(string name, int age)
{
Name = name;
Age = age;
}
}

// Creating an object and calling the constructor with one parameter
Person person1 = new Person("John");

// Creating an object and calling the constructor with two parameters
Person person2 = new Person("Jane", 30);

 

There are several advantages of using constructors in C#:

  1. Initialization :
  • Constructors are used to initialize objects of a class, setting their initial state and values. This eliminates the need to manually initialize the object’s properties and fields after it is created.
  1. Overloading :
  • Constructors can be overloaded, allowing multiple constructors with different parameters to be defined in a single class. This provides flexibility in creating objects of the class, as different constructors can be used to initialize objects with different sets of parameters.
  1. Code Reusability :
  • Constructors allow for code reuse, as the same code can be executed each time an object is created, reducing the amount of code duplication and increasing efficiency.
  1. Improved Readability :
  • Constructors help to improve the readability of code, as the logic for initializing objects is encapsulated within the class, rather than spread out in multiple places in the code.
  1. Simplified Memory Management :
  • Constructors automatically allocate memory for objects, simplifying the process of memory management and reducing the risk of memory leaks.



Exception handling in C# provides several advantages, including:

  1. Improved Reliability :
  • Exception handling makes it easier to detect and respond to unexpected errors and conditions, improving the reliability of an application.
  1. Better Error Management :
  • Exception handling provides a structured way to handle errors, making it easier to diagnose and resolve problems. It also separates error-handling code from the main logic of the application, making the code more maintainable and easier to understand.
  1. Graceful Failure :
  • Exception handling enables an application to gracefully fail, by allowing it to catch and handle exceptions and continue running, instead of abruptly crashing.
  1. Reduced Debugging Time :
  • Exception handling makes it easier to debug an application, as errors can be caught and logged, providing more information about the cause of the error.
  1. Improved User Experience :
  • Exception handling can improve the user experience, by displaying meaningful error messages and allowing the user to recover from errors, instead of just displaying a generic error message and crashing the application.
  1. Better Resource Management :
  • Exception handling helps to ensure that resources, such as database connections and file handles, are properly cleaned up, even in the event of an error, reducing the risk of resource leaks and improving the performance of an application.



  • LINQ (Language Integrated Query) is a set of features in C# that provides a simple and consistent way to query and manipulate data, regardless of the data source. LINQ allows you to write queries against a variety of data sources, including arrays, collections, XML documents, and databases.

Here’s an example of using LINQ to query a list of integers in C#:

using System;
using System.Linq;

class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var evenNumbers = from n in numbers
where n % 2 == 0
select n;

Console.WriteLine("Even numbers:");
foreach (var n in evenNumbers)
{
Console.WriteLine(n);
}

Console.ReadLine();
}
}
  • In this example, an array of integers is declared. A LINQ query is then used to select only the even numbers from the array and store the result in a variable evenNumbers. The where clause filters the numbers based on the condition n % 2 == 0, and the select clause specifies which values to select from the data source. Finally, the selected numbers are displayed on the console using a foreach loop.

This will output:

Even numbers:
2
4
6
8
10

 

The for loop and the foreach loop are both used to iterate over a set of items, but they have some key differences:

  1. Iteration Control :
  • In a for loop, you have complete control over the iteration, including the starting and ending conditions, as well as the increment or decrement of the loop variable. In a foreach loop, the iteration is controlled by the enumerator of the collection and you don’t have control over the iteration.
  1. Collection Type :
  • The for loop can be used with any type of collection, including arrays, lists, and custom collections, while the foreach loop is limited to collections that implement the IEnumerable interface.
  1. Modifying Elements :
  • In a for loop, you can modify the elements of the collection. In a foreach loop, you cannot modify the elements of the collection because the foreach loop enumerates a read-only version of the collection.

Here’s an example of a for loop:

int[] numbers = { 1, 2, 3, 4, 5 };

for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}

And here’s an example of a foreach loop:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int number in numbers)
{
Console.WriteLine(number);
}

In general, you should use a foreach loop when you need to iterate over a collection and you don’t need to modify the elements, and a for loop when you need more control over the iteration or need to modify the elements.

 

  • An array is a collection of elements of the same type that are stored in contiguous memory locations. Arrays are a fixed size, meaning that the number of elements in an array cannot be changed once the array has been created.

Here’s an example of how you can create and use an array in C#:

int[] numbers = new int[5];

numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;

foreach (int number in numbers)
{
Console.WriteLine(number);
}
  • An ArrayList, on the other hand, is a dynamic size collection of elements of any type that are stored in an array. Unlike arrays, ArrayLists can grow and shrink dynamically to accommodate the number of elements that are added or removed.

Here’s an example of how you can create and use an ArrayList in C#:

ArrayList list = new ArrayList();

list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);

foreach (int number in list)
{
Console.WriteLine(number);
}
  • While ArrayLists provide more flexibility than arrays, they come at a cost of performance, as the operations on an ArrayList are generally slower than the equivalent operations on an array. If you know the number of elements in advance, you should use an array, and if you don’t, you should use an ArrayList.
  • In C#, the try-catch block is used to handle exceptions, which are errors that occur during the execution of a program. The try block contains the code that might throw an exception, and the catch block contains the code that will be executed if an exception is thrown.

The basic syntax for the try-catch block is as follows:

try
{
// Code that might throw an exception
}
catch (ExceptionType ex)
{
// Code to handle the exception
}
  • In this example, the code inside the try block might throw an exception. If an exception is thrown, the control of the program will jump to the catch block, where the exception will be caught and processed. The ExceptionType in the catch block specifies the type of exception that will be caught, and ex is a variable that can be used to access information about the exception.
  • You can also include multiple catch blocks to handle different types of exceptions, and you can include a finally block to specify code that will be executed regardless of whether an exception was thrown.

Example:

try
{
int a = 10;
int b = 0;
int c = a / b;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Caught DivideByZeroException: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("Caught Exception: " + ex.Message);
}
finally
{
Console.WriteLine("Finally block executed.");
}
  • In this example, the try block contains code that might throw a DivideByZeroException if an attempt is made to divide by zero. The first catch block is designed to catch the DivideByZeroException and print a message to the console. The second catch block is designed to catch any other type of exception and print a message to the console. The finally block contains code that will be executed regardless of whether an exception was thrown or not.

 

Categorized in: