Thursday, 10 October 2013

What is Static Class in C#

A static category is rarely instantiated. The static keyword on a category enforces that a kind not be created with a builder. within the static category, we have a tendency to access members directly on the kind. This eliminates misuse of the category.

To start, there are 2 categories during this program: the Program category, that isn't static, and therefore the Perl category, that is static. you can not produce a brand new instance of Perl employing a builder. attempting to try and do thus leads to a blunder.

Public static members. The bool cooking pan and therefore the technique Blend() ar the general public static members on the Perl sort. Often, public static members ar utilized in helper categories or utility categories throughout a project.

Conceptually, a static category could be a variety of data concealment. you'll use regular categories and static categories within the same means, however the static modifier imposes an additional restriction. The builder is eliminated.

With static categories, we will enforce committal to writing standards and expectations with a minimum of effort. By eliminating the builder or the flexibility to make variables of a kind, we have a tendency to introduce world variables and single-instance fields.


Example:

using System;

class Program
{
    static void Main()
    {
 // Cannot declare a variable of type Perl.
 // This won't blend.
 // Perl perl = new Perl();

 // Program is a regular class so you can create it.
 Program program = new Program();

 // You can call static methods inside a static class.
 Perl._ok = true;
 Perl.Blend();
    }
}

static class Perl
{
    // Cannot declare instance members in a static class!
    // int _test;

    // This is ok.
    public static bool _ok;

    // Can only have static methods in static classes.
    public static void Blend()
    {
 Console.WriteLine("Blended");
    }
}

Output:  Blended

0 comments:

Post a Comment