Showing posts with label Object Oriented Programming. Show all posts
Showing posts with label Object Oriented Programming. Show all posts

Monday, 26 November 2012

what is Constructor overloading ?


Yes, till now we know that method overloading. Now we will see constructor overloading.

Points Keep in Mind :
Execution of derived classes starts from base class constructor.******maindatory
Based on signature of the constructor their apporiate parent constructor will be executed
(other wise parent default constructorà parameter less Ex: People() executes).

As we want to create a parameterized constructor we must create parameterless constructor also.


class People
    {
        public string Name{get;set;}
        public int Age {get;set;}
        public People ()
       {
            this.Name=Name;
            this.Age=Age;
               }
       public People (string name)
               {
            this.Name=name;
               }
       public People(int age)
       {
           this.Age = age;
       }
       public People (int age,string name)
               {
           this.Age = age;
           this.Name=name;         
               }
       public People(string name,int age)
       {          
           this.Name = name;
           this.Age = age;
       }        
    }
    class Developer : People
    {
        public Developer():base("kasi",41)   //  base --> people provides 4 signatures.
        {                                                     // People(string name,int age)
            Console.WriteLine("Developer name is :"+Name);
            Console.WriteLine("Developer Age is: " + Age);
        }     
   public Developer(int age)           
 {
          // executes People() constructor as default.        
            Console.WriteLine("Developer is :" + age);
 }             
    }
    class Designer : People
    {
          public Designer(): base(42, "Ravi")  //  People (int age,string name)
        {
            Console.WriteLine("Designer name is:" + Name);
            Console.WriteLine("Designer age is:" + Age);
        }
        public Designer(int age):base(42)  
              // executes People(int age) constructor here.
        {
            Console.WriteLine("Designer age is :" + Age);
        }   
    }

Thursday, 22 November 2012

Design Principles : SOLID


Design Principals:
Yes, we know Design Patterns for coding level to resolve the problems while building the applications. as well Design Principals for building types(classes, Interfaces..more efficiently).

These are SOLID Prinicals:

1.      Single Responsibility Principle
2.      Open – Closed Principle
3.      Liscov Substitution Principle
4.      Interface Segregation Principle
5.      Dependency Inversion Principle


Single Responsibility Principle :

Which partitioning the types as per their responabilities.  
To avoid --à tightly coupled types. making the splitting the types as per their responabilities.
We can increase the reusability.

In .net
SqlConnection is responablity is to connect to Sql-server and which contains  Connection relavent
Members. Like connectiontimeout, WorkingStationId……ect.
this type is designed for connection oriented things only. As which reused in another types like

SqlConnection--SqlCommand,SqlDataAdapter types so the same code is reuseable here.

SqlConnection is independent implementation and reused by other types also.

Open – Closed Principle:


Software Entities (Classes, Modules, Functions, etc.) should be open for extension but closed for modifications.
Achived through : Abstraction and Polymorphism.
Abstraction: Abstraction helps us in making our code more extensible while polymorphism helps us in making our code close.
Ex:
DbDataAdapter-à IDataAdapter
public interface IDataAdapter
{
int Fill(DataSet dataSet);  // by default : virtual, public
}
Based on the type of DataAdapteràSqlDataAdapter,OracleDataAdapter…are implements DbDataAdapter.
Base on the type of DataAdapter(SqlDataAdapter,OracleDatapter..)
DbDataAdapter provides the underlaing implementation as per the DataAdapter.
Here
public interface IDataAdapter
{
int Fill(DataSet dataSet);  // by default : virtual, public ,abstract *****
}
Which
Class DbDataAdapter : DataAdapter
{
public override int Fill(DataSet dataSet);
}
SqlDataAdapter : DbDataAdapter
OracleDataAdapter : DbDataAdapter

Here Open for Extenbility-à by declaring as virtual(bydefault interface members).
And close in derived types(SqlDataAdapter,OracleDataAdapter…ect) in dervied types using Override Funcationality.
through Polymorphism(Interface based)this override funcationality is achived.

And which makes colsed from Modification using Polymorphism.

Liskov Substitution Principle:

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. (Polymorphism; important part highlighted)

public abstract class DbCommand
protected abstract DbConnection DbConnection { get; set; } //generic
sealed class SqlCommand : DbCommand,
   protected override DbConnection DbConnection { get; set; }
sealed class OracleCommand : DbCommand
protected override DbConnection DbConnection { get; set; }
All abstract members are by default Virtual so we can override in dervide typles like above.

Interface Segregation Principle:

Clients should not be forced to depend upon interfaces that they do not use.
Means -à Every interface is specific purpose. And their derived types specific members only should be defined in that interface.
So define the member relavent to a specific type with relavent members.
EX: IEnumerable---only  Movenext(), Reset(), Current ----relavent to IEnumarable collections.

Dependency Inversion Principle:

to avoid tightly copuled programming between types.

https://csharpsimplified.wordpress.com/2010/10/01/design-principle/

https://mlichtenberg.wordpress.com/category/software-development/


Thursday, 18 October 2012

Lamda Expression simplifies Delegate signatures?

yes, lamda expressions simplifies the code more cleaner, simplifed manner


Delegates are also types, which are predefined , useful to hold the reference of another method.
Delegate declaration.
Delegate defincation.
Delegate innovation.
Ex:
Delegate is a keyword to define a delegate.
delegate int maticalOperation(int x); // Here maticalOperation is Name of the delegate.
maticalOperation add;
// define an delegate type variable [means event] which holds/referes the methods which has same signature like Add delegate.
int sum(int x)
{
            return x+10;
}
So delegate(maticalOperation) can hold/refer the sum operation why because sum operation/method has the same signature of maticalopration signature.
Multicate delegate.
A single delegate can points multiple method references using multicast delegates. In .net most of the delegates are multicast delegates.
Using the signatures
+= and -= operators.
Event based delegates.
Delegates and events are pre-defined in .net we can also define delegates and events for our user defined controls.
For every event we have pre-defined event.// event is a keyword.
Click(object sender, EventArgs e) ---delegate
Button_click(object sender, EventArgs e);---reference of above click delegate.
…like so many delegetes we have in .net.
Delegates are simplifed:
    delegate int maticalOperation(int x);
           maticalOperation m = sum;
            int value=message(5);
            Console.Write(value);
        static int sum(int a)
        {
            return a + a;           
        }
Referenced Method(sum) return type should be delegate(maticalOperation).
Like in lamda Expressions also. Return type should a generic delegate.
Example: Var is not acceptable as return type.
Fun<>,Action<>,predicate<> for developer compatability//instead of created by developer.
Like.

Action<int,int,int> message = (int a,int b,int c)=> //or delegate(int a,int b,int c)
{
  Console.WriteLine("The addition of three number is " + (a + b + c));
};
message(5, 6,71);
and => expression return type must be a generic delegate.
Delegates are simplified with the help of anamous methods and lamda expressions.
// linq makes dynamic memory allocation.
We can call the delegate in asynchronsly also using BeginInvoke method.
Invoke is synchronus method.
Lamda expressions are coupled with generic delegates.
So lamda expressions are tightly coupled with delegates[generic delegates].
So lamda-expressions return type is a delegate(generic delegate).
As well these delegate are can work with any types……..int,string,employee,..ect.
So finally delegates and lamda expressions are developer prospective to make programming more flixable.
Demo1:
delegate int maticalOperation(int x);
maticalOperation m = sum;
int value=m(4);
Console.Write(value);
static int sum(int a)
{
            return a + a;           
}
Here we create the maticalOperation delegate instead of this. We have to use existing delegate is Fun<> which will retun the value like below
Demo 2:
   Func<int, int, int> value1 = delegate(int a, int b)
            {
                return a * b;
            };
            Console.WriteLine("{0}", value1(5, 6));
   
Instead of writing keyword delegate we have simplify this like
Demo 3:
  Func<int, int, int> value1 = (int a, int b)=>
  {
                return a * b;
  };
 Console.WriteLine("{0}", value1(5, 6));   

prefined delegate is : Func<T,T,TResult>()
Demo 4:
   Func<int, int, int> value1 = (int a, int b) => (a * b);
    Console.WriteLine("{0}", value1(5, 6));  

Incase of single variable not require any parathisis like above.
Simplified like this. Here Int type for retrun type is Int***
Ex:
   Func<int,int> value2= a => a+10;
   Console.WriteLine("{0}", value2(4));   

as well as

lamda expression prepares(returns) a proper expression tree as per Lamda Expression of Right side

Expression<delegate> res=x=>x*x;

like
                     delegate int maticalOperation(int x);

            Console.WriteLine(" general way   ");

            maticalOperation myDelegate = x => x * x;
            int j = myDelegate(5);
            Console.WriteLine(j.ToString());

            Console.WriteLine(" 1st way ");

            Expression<maticalOperation> result = a => a * a;
            Console.WriteLine(result.Compile()(4));

            Console.WriteLine(" 2nd way  ");
            Expression<Func<int, int>> second = a => a * a;
            Console.WriteLine(second.Compile()(4));

so finally i want to say: delegates Signatures and return types should match.



Note: For every lamda expression few pre-defined delegates in dotnet framework. like

Func<T>(), Func<T,TResult>().Func<T,T,TResult>()...delegates available. in dotnet framework.




As well delegates usages:

Asynchronus programming.
Callback mechinamsms.
for holding the reference of another method.

Reference:

http://www.dotnetfunda.com/articles/article1956-func-and-action-delegates.aspx


Saturday, 23 June 2012

How to Initialize class to another class as Parameter to Constructor?

Yes, we can make class intialization to another class as a parameter.
means:  Class1 obj=new Class1{ new Class2()};  ----yes;

 class Book
    {            
        public Book(Publications obj)               // one
        {
            this.Publish = obj;
        }
        public Book(Book obj, Publications pobj)       //  two
        {
            this.Author = obj.Author;
            this.Publish = pobj;
        }
        public string Author { get; set; }
        public Publications Publish { get; set; }
    }
    class Publications
    {
        public string Publish { get; set; }
    }
 class InitailizataionofTwoClasses
    {
        static void Main()
        {                                      
          // 1st constructor 
            Book bo = new Book(new Publications { Publish = "Dream Tech" });         // one
            Console.Write(bo.Publish.Publish);
        
             // 2nd constructor
            Book bobj = new Book(new Publications { Publish = "BPB Publications" });  // two
            Console.Write(bobj.Publish.Publish);
            bobj.Author = "Propercode";
            Console.Write(bobj.Author);  // No author Here
    
        }
    }

Monday, 4 June 2012

How many ways we can Destory the objects in .net?


1.implictly resource cleanup (Destructors) : under the control of Garbage collector
2.Explict resource cleanup(IDispose-Dispose() method) : under the control of Developer

Implict Resource Clenup

What is the role of Garbage Collector in Disposing objects?

Yes, Garbage collector also dispose the objects implictly with the help of finallse() method of object(GC) but only managed objects and with the help of unreachable/unused objects mechanism of garbage collector. Implict Resource Cleanup.

We can define destrutor for any type by defining the Destructors.then Garbage Collector implictly generates try and finally blocks (like using block) and calls the Finialize() method of object.

class FinializeDemo
    {
        ~FinializeDemo()
        {
            // generates try and finally block by CLR.
        }

        static void Main()
        {
            Console.Write("welcomdssss");

       
        }
    }
Above destructor(~FinializeDemo()) automatically calls the Finialize method of object automatically..


Object destruction is under the control of Garbage Collector(not control by developers).

Garbage Collector is a static class which has Collect method to Developer to Forcebly destory the objects from Various Generations of GC mechanisum.

Like

        ~FinializeDemo()
        {
           GC.collect() ;                     // various generations// Gen1/2/3 and conditions
        }

How to use Expliect Resource Cleanup for objects Memory allocation?

Yes, to perform Explict Resource Cleanup is done with the types which impliments IDispose interface.

Ex :
 
Explict Resource Cleanup is done with Disposing objects expliectly. By calling Dispose method of IDispose Interface.

Static void Main()
{
            sqlConnection con=new Sqlconnection();
            con.Dispose();
}
Which call the Dispose method of sqlconnection for freeup the resource. Instead of calling Destructor of sqlconnection.
Dbconnection implements the IDispose method.

Inside Dispose

  public void Dispose()
{
      Dispose(true);
     GC.SuppressFinalize(this); // it won't call the destractor of sqlconnection class
}
protected  override void Dispose(bool Diposing)
 {
     if (!IsDisposed)
      {
        if (Diposing)
         {
           con.Dispose();
//Clean Up managed resources
         }
         else
         {
                    // not disposed till now impliectly                                     
         }
        /Clean up unmanaged resources
       }
    IsDisposed = true;       
         
 }

How to use impliectly Resource Cleanup for objects Memory allocation?

Which is done by calling Finialize method of destructor. If we not write desturctor for our type. Base class Object of Finialize() is called implictly.

Class SampleDemo
{

               static void Main()
        {
          FinializeDemo   fobj = new FinializeDemo();

              }

}

Class FinializeDemo()
{
               ~FinializeDemo()
        {
            Dispose(false);
        }
protected  override void Dispose(bool Diposing)
 {
     if (!IsDisposed)
      {
        if (Diposing)
         {
           con.Dispose();
//Clean Up managed resources
         }
         else
         {
                    // not disposed till now impliectly                                     
         }
   }
    IsDisposed = true;       
         
 }

}