C# Interview Questions and Answers

C# is a computer programming language. Here is some common important interview questions and answers in C#. Hope it will help you to build successful carrier.

What’s C# ?
C# (pronounced C-sharp) is a one kind of objects oriented language developed by Microsoft Corporation. It is designed with the combination of C and C++. It has taken a lot of concepts from Java.

C# Data Types
In a programming language Data Types describes what type of data a variable can hold. C# is a strongly typed language. That means every variable and object must have a declared type. When we declare a variable, we have to tell the compiler about what type of the data the variable can hold. In C# programming language, Data types are divided into three categories:

  1. Value Type
  2. Reference Type
  3. Pointer Type

What is Boxing and Unboxing?
In C# it is possible to convert a value of one type to a value of another type. The operation or process of Converting a Value Type to a Reference Type is called Boxing and the operation or process of converting a Reference Type to a Value Type is called Unboxing.

Value Type
A Value Type variable stores a copy of the value in the memory. Some common examples are int, char, float. When we declare an int type, the system allocates memory to store the value.

Reference Type
A Reference Type stores the address of the value in the memory. It does not contain the actual data stored in a variable. They contain a reference to the variables. Some built-in reference types are: object, dynamic and string. The user-defined reference types are: class, interface, delegate, Array.

Pointer Type
Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as in C or C++.

Object
Object is a built-in reference data type. It is a base class for all predefined and user-defined data types. A Class is a logical structure that represents a real world entity. This means that the predefined and user-defined data types are created based on the object class.

String
String is a built-in reference data type. A string type signifies Unicode character string values. It allows you to assign and manipulate string values. Once strings are created, they cannot be modified.

Class
A Class is user-defined structure that contains variables and methods.

Delegate
A Delegate is a user-defined reference type that stores the reference of one or more methods.

Interface
An interface is a type of user-defined class that is used for multiple inheritance.

Array
An array is a user-defined data structure that contains values of the same data type, such as marks of Student.

What is Enumerations or enums?
Enumerations or enums is a set of named integer constants. Enumerated type is declared using the enum keyword. In C# enums are value types and enum constants must be integral numeric values. Its index starts from 0;
Example
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
Output
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console.WriteLine(“Monday: {0}”, WeekdayStart);
Console.WriteLine(“Friday: {0}”, WeekdayEnd);
Monday: 1
Friday: 5

What are the types of comment in C# with examples?
Single line
//This is a Single line comment.
Multiple line (/* */)
/*This is a multiple line comment
We are in line 2
Last line of comment*/
XML Comments (///)
/// <summary>
///  Set error message for multilingual language.
/// </summary>

What is an object?
An object is an instance of a class through which we access the methods of that class. “New” keyword is used to create an object. A class that creates an object in memory will contain the information about the methods, variables and behavior of that class.

What is Abstraction?
Abstraction is a process of showing only the relevant and essential information to the users without showing unnecessary information.

What is Encapsulation?
Encapsulation is a process of protecting unwanted access of information. It is an attribute of an object.Abstraction and encapsulation are related features in OOP or Object Oriented Programming. Abstraction allows making relevant information visible and encapsulation protect unwanted access of information.Encapsulation is implemented by using access modifiers. An access modifier defines the scope and visibility of a class member. C# supports the following access modifiers:

  1. Public
  2. Private
  3. Protected
  4. Internal
  5. Protected internal

What is Polymorphism?
The word polymorphism comes from Greek and it means having multiple forms. This is one of the essential concepts of object oriented programming. Inheritance is related to class but polymorphism is related to object methods. A common example of polymorphism in C# : Function overloading, Operator overloading

What is Inheritance?
Inheritance is a process of reusability of code. It eliminates the use of redundant code. In this system child class can obtained all the features of parent class. Parent class is called based class and the child class is called derived class.

Differentiate strong typing and weak typing
In strong typing the data types of variable are checked at compile time. In weak typing the data types of variable are checked at runtime. In strong typing there is no chance of compilation error. Scripts use weak typing and that’s why issues arise at runtime.

C# language is?
C# language is strong typing. All .Net languages are strongly-typed.

What is the difference between Array and Array List?
Both Array and Array List is a container to store similar type of data. But it has a basic difference. The size of the array is fixed. But the size of Array List is not fixed.

What is Queue?
Queue is container of object where data are inserted and retrieved according to First In First Out (FIFO) structure. Its initial capacity is 32 elements.

What is Stack?
Stack is container of object where data are inserted and retrieved according to Last In First Out (LIFO) structure. Its initial capacity is 32 elements.

What are the differences between System.String and System.Text.StringBuilder classes?
System.String is immutable.  It means that we can’t modify a string at all. The result of modification is a new string.

When we modify the value of a sting variable then a new memory is allocated for the new value and the previous memory is released.
System.StringBuilder is mutable. It means that a string can be modified without allocation new memory. That’s why System.StringBuilder is more effective.

What is HashTable?
A hashtable or a hash map is a data structure that is used to implement an associative array. It associates keys with values. The primary operation in hash table is look like: given a key (e.g. a student’s name), find the corresponding value (e.g. that student’s ID number). It uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found. It is an older .NET Framework. It is slower than the generic Dictionary type.
Example:

Hashtable hashtable = new Hashtable();
hashtable.Add(100, "Dhaka");
hashtable.Add(200, "London");
// Display the keys.
foreach (int key in hashtable.Keys)
{
    Console.WriteLine(key);
}
// Display the values.
foreach (string value in hashtable.Values)
{
    Console.WriteLine(value);
}

Output
//First loop
100
200
//Second loop
Dhaka
London

When to use a HashTable?
When we need to search items quickly by key.
We can use IList or IEnumerable etc for a matching key but that will take O(n) time rather than O(1) for Hashtable or Dictionary.

Differences between Hashtable and Dictionary. Hashtable vs. Dictionary
Hashtable:

  1. It returns null if we try to find a key which does not exist
  2. It is slower than dictionary because it requires boxing and unboxing
  3. All the members in a Hashtable are thread safe
  4. It is not a generic type that means we can’t use it with any data type

Dictionary:

  1. It returns error if we try to find a key which does not exist
  2. It is faster than a Hashtable because there is no boxing and unboxing
  3. Only public static members are thread safe
  4. It is a generic type that means we can use it with any data type

What is Delegates?
A delegate in C# allows you to pass method of one class to objects of other class that can call these methods.
OR
A delegate is an object that holds the reference to a method.
In C++ it is called function pointer.

How do you inherit a class into other class in C#?
Colon(:) is used as inheritance operator in C#. To inherit a class just places a colon and then the class name.
public class DerivedClass : BaseClass

What is the difference between method overriding and method overloading?
Overloading

  1. It is a compile time polymorphism
  2. At the compile time the compiler know which object is assigned for which class
  3. Method name will be same, parameters will be different and its return type may or may not same
  4. Example- operator overloading, function overloading

Overriding

  1. It is a run time polymorphism
  2. At the compile time the compiler didn’t know which object is assigned for which class. Compiler knows it at run time
  3. Method name will be same, parameters will be same and its return type will be same
  4. Example- virtual function

What are Constructor & Destructor?
Constructor is a member function and its name is as like as class name. It is used to initialize the class object. Constructor & Destructor both are necessary for every class. If we don’t create them compiler automatically create them by himself. Constructor & Destructor has no return type. It is called when a class object is created. Constructor & Destructor has no statement primarily. But we can create custom statement. Constructor may have parameter or not.

Destructor is used to delete object instance from the memory. We need to destroy object instance after its task. If we don’t does this compiler automatically do this? Its name is as like class name. Only extra ~ sign is used before its name. It has no parameter and it doesn’t accept any operator.

What is the difference between static or dynamic assemblies?
Assemblies can be static or dynamic.
Static Assemblies are stored on the disk permanently. They can include .NET Framework classes, interfaces as well as resource files (bitmaps, JPEG files). They are not loaded directly from the memory. They are loaded form the disk when CLR requests for them. When we compile the C# codes Static Assemblies are generated. They are stored on disk in portable executable (PE) files.

Dynamic Assemblies are not stored on the disk before execution. They are not saved to disk before execution. We can save them to disk after they have executed. They are loaded form the memory directly. They are created dynamically at run time when application request for them.

What are the difference between Structure and Class?
Structures are value type and Classes are reference type.
Structures cannot have constructor or destructors.
Classes can have both constructor and destructors.
Structures do not support Inheritance, but Classes support Inheritance.

What is Authentication and Authorization?
Authentication is the process of identifying user. Authentication is identifying/validating the user against the credentials (username and password).
Authorization is the process of granting access to those users based on identity. Authorization allows the access of specific resource for a user. Authorization performs after authentication

What are the types of Authentication?
There are 3 types of Authentication. Windows, Forms and Passport Authentication.

What is Exceptions?
An exception is a problem that arises during the execution time of a program. A common example of exceptions is: when we try to divide a number by zero.

How exceptions are handled in C#?
C# provides 3 built-in objects try, catch and finally to handle exception/errors in the code.

Which block is optional?
Both catch and finally blocks are optional. A try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. A try block cannot exist without either catch block or finally block.

Can we have try block without catch?
Yes, we can write try { } finally { } block.

Can we use multiple catch blocks with a try block?
Yes, we can.

Why we need finally block?
The finally block is used to clean any resource that is allocated in the try block. This block is always executed even if an exception occurred or not occurred in try block. But the finally block does not executed, when we write System.Environment.Exit(0) in either try or catch, the CLR is going to be shutdown.

Can multiple catch blocks be executed?
No, multiple catch blocks can’t be executed. If a try block have more than one catch blocks, once the proper catch code executed, the control is transferred to the finally block.

Can we write return statement in try catch or finally block?
Yes, we can write the return statement in try catch & finally.

What is difference between the “throw” and “throw ex” in .NET?
“Throw” statement provides details information and “Throw ex” statement provides short informaion. “Throw” statement preserves original error stack whereas “throw ex” have the stack trace from their throw point. It is always advised to use “throw” because it provides more accurate error information.

For more..

Comments

  1. By Wahab Riaj

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *