Tech Point Fundamentals

Sunday, August 7, 2022

C# Interview Questions and Answers - Part 12

C# Interview Questions and Answers - Part 12

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


Q121. What is the difference between final, finally, and finalize?

The basic difference between final, finally, and finalize is that the final is an access modifier used for restriction, finally is a code block to execute a set of statements whether an exception is triggered or not, and finalize is the method of the object class to release the unmanaged resource.



Final:

Java has the final keyword but C# does not have any final keyword. However, for the sealed method, the compiler uses the final modifier internally. Please see the IL code generated by the compiler here for a C# sealed method.

C# use the sealed keyword for the same purpose. But unlike Java, a sealed keyword can only be applied to method and class, not on property or variable. In Java, the final keyword can be used for class, method, property, and variables as well.

The Final or sealed modifier is used to apply restrictions on a class or method. The final class or sealed can't be inherited, a final method (sealed) can't be overridden further and the final variable value can't be changed.

Please read the sealed class and sealed method article here for more detail.








Finally:

Finally is a code block that is used after the try-catch block or after the try block.  The final block is used to execute a given set of statements, whether an exception is thrown or not thrown. 

The finally block generally contains the logic to release the resource. The Iterator pattern and using dispose pattern always use the try-finally exception handling pattern. Please watch the try-finally video here for more detail.








Finalizer:

Finalize is a method of Object class. The Finalize in C# is used to free unmanaged resources like database connections etc. The finalize method is used to perform clean-up processing just before the object is garbage collected. 

It is invoked by the GC just before an object is discarded by the garbage collector. Please read the Finalizer article here for more detail.



Q122. What is the difference between First() and FirstOrDefualt() in C#?

Both First() and FirstOrDefualt() are used to get the first record of the object collection.

The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() will return the default value (null) if there is no result data.

So the First() method will throw System.InvalidOperationException exception if there is no result data but FirstOrDefault() returns the default value i.e null if there is no result data.



Q123. What is the volatile keyword? What is the use of volatile keywords in C#?

The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. So the volatile keyword is used to tell the compiler not to use any optimization on the volatile marked variables.

JIT compiler always does some optimization strategy while compiling the code. The optimization techniques used by the JIT might lead to unpredictable results when your .Net program is trying to perform non-volatile reads of data in a multithreaded scenario. 

However, in C# all memory writes are volatile irrespective of whether you are writing data to a volatile or a non-volatile object. But the ambiguity happens when you are reading data.

When you are reading data that is non-volatile, the executing thread may or may not always get the latest value.  If the object is volatile, the thread always gets the most up-to-date value








The volatile keyword in C# is used to inform the JIT compiler that the value of the variable should never be cached because it might be changed by the operating system, the hardware, or a concurrently executing thread. So the compiler avoids using any optimizations on the variable that might lead to data conflicts, i.e. to different threads accessing different values of the variable.

While using the volatile keyword, you must have to follow some rules:

  1. You can use the volatile keyword with any reference, pointer, and enum types.
  2. When you specify a reference type object as volatile, only the pointer address is volatile, not the value of the instance.
  3. You can also use the volatile modifier with byte, short, int, char, float, and bool types.
  4. But a local instance variable cannot be declared as volatile. 
  5. Also, a double variable cannot be volatile because it is 64 bits in size, larger than the word size on x86 systems. If you need to make a double variable volatile, you should wrap it inside in class.

Please watch the volatile video here for more details.



Q124. What is the difference between Deferred Execution vs Immediate Execution? or What is the difference between Lazy Operators vs Greedy Operators?

LINQ provides two different behaviors of Query Execution i.e. Deferred Execution and Immediate Execution. By default, LINQ uses deferred execution. So LINQ query is not executed when constructed but when enumerated.

When we write a LINQ query, it doesn’t execute by itself. It executes only when we access the query results means the execution of the query is deferred until the query variable is iterated over in a loop.

There are two types of query executions in LINQ:



Immediate Execution:

  1. In Immediate Execution Query is executed at the point of its declaration.
  2. Greedy Operators are used for Immediate Execution.
  3. For example Aggregate Functions (Count, Average, Min, Max, Sum) and Element Operators (First, Last, FirstOrDefault, LastOrDefault, Single, ToList, ToArray, ToDictionary, etc) are used for Immediate Execution.



Deferred Execution:

  1. Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. So a Deferred Execution doesn’t compute the result until the caller actually uses it.
  2. In Deferred Execution Query is not executed at the point of its declaration. 
  3. Lazy Operators are used for deferred execution. For example Projection Operator (Select, SelectMany) and Restriction Operator ( Where, Paging Operator like Take, Skip) are the Lazy Operators.
  4. Deferred execution greatly improves performance by avoiding unnecessary execution.  It is applicable on any in-memory collection as well as remote LINQ providers.
  5. Deferred execution re-evaluates each execution i.e is called lazy evaluation. So it always gives you the latest data.
  6. Deferred execution is supported directly in the C# language by the yield keyword when used within an iterator block. So you can implement deferred execution for your custom extension methods for IEnumerable using the yield keyword of C#. Please read more about the yield statement here.

The LINQ technologies make extensive use of deferred execution in both the members of the core System.Linq classes and in the extension methods in the various LINQ namespaces, such as System.Xml.Linq.Extensions.



Q125. What is the difference between Lazy Loading vs Early Loading in C#? 

Eager Evaluation vs Lazy Evaluation OR Lazy Loading vs Eager Loading:

When you write a method that implements deferred execution, you also have to decide whether to implement the method using lazy evaluation or eager evaluation. Lazy Loading and Explicit Loading both are types of deferred execution.

Lazy Loading says that “don’t do the work until you absolutely have to.” So in Lazy Loading, a query is not executed, until it is requested.  In Entity Framework, you can turn off the lazy loading feature by setting the LazyLoadingEnabled property of the ContextOptions on context to false.

context.ContextOptions.LazyLoadingEnabled = false;



Eager Loading says that “do all the work in advance”. So in Eager Loading, the LINQ query is executed when any Conversion operator like ToArray(), ToList(), ToDictionary(), ToLookup() is called. In LINQ to an Entity, we can also use the Include() method to make Eager Loading.

context.Contacts.Include("User.UserRole");

Explicit Loading says that “do all the work even with lazy loading disabled”.  So even with lazy loading disabled, it is still possible to lazily load related entities. For that, we have to make an explicit call to the Load() method. 

context.Entry(post).Reference(p => p.UserList).Load();

In Lazy Evaluation, every element of the source collection is processed during each call to the iterator. Lazy evaluation usually gives better performance because it distributes overhead processing evenly throughout the evaluation of the collection and minimizes the use of temporary data.

On the other hand in Eager Evaluation, the first call to the iterator will result in the entire collection being processed.  Due to this a temporary copy of the source collection might also be required for example the OrderBy clause.



Advantage of Deferred Execution:

  1. Deferred Execution avoids unnecessary query execution and hence improves performance.
  2. Query construction and Query execution are decoupled, so we can create the LINQ query in several steps.
  3. Deferred Execution prevents loading all the data from remote to in memory, so it enhances the performance of the application.
  4. A deferred execution query is always reevaluated when you re-enumerate so we always get the latest data.



Q126. What is the difference between Late Binding and Lazy Loading? Are both the same? 

Lazy Loading vs Late Binding:

Lazy Loading is the query execution concept where a query is not executed until it is requested. Projection Operator (Select, SelectMany) and Restriction Operator ( Where, Paging Operator like Take, Skip) are the Lazy Operators which are used in Lazy Loading.

On the other hand, Late Binding is the concept of binding a method to the object at run-time. It can be achieved by method overriding

So Lazy Loading and Late Binding both are not the same. Please read more about the late binding here for more details.








Q127. What is the difference between Early Binding and Early Loading? Are both the same?

Eager Loading vs Early Binding:

Eager Loading is the query execution concept where a query is executed immediately where it is declared. Greedy Operators like Aggregate Functions (Count, Average, Min, Max, Sum) and Element Operators (First, Last, FirstOrDefault, LastOrDefault, Single, ToList, ToArray, ToDictionary, etc) are used for Eager Loading.

On the other hand, Early Binding is the concept of binding a method to the object at compile time. It can be achieved by method overloading.

So Eager Loading and Early Binding are not the same. Please read more about the late binding here for more details.



Q128. What is the difference between "this" vs "base" keyword in C#?

Both this and base are used to refer to the context of a class member i.e current or base class.

The "base" Keyword:

  1. The "base" keyword is used to access the base class members from a derived class.
  2. The "base" keyword can be used to call a base class method that has been overridden in the derived class. Please read more here.
  3. The"base" keyword is used to call the base class constructor or you can say to pass the parameters to the base class constructors. Please read more here.
  4. The "base" keyword cannot be used in a static class or for a static member. Please read more here.








The "this" Keyword:

  1. A "this" keyword refers to the current instance of the class. So it is generally ignored as it is implicitly there.
  2. It is also used to differentiate between the method's formal parameters and class fields if they both have the same name.
  3. A  “this” keyword is also used to call another constructor from a constructor in the same class. This is known as constructor chaining. Please read more here.
  4. A "this" keyword is also used to define the first binding parameter in the extension method. Please read more here.
  5. A "this" keyword is used to define the indexers. Please read more here.








Q129. What is the difference between foreach loop and for loop in C#?

In C# for loop is used to perform any repetitive task for "n" number of times. Here we can specify the initial value and increment or decrement operation on each iteration explicitly. We can also specify multiple multiple loop variables to control the iterations.

On the other hand, foreach loop is also used for doing any task n number of times but it does not provide any control variable explicitly. The loop control value is decided automatically depending on the total collection of arrays or list generic or ArrayList or object collections.



For Statement:

  1. The for statement executes a statement or a block of statements while a specified Boolean expression evaluates to true. 
  2. The for loop has three sections, the initialization section, condition section, and iterator section. However, all the sections of the for statement are optional.
  3. A for statement uses the loop initialization variables and loop termination logic explicitly. However, if you don't declare a loop variable in the initializer section, you can use zero or more of the expressions from the preceding list in the initializer section as well.
  4. The initializer section is executed only once, before entering the loop.
  5. A condition section is a boolean expression that determines whether the next iteration in the loop should be executed or not. It can contain zero or more expressions separated by commas.
  6. The iterator section defines what happens after each execution of the body of the loop. The iterator section contains increment or decrement on the counter.
  7. At last, the body of the loop must be a single statement or a block of statements.



Foreach Statement:

  1. The foreach statement executes a statement or a block of statements for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface.
  2. If the foreach statement is applied to null, a NullReferenceException is thrown. 
  3. If the source collection of the foreach statement is empty, the body of the foreach statement isn't executed and skipped.
  4. Beginning with C# 8.0, you can use the await foreach statement to consume an asynchronous stream of data, that is, the collection type that implements the IAsyncEnumerable<T> interface.
  5. You can use the var keyword to let the compiler infer the type of an iteration variable in the foreach statement. However, you can also explicitly specify the type of iteration variable.



For Loop vs ForEach Loop:

  1. The foreach statement enumerates the elements of a collection and executes its body for each element of the collection. On the other hand a for statement executes its body while a specified Boolean expression evaluates to true.
  2. In for loop, we iterate the collection in both forward and backward directions, But in the foreach loop, we can iterate a collection only in the forward direction, not in a backward direction.
  3. In terms of a variable declaration, foreach loop has five variable declarations whereas for loop only have three variable declarations.
  4. A foreach loop also creates a copy of a collection temporarily whereas the for loop doesn’t do.
  5. Foreach loops do not keep track of the index. So we cannot obtain array index in the ForEach loop but we can do that in the for loop.
  6. Foreach loop is always forward readonly so they are not appropriate when you want to modify the collection but a for loop can be used in this scenario.



Q130. What is the difference between instance field and property in the C# class?

You can store value using either a field or a property and retrieve the value back from them. You can even protect both fields and properties using access modifiers such as private or protected. Both can be defined in class and structure. 

The main difference between a field and a property is that a field is a variable of any type that is declared directly in the class while a property is a member that provides a flexible mechanism to read, write or compute the value of a private field. An interface cannot define an instance field but a class or struct can have instance fields.

Instance fields are actual variables that store a particular piece of information. Properties offer another level of abstraction to expose the fields. This additional abstraction layer in properties enables the developers to apply access modifiers separately for getters and setters.








The properties do not have storage locations. The properties have accessors that contain the executable statements to read the values and to set the values. The accessor declarations can contain a get accessor and a set accessor. Also, you cannot apply any validation logic on instance fields but you can do that on property.

For auto-properties that you use, the compiler will generate backing fields and associated methods to access the fields for you. By using property, you can restrict the external user to either set the value(only set accessor) or read (only get accessor) the value or both (both get and set accessor).

A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type. A class or struct may have instance fields, static fields, or both. Instance fields are specific to an instance of a type while a static field belongs to the type itself, and is shared among all instances of that type.

Please watch the instance field vs property video here for more details.



To Be Continued Part-13...


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.