Friday, February 26, 2016

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)

Saturday, February 20, 2016

What is interface in C# with example?



Interface is like a class but has no implementation it contains only declaration methods, properties and indexer .It is declared by the interface keywords in place of class.

The example of the interface is given below:

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

namespace WindowsFormsApplication5
{
    interface A
    {
        void show1();
    }
    interface B
    {
        void show2();
    }
    public class classC:A,B
    {
        public void show1()
        {
            MessageBox.Show("hi");
        }
        public void show2()
        {
            MessageBox.Show("hello");
        }
    }
}

Code on button click:
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 WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            classC obj = new classC();
            obj.show1();
            obj.show2();
        }
    }
}
 
Output:
hi
hello

Wednesday, February 17, 2016

What is structure in c#?



In C sharp Structure are the light weight classes and also value type, it contains fields, methods, constants, constructor, indexer.
Some key points of structure are given below:
Structure does not inherited
Not protected modifier is used
We cannot create default constructor in structure
With new keyword and without new structure is used while in class new is necessary
Instance field initializer is not possible in the structure
The example of the structure is given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    struct mystruct
    {
       public  int x, y;
        public mystruct(int i, int j)
        {
            x = i;
            y = j;
        }
    }
}


Code on Button click:
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            mystruct obj = new mystruct();
            obj.x = 1;
            obj.y = 2;
            MessageBox.Show(obj.x.ToString());
            MessageBox.Show(obj.y.ToString());
           
        }
    }
}

Output :
1
2