Monday, February 29, 2016

What is abstract class in c#?



An abstract class is an incomplete class that cannot be instantiated, it only allow other class to inherit from it.an abstract method must be implemented in child class by using the override keyword.

Features of abstract class: 

Abstract class have constant and fields
It can be implement a property
It can have constructor and destructors
It cannot support multiple inheritance
The example of the abstract class is given below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
    public abstract class Class1
    {
        protected string s;
        public abstract void show();
    }
    public class class2 : Class1
    {
        public override void show()
        {
            s = "Dot Net Darpan";
            MessageBox.Show(s);
         
        }
    }
}


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            class2 obj = new class2();
            obj.show();
        }
    }
}
 
Output:  

 

Friday, February 26, 2016

What is inheritance in C#?



Inheritance is one of the fundamental object oriented programming language concept that allow the creation of hierarchical classifications.in C# programming the, a class that is inherited is called base class. In simple words the child class inherit variables, methods, properties and indexers of the parent class by using the “:” character. The main advantage inheritance is to re-usability of code.

The example of the inheritance is given below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace inheritance
{
    public class Class1
    {
        public void xyz()
        {
            MessageBox.Show("Hello");
        }
    }

    public class pqr : Class1
    {
        public void xyz1()
        {
            MessageBox.Show("Hi");
        }
    }
}

 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace inheritance
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            pqr obj = new pqr();
            obj.xyz();
            obj.xyz1();
        }
    }
}
 

output: Hello
Hi

In which SCENARIOS we use Abstract Class

For many  people  including me , It is very difficult to answer when to use "Abstract Class" , I had already tried  to find the answer for this from many sites.

Here I share my experiences with this question,  and I am sure you will definitely  be able to answer this question after reading this article.

 "Abstract Class"

Here I explain in which "SCENARIOS" you can use "Abstract Class"  Lets take an example from our Microsoft core library

Suppose I have a class "SqlConnection "  and when you go to its meta definition

    public sealed class SqlConnection : DbConnection, ICloneable
    {
        // Summary:
        //     Initializes a new instance of the System.Data.SqlClient.SqlConnection class.
        public SqlConnection();
        //
        // Summary:
        //     Initializes a new instance of the System.Data.SqlClient.SqlConnection class
        //     when given a string that contains the connection string.
        //
        // Parameters:
        //   connectionString:
        //     The connection used to open the SQL Server database.
        public SqlConnection(string connectionString);
 
        // Summary:
        //     Gets or sets the string used to open a SQL Server database.
        //
        // Returns:
        //     The connection string that includes the source database name, and other parameters
        //     needed to establish the initial connection. The default value is an empty
        //     string.
        //
        // Exceptions:
        //   System.ArgumentException:
        //     An invalid connection string argument has been supplied, or a required connection
        //     string argument has not been supplied.
        [Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
        [RefreshProperties(RefreshProperties.All)]
        [ResCategory("DataCategory_Data")]
        [DefaultValue("")]
        [ResDescription("SqlConnection_ConnectionString")]
        [RecommendedAsConfigurable(true)]
        [SettingsBindable(true)]
        public override string ConnectionString { get; set; }
//many more things............................................
}

Here this "SqlConnection" class  inherited one abstract class name "DbConnection" class  lets see what this abstract class contain
 
public abstract class DbConnection : Component, IDbConnection, IDisposable
    {
        // Summary:
        //     Initializes a new instance of the System.Data.Common.DbConnection class.
        protected DbConnection();
 
        // Summary:
        //     Gets or sets the string used to open the connection.
        //
        // Returns:
        //     The connection string used to establish the initial connection. The exact
        //     contents of the connection string depend on the specific data source for
        //     this connection. The default value is an empty string.
        [RefreshProperties(RefreshProperties.All)]
        [ResCategory("DataCategory_Data")]
        [DefaultValue("")]
        [SettingsBindable(true)]
        [RecommendedAsConfigurable(true)]
        public abstract string ConnectionString { get; set; }
        //
        // Summary:
        //     Gets the time to wait while establishing a connection before terminating
        //     the attempt and generating an error.
        //
        // Returns:
        //     The time (in seconds) to wait for a connection to open. The default value
        //     is determined by the specific type of connection that you are using.
        [ResCategory("DataCategory_Data")]
        public virtual int ConnectionTimeout { get; }
        //
        // Summary:
        //     Gets the name of the current database after a connection is opened, or the
        //     database name specified in the connection string before the connection is
        //     opened.
        //
        // Returns:
        //     The name of the current database or the name of the database to be used after
        //     a connection is opened. The default value is an empty string.
        [ResCategory("DataCategory_Data")]
        public abstract string Database { get; }
        //
        // Summary:
        //     Gets the name of the database server to which to connect.
        //
        // Returns:
        //     The name of the database server to which to connect. The default value is
        //     an empty string.
        [ResCategory("DataCategory_Data")]
        public abstract string DataSource { get; }
//and many more things..................................................................................
 }

In this abstract class you can see a property " public abstract string ConnectionString { get; set; }" is declared, and it is override by "public override string ConnectionString { get; set; }"SqlConnection " class.   when we inherited "DbConnection "   abstract class it is necessary to implement abstract string "ConnectionString ". The point is clear when ever you use this class a wide range all the inhered class must implemented this property.

Now , My intension is here to show you Microsoft working style of abstract class. Lets talk about it in simple term.
  •  When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
     
  • The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
     
  • If you are thinking about multiple version of your component then create abstract class. Abstract classes provide a simple and easy way to version your component. By updating base class, all the inheriting classes are automatically updated.
Questions related to Abstract Class

Question 1 What is an Abstract Class?
Answer:  According to Code Project "Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'."

Question 2  Does Abstract class have constructor in c#
Answer:  Yes

Question 3  Then, why we do not create object of Abstract Class?
Answer:  When you want to instantiate data in the abstract class. One important reason is due to the fact there's an implicit call to the base constructor prior to the derived constructor execution. Keep in mind that unlike interfaces, abstract classes do contain implementation. That implementation may require field initialization or other instance members. Note the following example and the output:

Souce:stackoverflow

    abstract class Animal
    {
        public string DefaultMessage { get; set; }
 
        public Animal()
        {
            Console.WriteLine("Animal constructor called");
            DefaultMessage = "Default Speak";
        }
        public virtual void Speak()
        {
            Console.WriteLine(DefaultMessage);
        }
    }
 
    class Dog : Animal
    {
        public Dog()
            : base()//base() redundant.  There's an implicit call to base here.
        {
            Console.WriteLine("Dog constructor called");
        }
        public override void Speak()
        {
            Console.WriteLine("Custom Speak");//append new behavior
            base.Speak();//Re-use base behavior too
        }
    }

Although we cannot directly construct an Animal with new, the constructor is implicitly called when we construct a Dog.

OUTPUT:

Animal constructor called
Dog constructor called
Custom Speak
Default Speak


Question 4  It is necessary abstract classes have all the methods abstract?
Answer:  No. An abstract class can have concrete methods too.

Question 5  If c# allow to declare all method abstract then why we use Interface?
Answer:  Answer this question in single line,  Class can implement several interfaces but only one abstract class and you may required  a class inherited server classes  (means abstract "class+Interface") in real word   scenarios. ( as you see above code of Microsoft  "SqlConnection" class.

Question 6  In c#, Can we work with normal classes as Abstract Class do?
Answer: Abstract class is deigned to create non abstract and abstract fields method and properties , which can share by more than one classes , and can be override by its inherited classes and if we create a non abstract class then we will create the object of that class. So a class is incomplete, we didn't allow to create the object of that class.

Question 7  Can we use a sealed keyword with an abstract class?
Answer: No. Sealed classes cannot be inherited while an abstract class is meant to be inherited.

Monday, February 22, 2016

Cascade SQL example

You all know, we can't delete record or records of master table if it references to child table because you know primary and foreign key rule, if you did't know about these rule you call see my last article  in given below link

Referential Integrity Constraint

If you know these rules then I think you faced the given below "Note" problems

Note
  •  We can’t delete or update any record from the Master table if at all it has corresponding child records in the child table.
  •  Because by default we can’t delete a record from the Master table when it has corresponding child records. To delete them we are provided with cascading rules.
Cascading Rules :

Cascading rules are of 2 types, they are: -

(1) Delete Rules: -

  • On Delete No Action (Default)
  • On Delete cascade
  • On Delete Set Null
  • On Delete Set Default
     
(2) Update Rules: -
  • On Update No Action (Default)
  • On Update cascade
  • On Update Set Null
  • On Update Set Default
All these rules has to be applied while creating the child tables. We can choose one rule from each set & apply on the child tables.

On Delete No Action and On Update No Action:

These are the default rule that gets applied on the child table. When these are applied we can’t delete or update a record in a Master table if at all it has corresponding child records.

On Delete Cascade and On Update Cascade:

If these rules are applied on the child table it will allow us to delete a record from the Master table, so that corresponding child records get deleted as well as allow us to update a record in the Master table, so that the corresponding child records foreign key also gets updated.


CREATE TABLE [dbo].[Employee](
     [EmpID] [int] IDENTITY(1,1) NOT NULL primary key,
     [EmpName] [varchar](150) NOT NULL,
     [RefDeptID] [int] NULL,
     CONSTRAINT [dno_fk] FOREIGN KEY([RefDeptID]) REFERENCES Department ([DeptID])
    ON UPDATE CASCADE ON DELETE CASCADE)

On Delete Set Null and On Update Set Null:

If these rules are applied while creating the child tables it will allow us to delete as well as update a record from the master table so that the corresponding child records foreign key value changes to NULL provides the column is not imposed with a not NULL constraint on it. It is newly added in SQL Server.

CREATE TABLE [dbo].[Employee](
     [EmpID] [int] IDENTITY(1,1) NOT NULL primary key,
     [EmpName] [varchar](150) NOT NULL,
     [RefDeptID] [int] NULL,
     CONSTRAINT [dno_fk] FOREIGN KEY([RefDeptID]) REFERENCES Department ([DeptID])
   On Delete Set Null On Update Set Null)

On Delete Set Default and On Update Set Default:

If these rules are applied on the child table while creating it will allow us to delete as well as update a record in a master table do that changes to the default value specified for the foreign key column. If no default value is specified Null is taken as default which is equal to the On Delete Set Null.

CREATE TABLE [dbo].[Employee](
     [EmpID] [int] IDENTITY(1,1) NOT NULL primary key,
     [EmpName] [varchar](150) NOT NULL,
     [RefDeptID] [int] NULL,
     CONSTRAINT [dno_fk] FOREIGN KEY([RefDeptID]) REFERENCES Department ([DeptID])
   On Delete Set Default On Update Set Default)