CSharp Interview Questions & Answers


What is C#?

C Sharp (C#) in an Object Oriented Programming Language which runs on the .NET Framework.

What is .NET?

.NET is a framework for building and running Software's and Web Applications.

What is OOPS?

OOP stands for Object Oriented Programming, which means it is a way to create/developed Software around Object.

OOP'S provides clear structure for the software's and web applications.

What are the main concepts of OOP'S?

Main concepts of OOPs are :

  • Objects
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation
What are the Advantages of OOPS?

Advantages of OOPS

  • Reuse of code using Inheritance.
  • Flexibility of code using polymorphism.
  • Secure application by using Encapsulation
  • Easily scalable from small to large applications.
  • Easier troubleshooting of code because of modularity
What is Class? & What are class members?

A class is Logical Unity/Blue print. It contains constructor, fields, methods, and properties.

Class members are:

  • Constructor : is a method in the class which gets executed when a class object is created.
  • Field : is a variable of any type. It is basically the data.
  • Property : is a member that provides helps in read and write of private field.
  • Method : is a code block that contains a series of statements.
What is Object?

Object : An Object is an Instance of Class.

What are type of Class?

Type of Class :

  • Regular classes: These are the most common type of classes used in C#. They define the structure and behavior of objects.
  • Abstract classes: Abstract classes cannot be instantiated directly. They are used as base classes from which other classes can inherit properties and methods. Abstract classes may contain abstract methods, which are methods without a body, to be implemented by derived classes.
  • Sealed classes: Sealed classes are the opposite of abstract classes. They cannot be inherited, meaning they cannot serve as base classes. They are often used to prevent derivation or modification of a class's behavior.
  • Static classes: Static classes cannot be instantiated, and they can only contain static members (methods, properties, fields). They are commonly used for utility classes that provide helper functions or constants.
  • Partial classes: Partial classes allow a class's definition to be split across multiple files. This is useful for separating code generated by tools or different developers working on the same class.
  • Nested classes: Nested classes are classes defined within another class. They can access private members of the outer class and are often used for grouping related functionality.
Is it possible to prevent object creation of a class in C#?

Yes, it is possible to prevent the creation of objects of a class in C#. You can achieve this by making the class constructor private or by using the static keyword to create a static class. Here's how you can do it:

  • Private Constructor: With a private constructor, you cannot create an instance of the class using the new keyword from outside the class itself.
  • Static Class: Static classes cannot be instantiated, and they can only contain static members (methods, properties, fields).
What is Property?

A property isa class member that provides a flexible mechanism to readand writeprivate field.

What is the difference between Property and Function?
  • Property is a specialized functiononly.
  • Specialized means properties are used only to get and set field values.
What are Namespaces?

A namespace is a container for a set of related classes and other types.

In C#, a namespace is a way to organize and group related code elements, such as classes, structs, interfaces, enums, and delegates, into a logical hierarchy. Namespaces help to prevent name collisions between different parts of your code and provide a way to encapsulate code for better organization, readability, and maintainability.

Inheritance


What is Inheritance? When to use Inheritance?

Inheritance is creating a PARENT-CHILD relationship between two classes, where child class will automaticallyget the properties and methods of the parent.

Inheritance is good for: REUSABILITY and ABSTRACTION of code

What are the different types of Inheritance?
  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchial Inheritance
Does C# support Multiple Inheritance? How can you implement multiple inheritance in C#?

No
C# support inheritance by using multiple Interfaces. This is an alternative way of multiple inheritance.

How to prevent a class from being Inherited?

By using SEALED keyword in class

By using STATIC keyword in base class

Note: Difference between sealed & static is, you can create the object of sealed class, but you cannot create the object of static class.

Are private class members inherited to the derived class?

No, the private members cannot be inherited to derived class.
Only public and protected class members can be inherited.

Abstraction & Encpsulation


What is Abstraction? How to implement abstraction in real applications?

Abstraction means showing only required things and hide the BACKGROUND details.

Mostly we use abstract classes and interfaces for implementing abstraction.

What is Encapsulation? How to implement encapsulation in real applications?

Encapsulation means WRAPPING of data and methods into a single unit.

What is the difference between Abstraction and Encapsulation?

Abstraction:

  • Abstraction means showing only required things and hide the BACKGROUND details.

Encasulation:

  • Encapsulation means WRAPPING of data and methods into a single unit.

Polymorphism


What is Polymorphism and what are its types? When to use polymorphism?

Polymorphism is the ability of a variable, object, or function to take on MULTIPLE FORMS.

  • Compile Tile
    • Overloading
  • Run Time
    • Overriding
What is Method Overloading? In how many ways a method can be overloaded?

Method overloading is a type of polymorphism in which we can create multiple methods of the same name in the same class, and all methods work in different ways.

  • Number of parameters are different
  • Type of parameters are different
  • Order of parameters is different
What is the difference between Overloading and Overriding?

Method Overloading:

  • Multiple methods of same name in single class.
  • No need of inheritance, as it is in single class.
  • All methods have different signature.
  • It’s a compile time polymorphism.
  • No special keyword used.

Method Overriding:

  • Multiple methods of same name are in different class.
  • Inheritance is used, as it is in different class.
  • Both methods have same signature.
  • It’s a run time polymorphism.
  • Virtual & override keywords.
What is the use of Overriding? When should I override the method in real applications?

Overriding is used to modify and provide a new implementation of the method inherited from a base class.

If a method is marked as virtual, do we must have to "override" it from the child class?

NO. Overriding virtual method is optional.

What is the difference between Method Overriding and Method Hiding?

In Method Hiding, you can completely hide the implementation of the methods of a base class from the derived class using the new keyword.

Abstract Class & Interface


What is the difference between an Abstract class and an Interface?

Abstract class :

  • Abstract class contains both DECLARATION & DEFINITION of methods.
  • Abstract class keyword: ABSTRACT
  • Abstract class does not support multiple inheritance
  • Abstract class can have constructors.

Interface :

  • Interface should contain DECLARATION of methods.
  • Interface keyword: INTERFACE
  • Interface supports multiple inheritance.
  • Interface do not have constructors.
When to use Interface and when Abstract class in real applications?

When to use Interface?

  • An interface is a good choice when you know a method has to be there, but it can be implemented DIFFERENTLY by independent derived classes.

When to use Abstract class?

  • Abstract class is a good choice when you are sure some methods are concrete/defined and must be implemented in the SAME WAY in all derived classes.

Normally we prefer Interface because it gives us the flexibility to modify the behavior at later stage.

Why to create Interfaces in real applications?

Benefits of Interfaces:

  • Help in defining the contract of the system.
  • Unit testing is easy in application having interfaces.
  • Used for implementing dependency injection.
Can we define body of Interfaces methods? When to define methods in Interfaces?

Yes. From C# 8.0 it is possible to put method bodies in Interfaces.

Can you create an instance of an Abstract class or an Interface?

No. Abstract class and interface purpose is to act as base class via inheritance. There object creation is not possible.

Do Interface can have a constructor?

NO. Interface can only be used for inheritance, so constructor is not required.

Do abstract class have Constructors in C#?

YES, Abstract class can have constructors.

The reason is, when the abstract class is inherited in the derived class, and whenever the object of the derived class is created then FIRST the constructor of the abstract/ base class will be called and then only the constructor of derived class will be called.

What is the difference between abstraction and abstract class?

Abstraction means showing only required things and hide the BACKGROUND details.

Abstract class is one of the ways to implement abstraction.

Can Abstract class be Sealed or Static in C#?

NO. Abstract class are used for inheritance, but sealed and static both will not allow the class to be inherited.

Can you declare abstract methods as private in C#?

NO. Abstract methods are only declaration, and they must be implemented in the derive class, therefore they can not be private.

Does Abstract class support multiple Inheritance?

NO. Only at maximum one abstract class can be used for inheritance.

But multiple interfaces can be used.

Access Specifiers, Boxing, Unboxing, String & StringBuilder


What are Access Specifiers?
  • Access specifiers are keywords to specify the accessibility of a class, method, property, field.
  • The keywords are – Public, Private, Protected, Internal, Protected Internal.
What is internal access modifier?

Internal modifier is used to tell that access is limited to the current assembly.

Internal modifier is the default access modifier of a class.

What is Boxing and Unboxing? Where to use Boxing and Unboxing in real applications?

Boxing - Boxing is the process of converting from value type to reference type.

Unboxing - Unboxing is the process of converting reference type to value type.

Where to use Boxing and Unboxing in real applications?

We internally use boxing when item is added to Arraylist. And we use unboxing when item is extracted from Arraylist.

Which one is explicit Boxing or Unboxing?

Unboxing is explicit conversion process.

Is Boxing and Unboxing good for performance?

No, it is recommended to use boxing and unboxing when it is necessary only.

Converting from one type to another type is not good from performance point of view.

What are the basic string operations in C#?

Concatenate : Two strings can be concatenated either by using a System.String.Concat or by using + operator.

    
        string str1 = "This is One";
string str2 = "This is Two";
string str2 = str1 + str2;
//Output: This id One This is Two

Replace: Replace(a,b) is used to replace a string with another string.

    
        string str1 = "This is One";
string str2 = str1.Replace("One", "Two");
//Output: This is Two

Trim: Trim() is used to trim the white spaces in a string at the end.

    
        string str1 = "This is One "'
str1.Trim();
//Output: "This is One"

Contains: Check if a string contains a pattern of substring or not.

    
        string str = "This is test";
bool result = str.Contains("test");
//Output: true
What is the difference between “String” and “StringBuilder”?

String is IMMUTABLE in C#.

  • It means if you defined one string then you couldn’t modify it. Every time you will assign some value to it, it will create a new string.

StringBuilder is MUTABLE in C#.

  • This means if any manipulation will be done on string, then it will not create a new instance every time.
When to use String and when StringBuilder in real applications?

If you want to change a string multiple times, then StringBuilder is a better option from performance point of view because it will not require new memory every time.

What is String Interpolation in C#?

String interpolation is a technique that enables you to insert expression values into strings.

Loops, Conditions, Exception Handling


What are the Loop types in C#? When to use what in real applications?

While Loop :
A while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to true. The loop continues iterating as long as the condition remains true, and terminates when the condition becomes false.
The syntax for a while loop is as follows:

    
        int i = 0;
        while(i < 5)
        {
            Console.WriteLine(i);
            i++;
        };
        //Output: 0 1 2 3 4
    

Do While :
A do-while loop in C# executes its block of code at least once, then repeats it while a specified condition remains true, ensuring the block is executed before the condition is checked.

    
        int j = 100;
        do
        {
            Console.WriteLine(j);
            j++;
        }
        while(j < 10);
        //Output: 100
    

For loop :
A for loop in C# is a control flow statement used to repeatedly execute a block of code a specified number of times. It consists of three parts: initialization, condition, and iteration, allowing for concise and efficient iteration over a range of values or conditions.

    
    for (int k = 0; k < 5; k++;)
    {
        Console.WriteLine(k);
    }
    //Output: 0 1 2 3 4
    

ForEach Loop :
A foreach loop in C# is used to iterate over elements in a collection such as arrays, lists, or other enumerable types without explicitly specifying indices or iterators. It simplifies iteration by automatically handling the traversal of each element in the collection sequentially.

        
            int [] arr = {1,2,3,4};
            foreach (int i in arr)
            {
                Console.WriteLine(i);
            }
            //Output: 1 2 3 4
        
    
What is the difference between “continue” and “break” statement?

Continue statement end the loop iteration and transfer the control to the beginning of the loop.

Break statement end the loop iteration and exit the loop.

What are the alternative ways of writing if-else conditions? When to use what?

Switch statement :

    
        switch (level)
        {
            case "SM"
                salary = 70000;
                break;
            case "ASM:
                salary = 100000;
        }