Monday, 19 August 2013

What is Static Class in C#


Static Class in C#: Static classes are used to define methods that can be accessed without creating an instance of the class. The static keyword is used to define a class and its member is static .You can use the class name to access the members of a static class. Some important features of static class as follows.
  •    It can contain only static members
  •    It cannot be instantiated
  •    It cannot have instance constructors, which  are constructors that are  used to  create and initialize member variable of an instance
  •   It cannot be inherited
 When you declare a static class, you must remember that static classes cannot be instantiated. Declaring a static class is similar to creating a class that contains only static member and private constructor. Static method cannot call non-static method directly. To call a non-static method from a static method, you need to create an object of the class in which the non static method is defined. Similarly, non -static methods cannot call static method directly .To call a static method from a non-static method, you need to use the name of class in which the static method is defined. A static member can exist inside a static or a non-static class.

 Exmaple of Static Class:

 First we take a Windows Forms Application and take one button for result on this Form1………………………

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

//create static class with two static function………………..

static class AreaVolume
{
static double length,width,height;

// create static method for Rectangle Area...................

public static double RectangleArea(double l,double w)
{
length=l;
width=w;
return(l*w);

}
// create static method for Cobiod Volume...................

public static void CubiodVolume(double l,double w,double h)
{
length=l;
width=w;
height=h;
MessageBox.Show("Volume of Cubiod is = "+(l*w*h));
}
}

private void btnresult_Click(object sender, EventArgs e)
{
// for Rectangle Area...................
double area;
area= AreaVolume.RectangleArea(20.23, 11.89);
MessageBox.Show("Area of Rectangle is  =" + area);

//for Cubiod Volume............................
AreaVolume.CubiodVolume(25.00, 20.23, 12.44);

}

}
}

1 comments:

  1. very helpful Example
    Sir Please Provide interview Question Shortly.

    ReplyDelete