Sunday 10 May 2015

Designing With inheritance and composition,Which one you choose?

Inheritance, it is "IS A" relationship. Example, Employee is a person. Employee is base class and person is child class.

Composition is a "HAS A" relationship. Example Bike has a tyres. Bike class has reference of tyres class.

When you used inheritance and when you used composition.
  1. The only way to get maximum advantage of both inheritance and composition in your designs is to ask yourself if you have a permanent is-a relationship. If yes then use inheritance. If not, use composition.  
    • For Example. An question to ask yourself when you think you have an is-a relationship is whether that is-a relationship will be constant throughout the lifetime of the application. For example, you might think that an Employee is-a Person, when really Employee represents a role that a Person. What if the person becomes unemployed? What if the person is both an Employee and a Supervisor? Such impermanent is-a relationships should usually be modelled with composition.
    • And an Apple likely is-a Fruit, so I would be inclined to use inheritance. here no change to change is a relationship.
  2. As thinks for performance Inheritance is more costly compare to Composition. Every time you create object of child class before that parent constructor is called and memory is allocated for parent variable. Also you can not change behaviour of base class as run time.
  3. when you have need of the polymorphism then Polymorphism is achieved by inheritance.

Thursday 26 February 2015

Find MAX, MIN ,Second MAX and Second MIN value in C# LINQ

using System.IO;
using System;
using System.Linq;

class Program
{
    static void Main()
    {
       var a=new int[6]{1,10,5,7,4,3};
        int max1=a.Max();   //MAX
        int max2=a.Min();    //MIN
        int max3=a.OrderByDescending(z=>z).Skip(1).First();
                                         //Second MAX
        int max4=a.OrderBy(z=>z).Skip(1).First();
                                        //Second MIN
       
        Console.WriteLine("{0}",max1);
        Console.WriteLine("{0}",max2);
        Console.WriteLine("{0}",max3);
        Console.WriteLine("{0}",max4);
        Console.WriteLine("Hello, World!");
    }
}

Output:-
10
1
7
3