Showing posts with label Csharp interview questions. Show all posts
Showing posts with label Csharp interview questions. Show all posts

Monday, July 11, 2016

== VS Equals in C#

Contents

Introduction

Point 1 :- Comparison on the basis of Equality

  • Scenario 1:- Value type comparison
  • Scenario 2:- Reference types comparison
  • Scenario 3:- String comparison, interning and object type casting
  • Point 2 :- Compile time VS RunTime

    Point 3 :- The NULL Situation

    When to use what :- Technical comparison VS Semantical comparison

    The Full Picture

    Introduction

    To compare equality between variables C# has provided two ways of doing comparison “==” and an overloaded method “equals()”. Most of the developers use “==” and “Equals” is hardly discussed.

    So in this small note we will discuss about differences between them and when to use what.

    Point 1 :- Comparison on the basis of Equality

    Answering to the point “There is no difference between equality comparison using “==” and “Equals()”, except when you are comparing “String” comparison.

    The common comparison Rule :-Whenever youare 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”.

    The above rule is respected by both “==” and “Equals”.

    Scenario 1:- Value type comparison

    When you compare value types / primitive data types ( int , double etc) either by using “==” or “Equals” it’s always based on content. In the below code you can see both comparison methods will show as “true”.

    int i = 10;
    int y = 10;
    Console.WriteLine(i == y); // true
    Console.WriteLine(i.Equals(y)); // true
    

    Scenario 2:- Reference types comparison

    Now when you compare objects they are compared on the basis of reference (internal memory pointer). Below obj and obj1 comparison either through “==” or “Equals” will be false. So in the below code even though both the object have property name as “Shiv” still it shows unequal. Because the comparison is based on internal memory reference which is different for “obj” and “obj1”.

    Customerobj = newCustomer();
    obj.Name = "Shiv";
    Customer obj1 = newCustomer();
    obj1.Name = "Shiv";
    Console.WriteLine(obj == obj1); // false
    Console.WriteLine(obj.Equals(obj1)); // false
    

    But the below code will display true as the pointer points to same object.

    Customerobj = newCustomer();
    obj.Name = "Shiv";
    Customer obj1 = obj;
    Console.WriteLine(obj == obj1); // true
    Console.WriteLine(obj.Equals(obj1)); // true
    

    Scenario 3:- String comparison, interning and object type casting

    Now strings are immutable objects or reference types so they should be checked using the rules of reference types. In other words in the below scenario when we assign value to “str” it creates a string object and in heap has “test” stored. When you now assign “str1” this a different object so it should be a different instance.

    But look at the value, it the same. So C# string follows interning rule. In other words if the content is same “str” and “str1” they point to the same memory location and data. So both “==” and “Equals” will be true.

    objectstr = "test";
    object str1 = "test";
    Console.WriteLine(str==str1);
    Console.WriteLine(str.Equals(str1));
    

    But now look at the below code where we are explicitly creating new separate objects of string with same value. We are forcing and overriding interning behavior of string.In the below code “==” will return false even though the content is same while “Equals” will return true. This is one place where the equality behavior differs.

    objectstr = newstring(newchar[] { 't', 'e', 's', 't' });
    object str1 = newstring(newchar[] { 't', 'e', 's', 't' });
    Console.WriteLine(str==str1); // false
    Console.WriteLine(str.Equals(str1));  // true
    

    Point 2 :- Compile time VS RunTime

    The next point which makes them different is when do type checks happen. “==” does type checking during compile time while “Equals” is more during runtime. You can see in the below code how “==” is showing a warning message with green sign saying that you are comparing different types and you can have issues. “Equals” does not show any such warnings.

    Point 3 :- The NULL Situation

    “==” works with nulls but “Equals” crashes when you compare NULL values , see the below print screen.

    When to use what :- Technical comparison VS Semantical comparison

    “==” is a C# operator while “Equals” is a polymorphic method. So in other words “==” is a language feature while “Equals” is an object oriented programming feature which follows polymorphism.

    Now comparison is of two types one is purely based on content and reference, means computer based comparison and other is based on semantics. Semantics means the actual meaning of a thing. For example 1 <> 70 numerically ( technically) but 1 $ = 70 Rs in real world semantically.

    Some more examples:-

    • Technically: - 1 is equal to 1.
    • Semantically: - 1 Dollar is not equal to 1 Rs.
    • Technically: - “Destination “ word is not equal to “Last Stop”.
    • Semantically: - “Destination” means same as “Last Stop”.

    So technical comparison is computer based while semantic comparison is business based or we can say there is some kind of domain rule for comparison purpose.

    So now when to use “==” and when to use “Equals”:-

    • If you are looking for technical comparison then use “==” and most of the time “==” suffices as developers mostly do technical comparison.
    • If you are comparing semantically then you need over the “equals” with the semantic comparison logic and you need to use “equals” method while comparing.

    The Full Picture

    So if we list down all the point the final conclusion is the below table.

    == Equals
    Usage Technical based. Semantic based.
    Value types Content based Comparison Content based Comparison
    Objects Reference based Comparison Reference based Comparison
    String Content based Comparison Content based Comparison
    String with no interning Reference based Comparison Content based Comparison
    Type checking Compile time Run time
    Nulls Works Can crash

    See the following practical video on understanding the difference between == and .Equals :-

    Monday, November 24, 2014

    Can we overload MVC controller action methods? (MVC Polymorphism)

    This Saturday and Sunday when i was taking MVC class in Mumbai one of the participants asked this weird question, Can we overload MVC action methods?. This question was asked to him during a MVC interview recently.

    For moment I wondered why interviewer such kind of questions which does not test anything about programmer's ability. But let's leave that argument from some other day and lets answer this question.

    Well the answer is YES and NO depending on your expectation. Now before you turn me in to a politician who answers from both side's let me explain you why i have given such kind of a dubious answer.

    Overloading or in other words polymorphism is a feature of object oriented programming. So if you have some kind of a below controller code which has methods overloaded with same name and different argument's it would compile very well.
    public class CustomerController : Controller
        {
            //
            // GET: /Customer/
    
    publicActionResultLoadCustomer()
            {
    return Content("LoadCustomer");
            }
    publicActionResultLoadCustomer(string str)
            {
    return Content("LoadCustomer with a string");
            }
        }
    
    But now if you are thinking that when you call "http://localhost:3450/Customer/LoadCustomer/" it should invoke "LoadCustomer" and when you call "http://localhost:3450/Customer/LoadCustomer/test" it should invoke "LoadCustomer(string str)" you are WRONG.

    If you try to this you will end with a below error. Read the word "Ambiguous" in the error , does something click. Ok , let me explain in more detail what the below error means.










    Polymorphism is a part of C# programming while HTTP is a protocol. HTTP does not understand polymorphism it works on the concept's or URL and URL can only have unique name's. So HTTP does not implement polymorphism.

    And i know if you answer with the above argument MVC interviewer would still press that he wants to implement polymorphism , so how do we go about doing it.

    If you wish to keep polymorphism and also want the HTTP request to work you can decorate one of the methods with "ActionName" as shown in the below code.
    public class CustomerController : Controller
        {
            //
            // GET: /Customer/
    
    publicActionResultLoadCustomer()
            {
    return Content("LoadCustomer");
            }
    
            [ActionName("LoadCustomerbyName")]
    publicActionResultLoadCustomer(string str)
            {
    return Content("LoadCustomer with a string");
            }
        }
    
    So now you can invoke with URL structure "Customer/LoadCustomer" the "LoadCustomer" action and with URL structure "Customer/LoadCustomerByName" the "LoadCustomer(string str)" will be invoked.























    In case you want to start learning MVC , below is a nice MVC step by step video series which will help you to learn MVC in 16 hours i.e. 2 day's. Give a try.



    Saturday, August 16, 2014

    Things you will miss in ASP.NET MVC as an ASP.NET Webform developer

    Introduction

    No CodeBehind

    No Server controls

    No Page life cycle

    No ViewState


    Introduction


    I have been a great fan of ASP.NET Webform development but for past 2 years ASP.NET MVC is the talk of the town. If you are new to MVC start here and if you want to learn MVC super-fast start here.

    Note: - If ASP.NET MVC and ASP.NET WebForm vocabulary is confusing please read this before moving ahead :-http://computerauthor.blogspot.in/2014/08/aspnet-vs-mvc-vocabulary-confusion_15.html.

    When I started ASP.NET MVC development it took lot of time as an ASP.NET webform developer to get adjusted and acquainted with ASP.NET MVC development thought. This article walks you through some important mind set changes you need to make when working with ASP.NET MVC.

     

    No CodeBehind


    The whole thought of MVC is to get rid of behind code. Because behind code is not reusable , not testable .So when you add a view / UI in MVC is you will be find no behind code. You will find “.ASPX” but there is no “ASPX.CS”. You will find CSHTML but there is no CSHTML.CS.


    Now the time we say “No Behind code” this has a cascading effect. The remaining points are the after effect of “No code behind” concept.

    No Server controls


    ASP.NET webform Server controls was always a life savior. It was like a magic where you drag and drop and you are done.Now because we do not have any behind code server controls will not be seen in your tool box. You have to use HTML to create your MVC UI. The maximum support officially you have currently is HTML Helper classes , you can read about it from here.


    You can use server controls on an ASPX view but it’s not advisable as it will generate inline code behind again defeating the purpose of MVC.

    No Page life cycle


    Because we do not have behind code there is no such thing as page life cycle in ASP.NETMVC.In ASP.NET Webform the first hit comes to the Page and then rest of the things happen. ASP.NET Webform is UI first approach while MVC is class first approach.

    In MVC the first hit comes to the controller class and then to the UI. So all the logic of page life cycle goes in the controller.So no more discussion on page life cycle and which event what code needs to be written.

    No ViewState


    There are no automated generated hidden fields like viewstate. We have more robust and fine tuned way of session management viewdata , tempdata ,viewbag and session variables. You can read more about them from clicking here.

    Want to Learn MVC in 2 days start from this video






    Friday, August 15, 2014

    ASP.NET VS MVC – Vocabulary confusion

    If you have clicked on this article thinking that ASP.NET is the old thing and MVC is the new thing then you need to seriously read this article.


    Recently I was taking Learn MVC in 2 days in Andheri Mumbai and I saw lot of participants thinking ASP.NET is different and MVC is different. During the MVC training many were referring ASP.NET as the old thing and MVC as the new thing. But actually they are one and the same thing.

    ASP.NET is a web framework of Microsoft and MVC is a visual studio code template to  write code using MVC architecture style. The proper name of OLD ASP.NET is “ASP.NET webforms”. So ASP.NET webform is the old ASP.NET with behind code and MVC is the new thing.


    This is also very much evident when you create an ASP.NET Web project using visual studio. In visual studio you will see two different templates one with the name “ASP.NET Webform” and the other with “ASP.NET MVC”.


    Note :- Web and Webform are one and the same thing.

    If you want to learn MVC step by step start from the below link

    http://www.codeproject.com/Articles/207797/Learn-MVC-Model-View-Controller-step-by-step-in

    Tuesday, July 8, 2014

    What is CodeLens?

    Code lens is a new feature in visual studio 2013 which helps us to understand three important things about our code while we are coding inside visual studio.

    All these three things(Impact, test and latest) are seen right above your class / method when you code in visual studio as shown in the below figure.


    Impact: - First thing code lens shows is when we change the code what isthe impact of those changes. For instancein the above figure you can see it stating that if you make any changes to the log method it will be impact 1 reference.

    If you click on references further it will also show which the classes it’s referencing. With this we come to know the level of impact this change will have further.

    In the below screen it’s stating that “ConsoleApplication2” and “UnitTest1.cs” are the classes which.


    If you further click on “Show on Code Map” menu you should see a graphical representation of dependencies.


    Test :- Second important thing code lens tells is whether this method was unit tested or not.  For instance you can see it say’s 1 passing means this method was unit tested.


    Latest: -Third thing it tells where this is a latest code or not. You can see the last menu which states this is not a latest code and you need to do a get latest from the server.

    But now for the bad news nothing is free, code lens is currently available only in ultimate edition. Wish it was free as air….. ;-)


    Below is a nice and short video of codelens created by www.questpond.com team.



    Thursday, June 12, 2014

    Explain MVC model binders ? ( ASP.NET MVC interview questions)

    Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model.



    Take the below simple HTML form example :-








    Now this form needs to fill the below “Customer” class model. If you see the HTML control name they are different from the class property name. For example HTML textbox control name is “CCode” and the class property name is “CustomerCode”.  This mapping code is written in HTML binder classes.

    publicclassCustomer
    {
    publicstring CustomerCode { get; set; }
    publicstring CustomerName { get; set; }
    }
    

    To create a model binder we need to implement “IModelBinder” interface and mapping code needs to be written in the “BindModel” method as shown in the below code.

    publicclassCustomerBinder : IModelBinder
    {
    
    publicobject BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
    HttpRequestBase request = controllerContext.HttpContext.Request;
    
    string strCustomerCode = request.Form.Get("CCode");
    string strCustomerName = request.Form.Get("CName");
    
    returnnewCustomer
                {
                    CustomerCode = strCustomerCode,
                    CustomerName = strCustomerName
                };
    }
    }
    

    Now in the action result method we need to use the “ModelBinder” attribute which will attach the binder with the class model.

    publicActionResult SubmitCustomer([ModelBinder(typeof(CustomerBinder))]Customer obj)        
    {
    
    return View(“DisplayCustomer”);
    }
    

    This MVC interview question was provided by questpond which conducts ASP.NET MVC training . In case you are new to MVC you can start from questpond video which is shown below.

    Tuesday, December 31, 2013

    What is IOC and Dependency injection and how do they differ from each other?(Design pattern interview questions with answers)

    When we talk about software programs they have LOGIC’s and LOGIC’s have FLOW. Take the below simple code. We have a “Customer” class which is instantiated from a console application.

    class Customer
        {
            private SQLServer Dal = new SQLServer();
            public bool validate()
            {
                return true;
            }
            public void Add()
            {
                if (validate())
                {
                    Dal.Add();
                }
            }
        }
        class SQLServer
        {
            public void Add()
            {
            }
        }

    Customer obj = new Customer();
    obj.Add();

    If you watch the program flow of the customer object it is as follows:-
    • Client creates object of the customer class.
    • Customer class creates the object of SQL Server data access layer.
    • Customer object then invokes “Validate” method.
    • Once the “Validate” method is successful then it invokes the “Add” method.


    In other words the “Customer” class is in control of his FLOW. Now let us complicate the situation.  Let’s say we have different flavors of data access layer.  So let’s say we have “SqlServer” and “Oracle” as shown below.

    So the best way to implement the same is my creating a generic interface “Dal” and pointing that generic interface to “SQLServer” or “Oracle” object depending on situations. So if you see the flow now:-
    • Client creates object of the customer class.
    • Customer class depending on configuration decided to create SQL Server object or Oracle object.
    • Customer object then invokes “Validate” method.
    • Once the “Validate” method is successful then it invokes the “Add” method.


    A good code is that code which takes care of his own logic rather than overloading with logic which he is not concerned with. For instance in this case the customer class is now taking care of logics like deciding which data access layer objects to be created.

    class Customer
        {
            private Dal dal;
            public Customer(int DalType)
            {
                if (DalType == 1)
                {
                    dal = new SQLServer();
                }
                else
                {
                    dal = new Oracle();
                }
            }
            public bool validate()
            {
                return true;
            }
            public void Add()
            {
                if (validate())
                {
                    dal.Add();
                }
            }
        }

    interface Dal
        {
            void Add();
        }
        class SQLServer : Dal
        {
            public void Add()
            {
            }
        }
        class Oracle : Dal
        {
            public void Add()
            {
                throw new NotImplementedException();
            }
        }

    This makes the customer class tightly coupled to the data access layer changes and second in long run this code becomes difficult to maintain. So the solution here  is customer class should perform his own concerned logic like validating customer class , calling add method of data access layer. But deciding which data access layer to create is not his part.

    So if this logic or this control is given to some other entity or can be INVERTED to some one else then the code would look much better.


    So if we change the code to something as shown below. Where the customer class say’s hey  look I am not concerned its Oracle or SQL Server. Pass me the generic interface object from the constructor and relieve me from the decision making logic of Data access layer.

    class Customer
     {
            private Dal dal;
            public Customer(Dal obj)
            {
                dal = obj;
            }
          …
          …
    }

    So now it’s the work of client or the invoker to decide which data access layer object has to be passed.

    If you visualize this scenario the flow of “Customer” class now takes care of his logic and the unconcerned logic is now passed to an external entity. This is termed as “Inversion of control”. The control or logic which is not part of that entity is taken care by someone else.

    Also if you put in other terms the flow of “Customer” class is now affected by external entities depending on whether they inject “SqlServer” object or “Oracle” object.

    A word of caution here, do not conclude that IOC can  only be implemented by exposing abstraction via constructor.  You can delegate the control flow by callback delegates, observer pattern, events, and lot of other ways.


    The above way of sending abstraction from constructor is termed as “dependency” injection.IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC.

    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.












    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());

    Inversion of control
    Dependency injection
    It’s a generic term and implemented in several ways (events, delegates etc).
    DI is a subtype of IOC and is implemented by constructor injection, setter injection or method injection.













































































    Saturday, July 27, 2013

    C# interview question with answers :- What is Fragile parent class problem in c# ?

    Inheritance is a great power by which developers can increase reusability in parent-child relationship. But with great powers comes greater responsibility and also problems. One of the problems which creep’s in is the “Fragile parent class problem”.


    Take a simple scenario (below is the image) where we have a simple parent child class relationship. Assume that this child class is used in lot of projects and installed in lot of places. Now assume after the child class has been deployed across locations, after some months there are some changes in the parent class.

    These changes can have cascading and unexpected behavior in child class as well. This unexpected behavior on child classes is termed as “Fragile class problem”.


    Consider the below scenario where we have a parent class called as “DbParent” with a virtual method “Insert”.

    class DbParent
    {
         
            public virtual void Insert()
            {
                Console.WriteLine("Parent insert");
            }

    }

    Below is a simple child class with his own “Insert” implementation which is installed across various locations.

    class DbChildClass : DbParent
    {
           public void  Insert()
            {
                Console.WriteLine("Child inserts");
            }
    }

    Now let’s say after some months of deployment parent class developers without understanding the impact on child classes go and add a new method “Add”. This “Add” method calls the “Insert” method internally (below is the code snippet for the same).

    class DbParent
    {
    public  void Add() // Adds method with out consulting
    {
          this.Insert();
    }

    public virtual void Insert()
    {
                Console.WriteLine("Parent insert");
    }
    }

    Now client programs who invoke the “Add” method by creating child class objects expect that the “Child” class “Insert” implementation should be called.

    DbChildClass o = new DbChildClass();
    o.Add();
    Console.Read();

    But whoaaaa, if you run the below code you will see the parent class “Insert” is called which is not EXPECTED.









    So the next question is what is the proper way of solving this issue?. First thing to my understanding (I can be wrong) there are no standard and common ways of solving the problem.

    One of the thought which goes here is, if the base class is very fragile (will change time to time) then inheritance should not be allowed further. So by marking the classes as “sealed” or the fragile method as “sealed” this problem can be controlled.

    Second way would be avoid calling virtual methods in the parent class in other methods.

    I am myself hunting for proper standard solutions so if you have some better suggestions, please do write down the same in the comments below.

    Also I would like to point out that .NET framework handles fragile parent class issues to a certain extent by itself.  For instance in the below code even though the child class method “HandleNumerics” has been passed an integer value, it is still invoking the “HandleNumerics” with double data type.

    So the framework assumes that the child class method should be given preference rather than parent class.

    class Parent
        {
            public virtual void HandleNumerics(int d)
            {
                Console.WriteLine("Parent numeric ");
            }

        }

        class child : Parent
        {

            public  void  HandleNumerics(double d)
            {
                Console.WriteLine("Child numeric");
            }
            
        }

        class Client
        {

            public static void Main()
            {
                child o = new child();
                int i = 100;
                o.HandleNumerics(i);
            }
        }

    The above code will display “Child Numeric” rather than displaying “Parent Numeric”.

    Below is a simple youtube video which demonstrates the above auto fragile handling methodology by .NET framework. Many c# developers think that this is a defect but it’s actually done “By DESIGN” to solve the “Fragile base class” problem.
      




    Sunday, July 21, 2013

    .NET interview questions with answers: - Build solution VS Rebuild solution VS Clean solution

    I am not aware of a single day in my life when I have not clicked on “Build”, “Rebuild” or “Clean” menu of visual studio. Even though I use it on a daily basis  or sometimes even minute to minute basis when my keyboard was high on coding, I was still not clear what exactly each one of these menus do.  I had very vague idea, but I wanted to be sure about the exact differences between them.

    When I hunted the differences what came out was surprising, below goes a detailed explanation of the same.


    Build solution menu: - This will perform an incremental build. In other words it will only build code files which have changed. If they have not changed those files will not touched.

    Rebuild solution menu: - This will delete all current compiled files (i.e. exe and dll’s) and will build everything from scratch, irrespective if there is code change in the file or not.


    Clean solution menu: - This menu will delete all compiled files (i.e. EXE’s and DLL’s) from “bin” / “obj” directory.

    Now if you read the above 3 points I have discussed you can conclude that:-

    Rebuild = Clean + Build

    So the next question would be If you do a “Rebuild” and if you do “Clean” + “Build” , what is the difference ?.

    The difference is the way the build and clean sequence happens for every project. Let’s say if your solution has two projects “proj1” and “proj2”. If you do a rebuild it will take “proj1” , clean ( delete) the  compiled files for “proj1” and build it. After that it will take the second project “proj2” , clean compiled files for “proj2” and compile “proj2”.

    But if you do a “clean” and build”. It will first delete all compiled files for “proj1” and “proj2” and then it will build “proj1” first followed by “proj2”.

    Below image explains the same in a more visual format.


















    Below is a simple youtube video which demonstrates difference between these entities.



    Big thanks to questpond.com to provide these c# and .NET interview questions with answers videos.






    Saturday, July 13, 2013

    C# and .NET interview questions with answers: - How can we mark a method as deprecated?

    This question is taken from the book .NET interview questions written by Shivprasad Koirala.

    Many times you want to warn developers that some methods or classes should not be used as they are either replaced or going to be replaced with new versions. This is possible by using the “[Obsolete]” attribute.

    In the below class we have a method called as “Method1”. Now let’s say you have created a better improvised version of “Method1” called as “NewMethod1”. You want to send an alert to all your developers who are consuming this class to use “NewMethod1” rather than using “Method1”.

    So you can decorate “Method1” with the “[Obsolete]” attribute as shown in the below code.

    public class Class1
    {
            [Obsolete]
            public void Method1()
            {

            }

            public void NewMethod1()
            {
            }
    }

    Now if any programmer consumes the above class he will get a warning message as shown in the below figure.













    In case you want to show some message to the developers you can pass the message in the “Obsolete” attribute as shown in the below code snippet.

    [Obsolete("Please use NewMethod1")]
    public void Method1()
    {

    }

    If you want to be bit strict and do not developers to use that method, you can pass ‘true” to the “Obsolete” attribute as shown in the below code.

    [Obsolete("Please use NewMethod1",true)]
    public void Method1()
    {

    }

    Now in case developers try to make a call to “Method1”   they will get error and not just a simple warning.













    Also visit our site from more such c# interview question with answers videos.

    Also read this interesting .NET interview question with answer: - What is TPL ( Task parallel library ) ?





       

    Thursday, July 4, 2013

    C# circular dependency interview questions with answers.

    Can you define circular dependency?

    Circular dependency is a situation where “classlibrary1” references “classlibrary2” and “classlibrary2” is trying to reference “classlibrary1”.


    If you ever try to reference class libraries with each other visual studio throws the below exception.


    Can you explain a scenario where circular dependency situation occurs?

    Consider a situation of a 3 layer architecture where the middle layer is consuming data access layer. Below is a simple “Customer” class which belongs to the middle layer and its making call to the data access layer using the “CustomerDal” class.

    For now assume that both these classes are in different c# project.

        public class Customer : ICustomer
        {
            public int CustomerCode { get; set; }
            public string CustomerName { get; set; }
         
            public void Add()
            {
                CustomerDal oDal = new CustomerDal();
                oDal.Add(this.CustomerCode,
                                 this.CustomerName);
            }
        }

    public class CustomerDal
        {
            public void Add(int CustomerCode,
                            string CustomerName)
            {
             
                // database insert code goes over here
            }
        }

    Now if you see the “CustomerDal” class the add method has data passed in variables. It would be great if we can pass the “Customer” object directly. In other words we are looking at a modified version of “CustomerDal” as shown below.In order to achieve the same “CustomerDal” project needs to reference the “Customer” project.

    public class CustomerDal
        {
            public void Add(Customer cust)
            {
                
                // database insert code goes over here
            }
        }


    Now already the “Customer” project is referencing the “CustomerDal” project and if you try to reference the “Customer” project in “CustomerDal” project, it would throw a circular dependency error as shown below.


    How can we overcome the circular dependency problem?

    Circular dependency problem can be overcome by using interfaces or events. So for the above problem we can introduce an interface in between the “MiddleTier” and “Dal”


    So below is the solution. You can create an altogether different c# project and create an interface “ICustomer” as shown in the below code.

    public interface ICustomer
        {
            int CustomerCode { get; set; }
            string CustomerName { get; set; }
        }
    This interface project you will implement in the middle layer project on the  “Customer” class.

    public class Customer : ICustomer
        {
            public int CustomerCode { get; set; }
            public string CustomerName { get; set; }
            
            public void Add()
            {
                CustomerDal oDal = new CustomerDal();
                oDal.Add(this); // passing the object ( polymorphism)
            }

          
        }
    Now in the data access layer project you can reference the interface project and use the interface rather than passing the individual variables in the method.  When the middle layer makes a call to data access layer he will pass “this”. Due to polymorphism the customer object would be automatically type casted to the data access layer in the interface format. Please see the code of “Customer” class where in the “Add” method we have passed “this” object.

    public class CustomerDal
        {
            public void Add(ICustomer cust)
            {
                
                // database insert code goes over here
            }
        }

    Note: - Circular dependency is a sign of bad design and tight coupling. So when you get in to a circular dependency situation rather than fixing it directly by interfaces or events, question yourself why you landed in this situation.