• Skip to primary navigation
  • Skip to main content

Nikhil Mittal

|| Software Developer || App Developer ||

  • Home
  • About Me
  • Blog
  • Testimonials
  • Achievements
  • Portfolio
  • Interview Q&As
    • Angular – QA Series 1
    • Angular – QA Series 2
    • Angular – QA Series 3
    • Angular – QA Series 4
    • Convert Angular App to Mobile APK
    • C# TYPICAL QUESTIONS – SERIES
    • Advanced Q & A – Series 1
    • Advanced Q&A – Series 2
    • Advanced Q&A Series – 3
  • Free Video Tutorials
    • ASP.NET C#
    • C# Tutorial – In Hindi
    • C# Tutorial – English
    • C#-Advanced
    • MVC DOT NET 4.8
    • Web API Dot Net Core 3.1
    • Azure DevOps
    • HTML/CSS – In Hindi
    • SQL Developer
    • Angular 10+
    • Corporate Skills
  • Consulting
  • Contact Us

C# TYPICAL QUESTIONS – SERIES

# Yield Keyword:

Example Take a code as below:

Required Change is display values only greater than 3:

Program could be:

Same thing achieved using yield: ( Custom Iteration)

Explanation:

The control moves from the caller to the source and source to caller (to and fro)

Another thing that can be achieved is : (Stateful Iteration )

Code for the stateful iteration:

Full Code:

# IENUMERABLE VS IENUMERATOR:

Program for IEnumerable:

Program for IEnumerator:

IEnumerable uses IEnumerator internally:

Difference:

Using IEnumerable:

It does not maintains state. In second function it starts from 1900.

Using IEnumerator:

It maintains state. In second function it starts from 2001.

IEnumerable does not remember states, IEnumerator remembers states.

Dependency Injection & Inversion Of Control:

Dependency injection (DI) VS Inversion of Control (IOC)

The main goal of Inversion of control and Dependency injection is to remove dependencies of a application. This makes the system more decoupled and maintainable.

First let’s try to understand IOC (Inversion of control).  If you go back to old computer programming days, program flow used to run in its own control.  For instance let’s consider a simple chat application flow as shown in the below flow diagram.

  1. End user sends chat message.
  2. Application waits for the message from the other end.
  3. If no message is found it goes to Step 2 or else moves to Step 4.
  4. Displays the message.
  5. User continues with his work ahead.
http://3.bp.blogspot.com/-Sb34Uxuvjmk/UZCCb_05h1I/AAAAAAAAEgA/qOSoSUw04e0/s1600/1st+image.jpg

Now if you analyze the program flow closely, it’s sequential. The program is in control of himself. Inversion of control means the program delegates control to someone else who will drive the flow. For instance if we make the chat application event based then the flow of the program will go something as below:-

  1. End user sends chat message.
  2. User continues with his work ahead.
  3. Application listens to events. If a message arrives event is activated and message is received and displayed.
http://3.bp.blogspot.com/-4Y4krJiAn0U/UZCCxNPNDjI/AAAAAAAAEgI/p1bqKzyZPw4/s1600/2nd+image.jpg

If you see the program flow it’s not sequential, its event based.  So now the control is inverted. So rather than the internal program controlling the flow, events drive the program flow. Event flow approach is more flexible as their no direct invocation which leads to more flexibility.

A word of caution here, do not conclude that IOC are implemented by only events.  You can delegate the control flow by callback delegates, observer pattern, events, DI (Dependency injection) and lot of other ways.

IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC. IOC is a concept where the flow of application is inverted.   So for example rather than the caller calling the method.

SomeObject.Call();

Will get replaced with an event based approach as shown below.

SomeObject.WhenEvent += Call();

In the above code the caller is exposing an event and when that event occurs he is taking action.  It’s based on the Hollywood principle “Don’t call us we will call you”.  In Hollywood when artists used to give auditions the judges would say them “Don’t call us we will call you”.

The above approach makes code more flexible as the caller is not aware of the object methods and the object is not aware of caller program flow.

http://1.bp.blogspot.com/-2JkcEGnJVrY/UZCDAoPjk8I/AAAAAAAAEgQ/ilz1zM5fc78/s1600/3rd+image.jpg

DI provides objects that an object needs.  So rather than the dependencies construct themselves they are injected by some external means.  For instance let’s say we have the following below class “Customer” who uses a “Logger” class to log errors. So rather than creating the “Logger” from within the class, you can inject the same via a constructor as shown in the below code snippet.

http://4.bp.blogspot.com/-vUOcNsQcrUk/UZCDROepyWI/AAAAAAAAEgY/8NbtFggPfh4/s400/4th+image.jpg

The biggest benefit achieved by the above approach is “Decoupling”. You can now invoke the customer object and pass any kind of “Logger” object as shown in the below code.

Customer obj = new Customer(new EmailLogger());

Customer obj1 = new Customer(new EventViewerLogger());

http://3.bp.blogspot.com/-_9lG6Z7oO6M/UZCBXsOn8PI/AAAAAAAAEf0/QRrVQEUSVuY/s400/ID.jpg

Lazy Loading:

What happens during Lazy Loading:

It was achieved using below code:

Using Lazy Keyword:

Other than that to get the data:

Till the object is not created it will not get the data as IsValueCreated will be false:

NEW Keyword:

In C#, a method in a derived class can have the same name as a method in the base class. You can specify how the methods interact by using the new and override keywords. The override modifier extends the base class method, and thenew modifier hides it.

Introduction

In C# there are many operators and keywords available.

Today, we will explain “new”. We can divide the use of the “new” keyword into the following uses:

  • An operator
  • A modifier
  • A constraint

We will discuss all the preceding in this article.

new as an operator

It is used to create objects and invoke a constructor.

Using the “new” operator, we can create an object or instantiate an object, in other words with the “new” operator we can invoke a constructor.

Let’s create a class for example:

  1. public class Author  
  2. {  
  3. public Author()  
  4. {  
  5. }  
  6. public Author(string firstName, string lastName, int rank)  
  7. {  
  8. FirstName = firstName;  
  9. LastName = lastName;  
  10. Rank = rank;  
  11. }  
  12. public int num;  
  13. public string FirstName { get; set; }  
  14. public string LastName { get; set; }  
  15. public int Rank { get; set; }  
  16. new public string FullName()  
  17. {  
  18. return string.Format(“{0} {1}”, FirstName, LastName);  
  19. }  
  20. }   

Initialize a class:

  1. //We can instantiate or invoke a construtor  
  2. var author = new Author();   

Initialize collections:

  1. //we can initialize a collection  
  2.   
  3. var authors = new List<Author>();   

Create an instance of anonymous types:

  1. //anonymous can also be initialized by new  
  2.   
  3. var authorAnonymous = from auth in authors  
  4. select new { FullName = string.Format(“{0} {1}”, auth.FirstName, auth.LastName) };   

An important thing to notice is that with the use of the “new” operator we can invoke the default constructor of a value type.

  1. Int num = new int(); //think about this  

Interesting point

We cannot overload the “new” operator.

It will throw an exception if it fails to allocate memory. Think of a scenario where it does fail.

Declaring a default constructor for a struct results in an error. The reason is that every value type implicitly invokes its default constructor.

The following is wrong:

  1. Public struct MyStruct  
  2. {  
  3. Public MyStruct() { }  
  4. Public int num1;  
  5. }  

The “new” operator only assigns the memory and does not destroy memory that depends upon the scope.

Value-types objects, like int, are created on the stack and reference type objects like “Author” are created on the heap.

The new as a modifier

It hides a member that is inherited from a base class.

So, what does this mean?

It simply replaces the base class version.

What happens if I do not use “new”?

So, in this case your code runs perfectly with a compiler warning that you are hiding without using the “new” modifier.

There will be an error if you use both “new” and “override” on the same member.

The following is wrong:

  1. public class BaseAuthor  
  2. {  
  3. public class Author  
  4. {  
  5. public virtual string FullName()  
  6. {  
  7. return string.Format(“{0} {1}”, FirstName, LastName);  
  8. }  
  9. }  
  10. }  
  11. public class DerivedAuthor:BaseAuthor  
  12. {  
  13. new public override string FullName()  
  14. {  
  15. return string.Format(“{0} {1}”, FirstName, LastName);  
  16. }  
  17. }  

Here we are hiding the base class in the derived class:

  1. public class BaseAuthor  
  2. {  
  3. public class Author  
  4. {  
  5. public virtual string FullName()  
  6. {  
  7. return string.Format(“{0} {1}”, FirstName, LastName);  
  8. }  
  9. }  
  10. }  
  11. public class DerivedAuthor:BaseAuthor  
  12. {  
  13. new public class Author  
  14. {  
  15. public virtual string FullName()  
  16. {  
  17. return string.Format(“{0} {1}”, FirstName, LastName);  
  18. }  
  19. }  
  20. }   

Now, we can invoke the parent and derived classes as:

  1. Author = new Author();  
  2.   
  3. BaseAuthor.Author = new BaseAuthor.Author();  

“new” as a Constraint

It specifies that the generic type must have a public parameterless constructor. The “new” constraint cannot be used on an abstract type.

  1. public class AuthorFactory<T> where T : new()  
  2. {  
  3. public T GetAuthor()  
  4. {  
  5. return new T();  
  6. }  
  7. }   

Now, we can initialize the preceding as:

  1. var factoryAuth = new AuthorFactory<Author>();   

To get an instance of the preceding type:

  1. var objAuth = factoryAuth.GetAuthor();   

If using multiple constraints then the “new” constraint must be last:

  1. public class AuthorFactoryComparable<T>  
  2. where T : IComparable, new()  
  3. {  
  4. //logic goes here  
  5. }  

Conclusion 

We have discussed the “new” keyword of C#. It is defined as:

  • an operator
  • a modifier
  • a constraint

# Finalize Keyword:

C++ destructors are executed immediately when an object goes out of scope, whereas finalize is called during object cleanup at GC. In C#, finalize cannot be directly called or overridden. If a destructor is declared, it is converted to the finalizemethod when the program is compiled.

Introduction

We have been using the Dispose method for disposing objects in .NET. For the same purpose, we may also use the Finalize method. In this article I will try to explain what the Dispose and the Finalize methods are and where to use the Finalize and where to use the Dispose. I will also try to explain the difference between them.

Dispose

Garbage collector (GC) plays the main and important role in .NET for memory management so programmer can focus on the application functionality. Garbage collector is responsible for releasing the memory (objects) that is not being used by the application. But GC has limitation that, it can reclaim or release only memory which is used by managed resources. There are a couple of resources which GC is not able to release as it doesn’t have information that, how to claim memory from those resources like File handlers, window handlers, network sockets, database connections etc. If your application these resources than it’s programs responsibility to release unmanaged resources. For example, if we open a file in our program and not closed it after processing than that file will not be available for other operation or it is being used by other application than they can not open or modify that file. For this purpose FileStream class provides Dispose method. We must call this method after file processing finished. Otherwise it will through exception Access Denied or file is being used by other program. 

Close Vs Dispose

Some objects expose Close and Dispose two methods. For Stream classes both serve the same purpose. Dispose method calls Close method inside.

  1. void Dispose()   
  2. {  
  3.     this.Close();  
  4. }  

Here question comes, why do we need Dispose method in Stream.Having Dispose method will enable you to write below code and implicitly call dispose method and ultimately will call Close method.

  1. using(FileStream file = new FileStream(“path”, FileMode.Open, FileAccess.Read))   
  2. {  
  3.     //Do something with file   
  4. }  

But for some classes both methods behave slightly different. For example Connection class. If Close method is called than it will disconnect with database and release all resources being used by the connection object and Open method will reconnect it again with database without reinitializing the connection object. HoweverDispose method completely release the connection object and cannot be reopen just calling Open method. We will have re-initialize the Connection object.

Creating Dispose

To implement Dispose method for your custom class, you need to implement IDisposable interface. IDisposable interface expose Dispose method where code to release unmanaged resource will be written.

Finalize

Finalize method also called destructor to the class. Finalize method can not be called explicitly in the code. Only Garbage collector can call the the Finalize when object become inaccessible. Finalize method cannot be implemented directly it can only be implement via declaring destructor. Following class illustrate, how to declare destructor. It is recommend that implement Finalize and Dispose method together if you need to implement Finalize method. After compilation destructor becomes Finalize method.

  1. public class MyClass: IDisposable {  
  2.   
  3.     //Construcotr   
  4.     public MyClass() {  
  5.         //Initialization:   
  6.     }  
  7.   
  8.     //Destrucor also called Finalize   
  9.     ~MyClass() {  
  10.         this.Dispose();  
  11.     }  
  12.   
  13.     public void Dispose() {  
  14.         //write code to release unmanaged resource.   
  15.     }  
  16. }  

Using Finalize

Now question is, When to implement Finalize? There may be any unmanaged resource for example file stream declared at class level. We may not be knowing what stage or which step should be appropriate to close the file. This object is being use at many places in the application. So in this scenario Finalize can be appropriate location where unmanaged resource can be released. It means, clean the memory acquired by the unmanaged resource as soon as object is inaccessible to application.

Finalize is bit expensive to use. It doesn’t clean the memory immediately. When application runs, Garbage collector maintains a separate queue/array when it adds all object which has finalized implemented. Other term GC knows which object has Finalize implemented. When the object is ready to claim memory, Garbage Collector call finalize method for that object and remove from the collection. In this process it just clean the memory that used by unmanaged resource. Memory used by managed resource still in heap as inaccessible reference. That memory release, whenever Garbage Collector run next time. Due to finalize method GC will not clear entire memory associated with object in fist attempt.

Conclusion

It is always recommended that, one should not implement the Finalize method until it is extremely necessary. First priority should always be to implement the Dispose method and clean unmanaged as soon as possible when processing finish with that.

#: Ref VS Out 

Introduction

The keywords ref and out are used to pass arguments within a method or function. Both indicate that an argument / parameter is passed by reference. By default parameters are passed to a method by value. By using these keywords (ref and out) we can pass a parameter by reference.

Ref Keyword

The ref keyword passes arguments by reference. It means any changes made to this argument in the method will be reflected in that variable when control returns to the calling method.

Example code

  1. public static string GetNextName(ref int id)  
  2. {  
  3.     string returnText = “Next-” + id.ToString();  
  4.     id += 1;  
  5.     return returnText;  
  6. }  
  7. static void Main(string[] args)  
  8. {  
  9.     int i = 1;  
  10.     Console.WriteLine(“Previous value of integer i:” + i.ToString());  
  11.     string test = GetNextName(ref i);  
  12.     Console.WriteLine(“Current value of integer i:” + i.ToString());  
  13. }   

Output

Ref in C#

 

Out Keyword 

The out keyword passes arguments by reference. This is very similar to the ref keyword.

Example Code

  1. public static string GetNextNameByOut(out int id)  
  2. {  
  3.     id = 1;  
  4.     string returnText = “Next-” + id.ToString();  
  5.     return returnText;   
  6. }  
  7. static void Main(string[] args)  
  8. {  
  9.     int i = 0;  
  10.     Console.WriteLine(“Previous value of integer i:” + i.ToString());  
  11.     string test = GetNextNameByOut(out i);  
  12.     Console.WriteLine(“Current value of integer i:” + i.ToString());  
  13. }  

Output

Out in C#

Ref Vs Out

RefOut
The parameter or argument must be initialized first before it is passed to ref.It is not compulsory to initialize a parameter or argument before it is passed to an out.
It is not required to assign or initialize the value of a parameter (which is passed by ref) before returning to the calling method.A called method is required to assign or initialize a value of a parameter (which is passed to an out) before returning to the calling method.
Passing a parameter value by Ref is useful when the called method is also needed to modify the pass parameter.Declaring a parameter to an out method is useful when multiple values need to be returned from a function or method.
It is not compulsory to initialize a parameter value before using it in a calling method.A parameter value must be initialized within the calling method before its use.
When we use REF, data can be passed bi-directionally.When we use OUT data is passed only in a unidirectional way (from the called method to the caller method).
Both ref and out are treated differently at run time and they are treated the same at compile time.
Properties are not variables, therefore it cannot be passed as an out or ref parameter.

Ref / Out keyword and method Overloading

Both ref and out are treated differently at run time and they are treated the same at compile time, so methods cannot be overloaded if one method takes an argument as ref and the other takes an argument as an out.

Example code

  1. public static string GetNextName(ref int id)  
  2. {  
  3.     string returnText = “Next-” + id.ToString();  
  4.     id += 1;  
  5.     return returnText;  
  6. }  
  7. public static string GetNextName(out int id)  
  8. {  
  9.     id = 1;  
  10.     string returnText = “Next-” + id.ToString();  
  11.     return returnText;  
  12. }  

Output when the code is compiled:

method Overloading

However, method overloading can be possible when one method takes a ref or out argument and the other takes the same argument without ref or out.

Example Code

  1. public static string GetNextName(int id)  
  2. {  
  3.     string returnText = “Next-” + id.ToString();  
  4.     id += 1;  
  5.     return returnText;  
  6. }  
  7. public static string GetNextName(ref int id)  
  8. {  
  9.     string returnText = “Next-” + id.ToString();  
  10.     id += 1;  
  11.     return returnText;  
  12. }  

Summary

The out and ref keywords are useful when we want to return a value in the same variables as are passed as an argument. 

NEW FEATURES IN C#6.0

 ?—Conditional Access Operator

In earlier versions of the C# language, you always had to write the explicit if condition NULL checks before using an object or its property, as shown below.

private void GetMiddleName(Employee employee)

{

   string employeeMiddleName = “N/A”;

   if (employee != null && employee.EmployeeProfile

      != null)

      employeeMiddleName =

         employee.EmployeeProfile.MiddleName;

}

The same can be converted into a one-liner by using the Conditional Access Operator in C# 6.

private void GetMiddleName(Employee employee)

{

   string employeeMiddleName =

      employee?.EmployeeProfile?.MiddleName ?? “N/A”;

}

Notice the default value provided on the same line of code.

Primary Constructor

Primary Constructor is a feature in which you are allowed to pass the constructor parameters at the class declaration level instead of writing a separate constructor. The scope of the primary constructor parameters values is class level and will be available only at the time of class initialization. It comes to good use when it is used with the Auto-Property initializers.

// Primary constructor

class Basket(string item, int price)

{

   // Using primary constructor parameter values

   // to do auto property initialization.

   public string Item { get; } = item;

   public int Price { get; } = price;

}

 Await in the Catch Block

This is an important non-syntactic enhancement that will be available in C# 6. The await keyword can be called inside the catch and finally blocks. This opens up the way to perform an async exception handling or fallback process in case an exception happened during an async process call.

public async void Process()

{

   try

   {

      Processor processor = new Processor();

      await processor.ProccessAsync();

   }

   catch (Exception exception)

   {

      ExceptionLogger logger = new ExceptionLogger();

      // Catch operation also can be aync now!!

      await logger.HandleExceptionAsync(exception);

   }

Exception Filters

Exceptions can be filtered in the catch blocks with ease and cleanly with C# 6. Following is a sample source code where the intention is to handle all Exceptions except the SqlException type.

public async void Process()

{

   try

   {

      DataProcessor processor = ne

   }

   // Catches and handles only non sql exceptions

   catch (Exception exception) if(exception.GetType()

      != typeof(SqlException))

   {

      ExceptionLogger logger = new ExceptionLogger();

      logger.HandleException(exception);

   }

}

Q). what is default Http Verb in MVC

Ans: HTTPGET

***

Visits: 176
  • Home
  • About Me
  • You Tube
  • LinkedIn