C# Interview Question and Answers with Example - Part 2


Below is top C# interview question and answers with examples for freshers and intermediate developers.

What is an array?

An array is a collection that contains data of the same type.

What are the 3 different types of arrays?

1. Single-Dimensional
2. Multidimensional
3. Jagged

What is Jagged Array?

If element of an array is also an array then it is called as jagged array.

Are arrays value types or reference types?

Arrays are reference types.

What is the base class for Array types?

System.Array

Can you use foreach iteration on arrays in C#?

Yes, we can use foreach iteration on arrays as it implementIEnumerable interface.

What are advantages of using array?

Array is strongly data type as it contains similar type of data.
Arrays do not perform boxing and unboxing.
Type mismatch can be detected as compile type time.

What are disadvantages of using array?

Arrays are fixed in size and cannot grow over time, where ArrayList in System.Collections namespace can grow dynamically.
Arrays are zero index based, and hence a little difficult to work with. The only way to store or retrieve elements from arrays, is to use integral index. Arrays do not provide convenient methods like Add(), Remove() ..etc provided by collection classes found in System.Collections or System.Collections.Generics namespaces, which are very easy to work with.

How to declare and initialize single-dimensional array?

Single-dimensional array can be declare and initialized as shown below.

// only declaration
int[] intArray; // to store integer value
string[] stringArray; // to store string
Employee[] classArray; // to store concrete class
// declaration, initialization and adding value seperately
int[] intArray;
intArray = new int[10];
intArray[0] = 1;
intArray[1] = 2;
// declaration, initialization together and adding values later on
int[] intArray = new int[5];
intArray[0] = 1;
intArray[1] = 2;
// declaration, initialization and adding values together
int[] intArray = new int[] { 10, 20, 12, 30, 40 };
int[] intArray = new int[5] { 10, 20, 12, 30, 40 };
// will throw error when size is not specfied
int[] intArray = new int[];

How to declare and initialize multi-dimensional array?

A multi-dimensional array can be declared and initialized as shown below. Here, [3,2] specifies that array can include 3 rows and 2 columns.

int[,] intArray = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
// or 
int[,] intArray = { {1, 1}, {1, 2}, {1, 3} };

How to declare and initialize jagged array?

A jagged array is initialized with two square brackets [][]. The first bracket specifies the size of an array and the second bracket specifies the dimension of the array which is going to be stored as values.
The following jagged array stores a two single dimensional array as a value.

int[][] intJaggedArray = newint[2][];
intJaggedArray[0] = new int[3] { 1, 2, 3 };
intJaggedArray[1] = new int[2] { 4, 5 };
Console.WriteLine(intJaggedArray[0][0]); // 1
Console.WriteLine(intJaggedArray[0][2]); // 3
Console.WriteLine(intJaggedArray[1][1]); // 5

The following jagged array stores a multi-dimensional array as a value. Second bracket [,] indicates multi-dimension.

int[][,] intJaggedArray = newint[3][,];
intJaggedArray[0] = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
intJaggedArray[1] = new int[2, 2] { { 3, 4 }, { 5, 6 } };
intJaggedArray[2] = new int[2, 2];
Console.WriteLine(intJaggedArray[0][1, 1]); // 4
Console.WriteLine(intJaggedArray[1][1, 0]); // 5
Console.WriteLine(intJaggedArray[1][1, 1]); // 6

What is collection in C#?

Collection in C# is just like array in C# but provides more functionality like adding, removing functionality in superior manner.

What are collection types?

There are 2 types of collection. Non-generic and Generic collection.

What is non-generic collection?

1) Non-generic collection is found under System.collection namespace.
2) Size can grow dynamically.
3) It can store any type of data [type unsafe] thus causing boxing and unboxing and increase performance overhead.

What is non-generic collection?

1) Generic collection is found under System.collection.generic namespace.
2) Size can grow dynamically.
3) It stores only same type of data [type safe] and thus reduce performance overhead.

Give examples of non-generic collection.

Examples are shown below.
1) ArrayList
2) HashTable
3) SortedList
4) Stack
5) Queue

Give examples of generic collection.

Examples are shown below.
1) List
2) Dictionary
3) SortedList
4) Stack
5) Queue

What is difference between Array and ArrayList?

Array: 1) Array is strongly typed. This means that an array can store only specific type of items\elements.
2) Array stores fixed number of elements. Size of an Array must be specified at the time of initialization.
3) No need to cast elements of an array while retrieving because it is strongly type and stores specific type of items only.
4) Use static helper class Array to perform different tasks on the array. ArrayList: 1) ArrayList can store any type of items\elements.
2) ArrayList grows automatically and you don't need to specify size.
3) Items of ArrayList need to be cast to appropriate data type while retriving.
4) ArrayList itself includes various utility methods for various tasks.

What is difference between ArrayList and List?

ArrayList: 1) Found under system.collection namespace.
2) ArrayListArraylist is used to store any type of data there is no restriction that mean we can store integer or string or any object based on our requirements.
3) ArrayList resizes automatically as you add the elements.
4) ArrayList values must be cast to appropriate data types before using it.
5) ArrayList can contain multiple null and dulplicate items.
6) ArrayList can be accessed using foreach or for loop or indexer.
7) Provides Add, AddRange, Remove, RemoveRange, Insert, InsertRange, Sort, Reverse methods. Ex.

ArrayListmyArryList = new ArrayList();
myArryList.Add("One");
myArryList.Add(2);
myArryList.Add(3);
myArryList.Add(4.5f);
stringfirstElement = (string)myArryList[0];
intsecondElement = (int)myArryList[1];
intthirdElement = (int)myArryList[2];
floatfourthElement = (float)myArryList[3];

List: 1) Found under system.collection.generic namespace.
2) Generic List (List<T>)Generic lists are the type safe objects because it will store only specified datatype of elements.
3) List<T> here T means datatype i.e. either string, integer, etc.
4) List<T> stores elements of the specified type and it grows automatically.
5) List<T> can store multiple null and duplicate elements.
6) List<T> can be assigned to IList<T> or List<T> type of variable. It provides more helper method When assigned to List<T> variable 7) List<T> can be access using indexer, for loop or foreach statement.
8) LINQ can be use to query List<T> collection.
9) List<T> is ideal for storing and retrieving large number of elements. Ex.

List<int> myIntList = new List<int>();
myIntList.Add(10);
myIntList.Add(20);
myIntList.Add(30);
myIntList.Add(40);
List<string> myStringList = new List<string>();
myStringList.Add("one");
myStringList.Add("two");
myStringList.Add("three");
myStringList.Add("four");
myStringList.Add("four");
myStringList.Add(null);
myStringList.Add(null);
List<Student> myStudentList = new List<Student>();
myStudentList.Add(new Student());
myStudentList.Add(new Student());
myStudentList.Add(new Student());

What is difference between HashTable and Dictionary?

HashTable: 1) Found under system.collection namespace.
2) Hashtable stores key-value pairs of any datatype where the Key must be unique.
3) The Hashtable key cannot be null whereas the value can be null.
4) Hashtable retrieves an item by comparing the hashcode of keys. So it is slower in performance than Dictionary collection.
5) Hashtable uses the default hashcode provider which is object.GetHashCode(). You can also use a custom hashcode provider.
6) Use DictionaryEntry with foreach statement to iterate Hashtable. Ex.

Hashtablehashtable = new Hashtable();
hashtable.Add(1, "One");
hashtable.Add(2, "Two");
hashtable.Add(3, "Three");
hashtable.Add(4, "Four");
hashtable.Add(5, null);
hashtable.Add("Fv", "Five");
hashtable.Add(8.5F, 8.5);

Dictionary: 1) Found under system.collection.generic namespace.
2) Same as hashtable except that it is strongly type.
3) A Dictionary stores Key-Value pairs where the key must be unique.
4) Value can be null. Ex.

Dictionary<int,string> dict1 = new Dictionary<int,string>();
dict1.Add(1,"One");
dict1.Add(2,"Two");
dict1.Add(3,"Three");
dict1.Add(4,null);
//accessing dictionary
for (int i = 0; i < dict1.Count; i++)
{
Console.WriteLine("Key: {0}, Value: {1}", dict1.Keys.ElementAt(i), dict1[dict1.Keys.ElementAt(i)]);
}
//or
foreach (KeyValuePair<int,string> item in dict1)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}

The IDictionary type instance has one more overload for the Add() method. It accepts a KeyValuePair<tkey, tvalue> struct as a parameter. Ex.

IDictionary<int,string> dict2 = new Dictionary<int,string>();
dict2.Add(1, "One");
dict2.Add(new KeyValuePair<int,string>(2, "Two"));
dict2.Add(new KeyValuePair<int,string>(3, "Three"));
dict2.Add(new KeyValuePair<int,string>(4, null));
for (inti = 0; i< dict2.Count; i++)
{
Console.WriteLine("Key: {0}, Value: {1}", dict2.Keys.ElementAt(i), dict2[dict2.Keys.ElementAt(i)]);
}
//or
foreach (KeyValuePair<int,string> item in dict2)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}

What is difference between Stack and Queue?

Stack: 1) Can be found in generic and non-generic collection.
2) Stack stores the values in LIFO (Last in First out) style. The element which is added last will be the element to come out first.
3) Use the Push() method to add elements into Stack.
4) The Pop() method returns and removes elements from the top of the Stack. Calling the Pop() method on the empty Stack will throw an exception.
5) The Peek() method always returns top most element in the Stack. Ex.

// non generic
Stack myStack = new Stack();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push("test");
myStack.Push(null);
// generic 
Stack<int> myStack1 = new Stack<int>();
myStack1.Push(1);
myStack1.Push(2);

Queue: 1) Can be found in generic and non-generic collection.
2) The Queue stores the values in FIFO (First in First out) style. The element which is added first will come out First.
3) Use the Enqueue() method to add elements into Queue.
4) The Dequeue() method returns and removes elements from the beginning of the Queue. Calling the Dequeue() method on an empty queue will throw an exception.
5) The Peek() method always returns top most element. Ex.

// non generic
Queue queue = new Queue();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue("Three");
queue.Enqueue(null);
// generic
Queue<int> queue2 = new Queue<int>();
queue2.Enqueue(1);
queue2.Enqueue(2);

What is Constructor in C#?

A constructor is special kind of method which gets automatically invoked when instance of class is created. A constructor is used to initialize private fields of the class when instance of class is created. Default constructor is automatically created by compiler, if you not created a constructor in the class. Key points to remember: A constructor with no parameter is called as default constructor.
Constructor doesn’t have any return type, not even void.
A class can have any number of constructors.
A static constructor can’t be parameterized constructor.
A class can have only one static constructor.

What are the types of Constructor?

Below is constructor types.
1) Default Constructor
2) Parameterized Constructor
3) Copy Constructor
4) Static Constructor
5) Private Constructor


Page 2 of 7