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.