Tech Point Fundamentals

Sunday, July 24, 2022

C# Interview Questions and Answers - Part 10

C# Interview Questions and Answers - Part 10

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 10th 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 10


Q091. What are the different ways to handle the exceptions in C#? Can a try block exist without a catch block in C#?

In C# try, catch, and finally block is used to handle the exceptions. An exception is a response to an exceptional circumstance that arises while a program is running.

Try Block:

  1. It contains the C# code that might cause any runtime exceptions. Any suspected code that may raise exceptions should be put inside a try{ } block. 
  2. During the execution, if an exception occurs, the flow of the control jumps to the first matching catch block. 
  3. A try block identifies a block of code for which particular exceptions are activated. 
  4. A try block must be followed by a catch or finally or both blocks. The try block without a catch or finally block will give a compile-time error.



Catch Block:

  1. This section contains the exception handling strategies. The catch block is an exception handler block where you can perform some action such as logging and auditing an exception. 
  2. The catch block takes a parameter of an exception type using which you can get the details of an exception.
  3. You can use multiple catch blocks with different exception type parameters. These are known as exception filters. Exception filters are useful when you want to handle different types of exceptions in different ways. 
  4. Multiple catch blocks with the same exception type are not allowed. A catch block with the base Exception type (i.e exception ex) must be the last block.
  5. A parameterless catch block and a catch block with the exception parameter are not allowed in the same try-catch statements, because they both do the same thing. 
  6. So a parameterless catch block i.e. catch{ } or general catch block i.e. catch(Exception ex){ }  must be the last block otherwise compiler will generate an error.
  7. If there is finally a block defined, the catch block can be omitted.
  8. A try block containing any yield statement cannot have a corresponding catch block. Please watch the yield statement video here for more details.








Finally Block: 

  1. The finally block is an optional block and should come after a try or catch block. 
  2. The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. 
  3. The finally block will always be executed whether an exception is raised or not. 
  4. It is generally used to release unmanaged resources. This is an optional block, so the developer can skip this when not required.
  5. Multiple finally blocks are not allowed, unlike the catch blocks.
  6. The finally block cannot have the return, continue, or break keywords. It doesn't let control leave the finally block.
  7. The finally block cannot contain any yield statement. Please watch the yield statement video here for more details.








Exception Handling Patterns: There could be three exception handling patterns in C#:

  1. Try-Catch-Finally Pattern
  2. Try-Catch Pattern
  3. Try-Finally Pattern

A try block can exist without a catch block. But in this case, finally block must be placed. The Try-Finally pattern is used in the IDisposable interface for the "using dispose pattern". The finalizer also uses this try-finally pattern. Please read the IDisposable Interface article here and the Finalizer article here for more details.






The try-finally pattern is also used in the iterator pattern. A try code block having a yield statement cannot have any matching catch block. So it must have to use only finally block. Please watch the yield statement video here for more details. 

C# also allows nested try-catch blocks. When using nested try-catch blocks, an exception will be caught in the first matching catch block that follows the try block where an exception occurred. If there isn't an inner catch block that matches with raised exception type, then the control will flow to the outer catch block until it finds an appropriate exception filter.
 
Please watch the Try Without Catch Blocks video herePlease watch the Try-Finally Blocks video here and the Throw vs Throw ex video here for more details.




Q092. What is the difference between IEnumerable and IEnumerator in C#?

Both IEnumerable and IEnumerator are interfaces that implement the iterator design pattern in the .Net Framework. So the return type of all the method which contains the yield statement must be either IEnumerable or IEnumerator. Please watch the yield statement video here for more details.

Both IEnumerable and IEnumerator are interfaces that help to loop through the collection. However, both are forward read-only and cannot be used to modify the underlying collection. 

In C#, all collections (i.e lists, dictionaries, stacks, queues, etc) are enumerable because they implement the IEnumerable interface internally. In fact, the foreach loop works with all the collection types that implement the IEnumerable interface. That's why the compiler generates code that uses an Enumerator internally when you write a foreach loop in C#.

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. IEnumerable can move forward only and read-only over a collection, it can’t move backward and between the items.



If you check the IEnumerable Interface defined in System.Collection namespace:

ienumerable

If you check the IEnumerable Interface defined in System.Collection.Generic namespace it also uses the same:

generic-ienumerable




IEnumerator, on the other hand, is the base interface for all non-generic enumerators which are used to read the data in the collection.

An Enumerator is an object that returns each item in a collection in a specific order, exactly as they are requested. IEnumerator is an interface implemented by an enumerator and the enumerable class implements the IEnumerable interface.

IEnumerator has two methods MoveNext() and Reset(). It also has a property called Current. The MoveNext ( ) returns a Boolean value that indicates the end of the list and helps position the first element in the list after calling the Reset ( ) method. 

The Current property can only be called through an instance of the IEnumerator interface and it returns the current element in the list. If you check the IEnumerable Interface defined in System.Collection namespace:

IEnumerator



If you check the IEnumerable Interface defined in System.Collection.Generic namespace it also uses the same:

Generic-IEnumerator

The main difference between IEnumerable and IEnumerator is an IEnumerator retains its cursor's current state. So, if you want to loop sequentially through the collection, use an IEnumerable interface else if you want to retain the cursor position and want to pass it from one function to another function then use an IEnumerator interface.



Q093. What is the difference between IEnumerable and IQueryable in C#?

IEnumerable and IQueryable:

  1. Both are interfaces that are used for data manipulation.
  2. Both do forward read-only iteration over a collection.
  3. Both support deferred execution.



IEnumerable vs IQueryable:

  1. IEnumerable exists in the System.Collections namespace while IQueryable exists in the System.Linq Namespace.
  2. IEnumerable is not inherited from any interface while IQueryable is inherited from IEnumerable interface.
  3. IEnumerable is suitable for querying data from in-memory collections like List, Array, etc. while IQueryable is suitable for querying data from out-memory like remote database, service) collections.
  4. IEnumerable does not support lazy loading, hence not suitable for paging-like scenarios while IQueryable supports lazy loading.
  5. While querying data from the database, IEnumerable executes SQL queries on the server-side, loads data in-memory on the client-side, and then filters the data while IQueryable executes all the SQL queries on the server-side with all filters.
  6. IEnumerable does not support any custom query while IQueryable supports creating custom queries using CreateQuery and Execute.
  7. IEnumerable is mostly used LINQ to Object and LINQ to XML queries while IQueryable is mostly used in LINQ to SQL queries.

If you check the IQueryable Interface defined in System.LINQ namespace:

IQueryable




Q094. What is the difference between IEnumerable, IList, and List in C#?

IEnumerable vs List:

  1. The list is an abstract class while IEnumerable is an interface. 
  2. The list implements IEnumerable but represents the entire collection in memory. So IEnumerable describes behavior, while List is an implementation of that behavior.
  3. IEnumerable is read-only while List is not. So we can add and delete items in List but not in IEnumerable.
  4. IEnumerable can iterate over a collection in a forward-only direction while array can be traversed in both directions. 
  5. IEnumerable uses deferred execution but List does not.

All LINQ expressions return an enumeration, and by default, the expression executes when you iterate through it using a foreach, but you can force it to iterate sooner using .ToList() or .ToArray().

When you use IEnumerable, you give the compiler a chance to defer work until later,
possibly optimizing along the way. If you use ToList() you force the compiler to reify the results right away.

IEnumerable types have a method to get the next item in the collection. It doesn’t need the whole collection to be in memory and doesn’t know how many items are in it, foreach just keeps getting the next item until it runs out. On the other hand Lists and Arrays know how many items are in the collection and have more acknowledgment of their whole overall structure.



IList:

  1. IList exists in System.Collections Namespace.
  2. IList is used to access an element in a specific position/index in a list.
  3. Like IEnumerable, IList is also best to query data from in-memory collections like List, Array, etc.
  4. IList is useful when you want to Add or Remove items from the list.
  5. IList can find out the no of elements in the collection without iterating the collection.
  6. IList also supports deferred execution.
  7. IList doesn't support further filtering.

Please visit this link to see the IList interface methods. Please read some Do's and Don't here regarding collections here.



Q095. What is the use of Params keyword in C#?

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. Following are the fundamental points of a params keyword:

  1. The params parameter type must be a single-dimensional array otherwise you will get a compile-time error.
  2. The compiler uses a 1D array of respective data types internally for the params parameter. 
  3. Only one params type parameter is permitted in any method definition.
  4. It is an optional parameter and a final parameter.
  5. Since the params parameter is an optional parameter, if no argument is passed, the length of the params list is always zero by default.
  6. No additional parameters are permitted after the params keyword in a method declaration. So the params parameter must be the last parameter in the method definition.
  7. For the params parameter, you can pass either a comma-separated (CSV) list of arguments or an array of the type specified or a single value itself. Even you can skip it at all.
  8. The method having an optional parameter win over a method having a params parameter in method overloading.

Please read more about the Param Parameter and Method Overloading Rules here.



Q096. What is the difference between Equality Operator "==" and .Equals() method comparison in C#?

In C# there are two ways to compare two items i.e == operator and . Equals() method. The “==” is a C# operator while “Equals” is a polymorphic method. So “==” is a C# language feature while “Equals” is an object-oriented programming feature that follows polymorphism. 

Whenever you are comparing variables they are either value types or reference types. When values types are compared they are compared on the basis of “Content” when reference types are compared they are compared on the basis of “Reference”(memory location) and not “Content. 

Both the == Operator and the Equals() method are used to compare objects. Both can be applied on both value type (primitive types) and reference type objects comparison.








The main difference between them is that the Equality Operator (==) always compares the reference (memory pointer address) of the object while and Equals() method compares only the contents of the object. Because the Object class is the base class for all types in the .NET Framework, the Object.Equals(Object) method provides the default equality comparison for all other types as well.

Object.Equals() method determines whether two object instances are equal while == operator check if their operands are equal or not. The equality operator == returns true if its operands are equal, false otherwise. Similarly, the Equals method returns true if the content( instance for reference type and value for primitive type) of its operands are equal.

If the current instance is a reference type, the Equals(Object) method tests for reference equality, and if the current instance is a value type, the Equals(Object) method tests for value equality.

So when you compare value types( int, double, byte) either by using “==” or “Equals” it’s always based on content hence producing the same result.
When you compare reference type objects (class, interface, string) they are compared on the basis of reference, so both may produce different results.



String Comparision:

We know that a String is a very special data type that is a reference type but behaves like a value type. Strings are immutable objects in C#. So in the case of a string, the Equality Operator (==) always does content comparison not reference comparison. Two string operands are equal when both of them are null or both string instances are of the same length and have identical characters in each character position.

But remember that for using the Equals method the object must not be null otherwise you will get a Null Reference Exception, but you will not get any exception in case of equality operator comparison. So “==” works with nulls but “Equals” crashes when you compare NULL values.

The other difference between them is that the equality operator “==” does type checking at compile time while “Equals” during runtime.

The last difference between them is that although a structure is value type in C# you cannot use the "==" operator for comparison but you can use the Equals method.

Please watch the == vs Equals() comparison video here for more details. You can also watch the string vs String video here and the String vs StringBuilder video here for more details.








Q097. What is a private constructor? What is the use of a private constructor?

If a constructor is created with a private access modifier, then it is known as a Private Constructor. A private constructor is a special instance constructor that is generally used in classes that contain static members only. 

If we do not use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.

Also a private constructor without having any parameters prevent the automatic generation of the default constructor.






  1. A private constructor is generally used for singleton implementation.
  2. A class only having a default private constructor cannot be inherited.
  3. Private constructors are used for preventing the instantiation of a class.
  4. A class having only private constructors cannot be instantiated, except the nested class.

Please read more about the private constructor here and watch the private constructor video here for more details.



Q098. What is a static constructor in C#? How can you call the static constructor?

Static constructors are parameterless non-instance constructors.  Static constructors are used for initializing a static class or static data members of a non-static class. 

Static constructors are invoked only once while creating the object of the non-static class or on the creation of the first reference to a static member.






  1. A parameterized static constructor is not allowed.
  2. No access modifier is allowed for static constructors since they are private implicitly. 
  3. Static constructor overloading is not allowed
  4. Only a class or struct can contain a static constructor.
  5. A static constructor is never inherited since it is private implicitly.
  6. A static constructor can only access or initialize static data members.
  7. The static constructors are always called before any instance constructor.
  8. A static constructor can only access or initialize static data members.
  9. A static class can only have a static constructor.

Please read more about the static constructor here and watch the static constructor video here for more details.



Q099. What is the Constructor Chaining in C#? How it is different from Constructor Overloading?

Constructor Chaining is a way to invoke one constructor from another constructor. Constructor Chaining always happens in the case of inheritance. If you do not specify anything the default is base.

To do constructor chaining we have to use this keyword after the constructor definition. We can also chain to the base class constructors by using the base keyword.






In constructor chaining, we must have to know the order of the execution sequence. A chained constructor is always called first. Circular chaining is not allowed.

We can use the constructor chaining for validation. Instead of duplicating the assignment and validation logic in all the constructors, we move it into a single constructor. And then call that constructor in other constructors. This also makes the code easier to maintain and understand.

Please read more about the constructor chaining here and watch the constructor chaining video here for more details.








Q100. Can you prevent a class from being instantiated? What are the different ways to do that?

Normally we use the "sealed" class to prevent the inheritance in C#. In VB.Net "NotInheritable" keyword serves the purpose of sealing. In Java "final" keyword serves the same purpose. 

But based on the requirement, we can use the following in C#:

i) Sealed Class: Sealed class is mainly used to prevent subclassing in C#. If we decorate a class with a sealed modifier, no one can inherit from that class.

Please read more about the sealed class here for more details.






ii) Private Constructor: If you define a default parameterless private constructor in any class, then it cannot be inherited or instantiated due to its protection level. But if there is any public constructor along with the default parameterless private constructor, then it can be instantiated, but still cannot be inherited.

Please read more about the private constructor here. You can also watch the private constructor video here.

iii) Static Class: Since all the static classes are sealed implicitly, you can also use static classes based on the requirement.

Please read more about the static class here. You can also watch the static class video here.






iv) Structure: Since all the structs are sealed implicitly.  A struct cannot inherit from any struct or class but a struct can implement the interface. We can also use struct based on our requirements. In the .Net Framework, structs are used for defining a lot of namespaces and libraries.

Please read more about the structure here.



To Be Continued Part-11...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedIn, Facebook, Telegram, Quora, YouTube, Twitter, Pinterest, Tumbler, VK, and WhatsApp for regular updates.


No comments:

Post a Comment

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