C# Static classes and static members

Question posted in Computer Software on 10 2009
Rate question difficulty level 0 Votes
Please explain what are static class and class members.
state it main features and give an example of a use of a static class and a static member
 
 
1 Answer
 
Overview
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

Static Classes
A class can be declared static, indicating that it contains only static members.
static class cannot be instantiated.
static class is sealed.
static class cannot contain instance constructors

example for a static class:
static class CompanyInfo
{
    public static string GetCompanyName() { return "CompanyName"; }
    public static string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}

Static Members
A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.

example of static members:
public class Automobile
{
    public static int NumberOfWheels = 4;
    public static int SizeOfGasTank
    {
    get
    {
    return 15;
    }
    }
    public static void Drive() { }
    public static event EventType RunOutOfGas;

    //other non-static fields and properties...
}






10/01/2009
 
 
Add an answer*
 
Email
Location: Glil Yam , Israel
C# Class Static
Now hiring!
Intuit 
---------------------------
---------------------------
---------------------------
---------------------------
---------------------------
---------------------------
---------------------------