Thursday, 22 August 2013

Extension Method in C#

Extension Method in C#: Extension methods, introduced in C# 2008, allow you to extend a class without deriving a new class from that class. The behavior of extension methods is similar to that of static methods and they are also defined with static keyword. An extension method can be defined in a static class. The first parameter of extension method is of type that the extension method extends and its is preceded by the this keyword as show in the following code ………………………..
Example with Extension Method…………………………………………
//execute  this query in sql Server 2008…………………..
create database test
use test
create table extenstion1(id nvarchar(50),name nvarchar(50),company nvarchar(50),age int)

First we create class which name is MyClass with extension method…………

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Extensions_Methods_Exp
{

static class MyClass
{

//Extensions_Methods for total of Array Element....

public static int total(this int[] ar)
{
int t = 0;
foreach (int a in ar)
t += a;
return t;
}

  //Extensions_Methods for save data in Database

public static string InsertinDataBase(this string a, string b, int c)
{

Random rr = new Random();
string id = a.ToString().Substring(0, 2).ToUpper() + rr.Next(1000, 9999);
SqlConnection con = new SqlConnection(@"Data Source=KUSH-PC\KUSH;Initial Catalog=test;Integrated Security=True");
SqlCommand cmd = new SqlCommand("insert into extenstion values('"+id+"','" + a + "','" + b + "','" + Convert.ToInt32(c) + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return id;
}
}

}

Code for Windows From Button to Save Data Database and Total of Array Element………….

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 Extensions_Methods_Exp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //code for total of each each element of aarray with Extensions_Method
        private void btngetresult_Click(object sender, EventArgs e)
        {
            int[] a= { 1,2,3,4,5,6,7,8,9 };
            int result = a.total();
            MessageBox.Show("Total of Array= " + result);

        }
        //code for save the data from From Control in Database with Extensions_Method
        private void btnSave_Click(object sender, EventArgs e)
        {
            string a = txtname.Text;
            string b = txtcompany.Text;
            int c = Convert.ToInt32(txtage.Text);
            string k = a.InsertinDataBase(b, c);
            MessageBox.Show("your Data Saved and Your Id is =" + k);
        }

     }
}

0 comments:

Post a Comment