Tech Point Fundamentals

Sunday, August 28, 2022

C# Interview Questions and Answers - Part 15

C# Interview Questions and Answers - Part 15

csharp-interview-questions-and-answers-part1

Are you preparing for the C# Interview? If yes, then you are at the right place. This is the C# Interview Questions and Answers article series. Here we will see the Top 150+ C# Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:



Please read the complete Design Patterns Interview Questions and Answers series here.


Introduction


This is the 15th part of this C# Interview Questions and Answers article series. Each part contains 10 C# Interview Questions with Answers. Please read all the C# Interview Questions list here.

I will highly recommend you to please read the previous parts over here before continuing the current part:





C# Interview Questions and Answers - Part 15


Q151. What is the difference between generic and non-generic collections? Why do we need generic collections?

C# provides specialized classes that store multiple objects are called collections. There are two types of collections available in C#: non-generic collections and generic collections.



Non-Generic Collections:

The System.Collections namespace contains the non-generic collection types. All the non-generic collection classes such as ArrayList, Stack, Queue, Hashtable, etc operate on the Object data type.  The non-generic collection classes can grow in size automatically when we add items into the collection, unlike the array.

Non-generic collection classes are not type-safe as they operate on Object data type so they can store any type of value. As non-generic collections operate on Object data type hence they are loosely typed. Loosely typed means you can store any type of value in the collection. Because of this loosely typed nature, we may get runtime errors.

Not only we get run time errors because of the loosely-typed nature, but it also affects the performance of the application due to boxing and unboxing. The object data type in C# is a reference data type. So the value that we store in the collection is converted to reference type. 



The following are non-generic collections:

  1. ArrayList
  2. Stack
  3. Queue
  4. Hashtable
  5. SortedList
  6. BitArray



Generic Collections:

The Generic Collections are introduced as part of C# 2.0. The Generic collection is an extension of the non-generic collection classes. The .Net framework has re-implemented all the existing collection classes in the generic collections. The System.Collections.Generic namespace includes generic collection types.

Now Generic Collections are able to store a specific type of data which provides type safety by eliminating the type mismatch at run time. The Generic Collections in C# are strongly typed. The strongly typed nature allows these collection classes to store only one type of value into it. This not only eliminates the type mismatch at runtime but also we will get better performance as they don’t require boxing and unboxing while they store value type data. 



Following are the generic collections:

  1. List<T>
  2. Dictionary<TKey,TValue>
  3. Queue<T>
  4. Stack<T>
  5. Hashset<T>
  6. SortedList<TKey,TValue>









Q152. What is ArrayList? What is the difference between array and ArrayList?

The ArrayList in C# is a collection class that works like an array but provides the facilities such as dynamic resizing, adding, and deleting elements from the middle of a collection. ArrayList is one of the most flexible data structures from C# collection.

ArrayList is a non-generic type of collection that is available in the System.Collections namespace in C#. So you can store any type of data in ArrayList.

ArrayLists are dynamic in size so they do not have a specific size. When we initialize an ArrayList, it will initially allocate the memory for 4 elements. When we add the 5th element, ArrayList will automatically redimension to double of its current size. So, the size will increase as 4, 8, 16, 32, 64, and so on (i.e 2^n).



The ArrayList is internal an array is of the Object type. So, if we are using value type then each element is boxed and stored on a heap and whenever we access them it is unboxed to value type.

ArrayList implements the System.Collections.IList interface that provides various methods like Add(), Remove(), Insert() that we can use for easy implementation. 

ArrayList al = new ArrayList();
al.Add(10); // Inserting value
al.Insert(2, TechPoint); // Inserting values into the middle of the array list collection
al.Remove(TechPoint); // Removing element by values 
al.RemoveAt(1); // Remove element by using index position




ArrayList vs Array:

  1. Array belongs to the System namespace while ArrayList belongs to the System.Collections namespace.
  2. An Array is strongly-typed so we can store only a similar type of data.  While ArrayList is a non-generic collection type so we can store different types of data in ArrayList.
  3. An array is a fixed size so it can store only a fixed number of elements. On the other hand, ArrayList is dynamic in terms of capacity, ArrayList will increase to double its current size if the number of elements exceeds.
  4. We cannot insert any item in the middle of the array but we can insert an item in the middle of ArrayList.
  5. We cannot delete any item from the middle of the array but we can remove an item from the middle of ArrayList.
  6. Array provides better performance than ArrayList because it does not cause boxing and unboxing. But ArrayList involves boxing and unboxing.
  7. The Array cannot accept null values while An ArrayList can accept null.
  8. The array uses static helper class Array which provides support for handling the array but ArrayList implements an IList interface which provides different methods that are used for easy implementation.




Q153. What is Dictionary? What is the difference between a List and Dictionary?

A Dictionary is a generic collection class same as HashTable. It is used to store the data in the form of Key-Value Pairs, but here while creating the dictionary object we need to specify the type for the keys as well as the type for values also. 

A dictionary is a collection of key-value pairs which is present in the System.Collections.Generic namespace. When creating a dictionary, we need to specify the type for the key and as well as type for the value.

Dictionary is the fastest way to find value in a dictionary. So the Keys in a dictionary must be unique.



Dictionary<TKey, TValue> di = new Dictionary<int, string>();
Dictionary<int, string> di = new Dictionary<int, string>();
di.Add(101, "Tech Point"); 
di.Remove(101); 

When you add data to a Dictionary, you should specify a unique key to the data so that it can be uniquely identified. A Dictionary has a unique identifier, so whenever you look up a value in a Dictionary, the runtime must compute a hash code from the key. 

With C# 3.0, the dictionary allows initializing a collection directly at the time of declaration like an array. 

Dictionary<int, string> di = new Dictionary<int, string>() { {101, "Tech Point"}, {102, "www.techpointfunda.com"}};



The Dictionary provide lot of inbuilt methods like Add(), Remove(), TryGetValue(), Count(), Clear() to operate on the dictionary object. 

Add(): The Add method takes two parameters, one for the key and one for the value.

TryGetValue(): This method takes two parameters, one is the key and the other one is the value. The value type parameter is of type out parameter. If the key exists in the dictionary then it will return true and the value with that associated key is stored on the output variable. If you are not sure if a key is present or not in the dictionary, then you can use the TryGetValue() method to get the value from a dictionary because if you are not using TryGetValue then in that case you will get KeyNotFoundException.

Count(): The Count() function is used to find the total number of items in a dictionary.

Remove(): If you want to remove an item from the dictionary collection, then you need to use the Remove() method.

Clear(): The Clear() method is used to remove all the items from the dictionary.



List vs Dictionary:

Both List and Dictionary are generic collections available in System.Collections.Generic namespace that is used to store collections of data. But Dictionary uses a key-value pair collection while a List is a flat object collection.

Both have random access data structures but Dictionary returns an error if you try to find a key that is not there.

The Dictionary is based on a hash table which means it uses a hash lookup, which is an efficient algorithm to look up things, on the other hand, a list, has to go and check element by element until it finds the result from the beginning.




Q154. What is HashTable? What is the difference between HashTable and Dictionary?

The Hashtable in C# is a collection that stores the element in the form of “Key-Value" Pairs. Hashtable class is defined in the System.Collections namespace.

The data in the Hashtable are organized based on the hash code of the key. The key in the HashTable is defined by us and the key can be of any data type. We can access the elements by using the keys. 

In the case of Array and ArrayList, we can access the elements from the collection using a key. That key is nothing but the index position of the elements which starts from zero (0) to the number of elements – 1. So if we want to provide some meaningful key name instead of an automatic index number, we can use a hashtable or dictionary.



The Hashtable computes a hash code for each key. Then it uses that hash code to look up the elements very quickly which increases the performance of the application.

Hashtable ht = new Hashtable();
ht.Add(101, "Tech Point Fundamentals");

We can use the foreach loop to iterate over a Hash collection:

foreach (object obj in ht.Keys)
{
Console.WriteLine(obj + " : " + ht[obj]);
}
 


HashTable provides a couple of methods to operate on the Hash Tables:

ContainsKey(): The ContainsKey() method of the Hashtable is used to check if a given key is present in the Hashtable or not. If the given key is present in the collection then it will return true else it will return false. 

ContainsValue(): The ContainsValue() method of the Hashtable class is used to check if a value is present in the Hashtable or not. If the given value is present in the collection then it will return true else it will return false.



HashTable vs Dictionary:

  1. Both Dictionary and Hashtable in C# are used to hold data as a collection of key-value pairs. But Dictionary is a generic type collection while Hashtable is a non-generic type collection.
  2. Dictionary is defined in System.Collections.Generic namespace while HashTable is defined in the System.Collection namespace.
  3. In Dictionary you must have to specify the "key" name but the HashTable generates the hash code internally.
  4. Dictionary class is a strong type < TKey, TValue > so you must have to specify the data types for key and value. On the other hand, Hashtable is a weakly typed data structure, so you can add keys and values of any object type.
  5. There is no need for boxing/unboxing in Dictionary while HasTable values need to have boxing/unboxing.
  6. When you try to access a non-existing key dictionary, it gives a runtime error. But when you try to access the non-existing key Hashtable, it gives null values.
  7. Dictionary maintains an order of the stored values but Hashtable never maintains an order of the stored values.
  8. Dictionary is faster compared to HasTable because Dictionary does not involve boxing and unboxing.




Q155. What is Stack? What are the applications of Stack? What is the difference between the Peek() and Pop() operation?

The Stack in C# is a non-generic collection class that works in the LIFO (Last In First Out) principle. So in Stack, the item which is added last will be removed first. Stack is useful to store temporary data in LIFO style, and you might want to delete an element after retrieving its value.

C# provides both the generic Stack<T> in System.Collection.Generic namespace and non-generic Stack in System.Collection namespace.



When we add an item into the stack, then it is called pushing an item. Similarly when we remove an item from the stack then it is called popping an item. The Stack Collection in C# allows both null and duplicate values.

Stack<string> myStack = new Stack<string>();
myStack.Push("Tech Point Fundamentals");
var item = myStack.Peek();
item = myStack.Pop();

You can also create a Stack from an array directly:

int[] arrayNumbers = new int[]{ 1, 3, 5, 8};
Stack<int> ArrayToStack = new Stack<int>(arrayNumbers);



The stack class provides the below methods that allow the stack implementation very easy:

Push(): The push() method is used to Insert an object on top of the Stack. 

Synatx: void Stack.Push(Object obj)

Pop(): The Pop() method returns the last element and removes it from a stack. So the pop() method is used to remove and return the object at the top of the Stack. 

If a stack is empty, then it will throw the InvalidOperationException. So, always check for the number of elements in a stack before calling the Pop() method.

Syntax: Object stack.pop()



Peek():  The peek() method is used to return the object from the top of the Stack without removing it. So the Peek() method returns the lastly added value from the stack but does not remove it.

Calling the Peek() method on an empty stack will throw the InvalidOperationException. So, always check for elements in the stack before retrieving elements using the Peek() method.

Syntax: Object Stack.Peek()

Clear(): The Clear() method of the Stack class is used to remove all the elements from the stack.

Syntax: Stack.Clear()

Contains(): The Contains() method checks whether the specified element exists in a Stack collection or not. It returns true if it exists, otherwise false.

Syntax: Stack.Contains(element)

Count: The Count property of the Stack class is used to return the number of elements present in the Stack.

Syntax: Stack.Count




Q156. What is Queue? What are the applications of Queue? What is the difference between Dequeue() and Peek() operation?

A queue is a special type of collection that stores the elements in FIFO style (First In First Out), exactly opposite of the Stack<T> collection. A queue is useful to store temporary data in FIFO style. 

So the item which is added first will be removed first from the collection. When we add an item into the queue collection, it is called enqueuing an item. Similarly when we remove an item from the queue collection then it is called dequeuing an item. 



Elements can be retrieved using the Dequeue() and the Peek() methods. It does not support an indexer. The non-generic Queue Collection class in C# allows both null and duplicate values.

C# provides the generic Queue<T> in System.Collection.Generic namespace and non-generic Queue in System.Collections namespace.

Queue<string> userQueue = new Queue<string>();
userQueue.Enqueue("Tech Point Fundamentals");
var item = userQueue.Peek();
item = userQueue.Dequeue();



The Queue class also provides inbuilt methods same as a stack to operate on the queue object collection:

Enqueue(): This method is used to add an item (or object) to the end of the Queue.

Syntax: void Queue.Enqueue(object obj)

Dequeue(): The Dequeue() removes and returns the first element from a queue because the queue stores elements in FIFO order. So the Dequeue() method of the Queue class is used to remove and return the object from the beginning of the Queue.

Calling the Dequeue() method on an empty queue will throw the InvalidOperationException exception. So, always check that the total count of a queue is greater than zero before calling it.

Syntax: Object Queue.Dequeue()



Peek(): The Peek() method always returns the first item from a queue collection without removing it from the queue. So the peek() method of the Queue class is used to return the oldest object without removing it.

Calling the Peek() method on an empty queue will throw a run-time InvalidOperationException exception. So always check that the total count of a queue is greater than zero before calling it.

Syntax: Object Queue.Peek()

Clear(): The Clear() method of the Queue class is used to remove all the elements from the queue collection.

Syntax: Queue.Clear()

Contains(): The Contains() method of the Queue class is used to check whether an object (element) is present in the Queue or not. If it presents, then it will return true else it will return false.

Syntax: Queue.Contains(element)

Count: The Count property of the Queue class is used to return the number of elements present in the Queue Collection.

Syntax: Queue.Count




Q157. What is Heap? What are the applications of Heap?

Heap is an area of memory where chunks are allocated to store certain kinds of data objects. In heap, the data can be stored and removed in any order. The Memory allocation is Dynamic in Heap.

When we declare a variable in a .NET application, it allocates some memory in the RAM. But depending on the data type the memory may be allocated either in the stack or in the heap memory.

So there are two types of memory allocation for the variables that we created in the .NET Application i.e. stack memory and heap memory. 

The stack memory is responsible for keeping track of the running memory needed in your application. The Stack Memory allocation and de-allocation in .NET are done using the Last In First Out (LIFO) principle. 



All the reference types are stored in Heap and the pointer to that is stored on the stack memory. The heap memory location does not track running memory. Heap is used for dynamic memory allocation. Only The reference pointers are allocated on the stack.

When the program or application exits, it will clear all the memory variables which are created on the stack.  It will de-allocate the memory in a LIFO fashion from the stack. But It will not de-allocate the heap memory. Later, the heap memory will be de-allocated by the garbage collector.

The memory allocation which is done on the stack is gone when the control moves out from the method i.e once the method completes its execution. On the other hand, the memory allocation which is done on the heap needs to be de-allocated by the garbage collector.

When an object stored on the heap is no longer used, that means the object does not have any reference pointing, then the object is eligible for garbage collection. At some point in time, the garbage collector will de-allocate this object from the heap.



Q158. What is Linked List in C#? 

In C# the LinkedList<T> class uses the concept of a linked list. It is defined in System.Collections.Generic namespace. It allows us to add and remove elements before or the last index fastly. It can have duplicate elements.

The LinkedList<T> is a general-purpose linked list. It supports enumerators and implements the ICollection interface, consistent with other collection classes in the .NET Framework.

LinkedList<T> provides separate nodes of type LinkedListNode<T>. You can remove nodes and reinsert them, either in the same list or in another list. Each node in a LinkedList<T> object is of the type LinkedListNode<T>. Because the LinkedList<T> is doubly linked, each node points forward to the Next node and backward to the previous node.



Lists that contain reference types perform better when a node and its value are created at the same time. LinkedList<T> accepts null as a valid Value property for reference types and allows duplicate values.

If the LinkedList<T> is empty, the First and Last properties contain null. The LinkedList<T> class does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state. The list remains consistent on a single thread.

The linklist class  provides list of inbuilt methods of the different types of opertaions like AddFirst(), AddLast(), Clear, RemoveFirst(), RemoveLast(), First, Last etc.

string[] nameArray = { "TechPoint", "Tech Point Fundamentals" };
LinkedList<string> name = new LinkedList<string>(nameArray);
name.AddFirst("www.techpointfunda.com");
name.AddLast("Tech Point");
name.RemoveFirst();
name.RemoveLast();




Q159. What is the difference between class and object? 

A class is simply a user-defined data type that represents both state and behavior. The state represents the properties and behavior is the action that objects can perform.

A class is a blueprint or template that describes the details of an object. In C#, a Class is composed of three things i.e. a name, attributes, and operations.

The object is an instance of a class. A class is brought live by creating objects. An object can be considered as a thing that can perform activities. The set of activities that the object performs defines the object’s behavior.



All the members of a class can be accessed through the object. To access the class members, we need to use the dot (.) operator. The dot operator links the name of an object with the name of a member of a class.

In order to create a class, you need to use the class keyword while if you want to create an object of a class then you need to use the new keyword.

In C# there are different types of classes available:









Q160. What is the use of optional parameters? Can you overload two methods based on optional Parameters? 

The definition of a method, constructor, indexer, or delegate can specify it's parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. 

Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. 



Since the Comma-separated gaps in the argument list aren't supported, C# 4 introduces named and optional arguments. Named arguments enable you to specify an argument for a parameter by matching the argument with its name rather than with its position in the parameter list.

Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.



We can make the method parameters optional in many different ways as follows.


The OptionalAttribute is present in System.Runtime.InteropServices namespace. 

public static void Add(int num1, int num2, [Optional] int[] nums) { }

Please read more about the params parameter, named parameter, and method overloading here.


To Be Continued Part-16...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK  for regular updates.

    

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.