Static Variables
|
Introduction
|
Imagine you create a class called Book. To access it in
the Main() method, you can declare its variable, as we have done so
far. A variable you have declared of a class is also called an instance of
the class. In the same way, you can declare various instances of the same
class as necessary:
|
Each one of these instances gives you access to the
members of the class but each instance holds the particular values of the
members of its instance. Consider the results of the following program:
using System; public class Book { public string title; public string author; public short yearPublished; public int numberOfPages; public char coverType; } public class Exercise { static int Main() { var first = new Book(); first.title = "Psychology and Human Evolution"; first.author = "Jeannot Lamm"; first.yearPublished = 1996; first.numberOfPages = 872; first.coverType = 'H'; Console.WriteLine("Book Characteristics"); Console.Write("Title: "); Console.WriteLine(first.title); Console.Write("Author: "); Console.WriteLine(first.author); Console.Write("Year: "); Console.WriteLine(first.yearPublished); Console.Write("Pages: "); Console.WriteLine(first.numberOfPages); Console.Write("Cover: "); Console.WriteLine(first.coverType); var second = new Book(); second.title = "C# First Step"; second.author = "Alexandra Nyango"; second.yearPublished = 2004; second.numberOfPages = 604; second.coverType = 'P'; Console.WriteLine("Book Characteristics"); Console.Write("Title: "); Console.WriteLine(second.title); Console.Write("Author: "); Console.WriteLine(second.author); Console.Write("Year: "); Console.WriteLine(second.yearPublished); Console.Write("Pages: "); Console.WriteLine(second.numberOfPages); Console.Write("Cover: "); Console.WriteLine(second.coverType); return 0; } }
This would produce:
Book Characteristics Title: Psychology and Human Evolution Author: Jeannot Lamm Year: 1996 Pages: 872 Cover: H Book Characteristics Title: C# First Step Author: Alexandra Nyango Year: 2004 Pages: 604 Cover: P
All of the member variables and methods of classes we
have used so far are referred to as instance members because, in
order to access them, you must have an instance of a class declared in
another class in which you want to access them.
In your application, you can
declare a variable and refer to it regardless of which instance of an object
you are using. Such a variable is called static.
A Static Variable
|
To declare a member variable of a class as static, type
the static keyword on its left. Here is an example:
public class Book
{
static string title;
}
In the same way, you can declare as many static
variables as you want. As we saw in previous lessons, you can control access
to a field using a modifier. If you apply the modifier, the static keyword
can be written before or after it, as long as it appears before the data
type. Here are examples:
public class Book { public static string title; static public string author; }
To access a static variable, you must "qualify" where
you want to use it. Qualifying a member means you must specify its class.
Here is an example:
using System; public class Book { public static string title; static public string author; public short yearPublished; public int pages; public char coverType; } public class Exercise { static int Main() { var first = new Book(); Book.title = "Psychology and Human Evolution"; Book.author = "Jeannot Lamm"; first.yearPublished = 1996; first.pages = 872; first.coverType = 'H'; Console.WriteLine("Book Characteristics"); Console.Write("Title: "); Console.WriteLine(Book.title); Console.Write("Author: "); Console.WriteLine(Book.author); Console.Write("Year: "); Console.WriteLine(first.yearPublished); Console.Write("Pages: "); Console.WriteLine(first.Pages); Console.Write("Cover: "); Console.WriteLine(first.coverType); var second = new Book(); Book.title = "C# First Step"; Book.author = "Alexandra Nyango"; second.yearPublished = 2004; second.pages = 604; second.coverType = 'P'; Console.WriteLine("Book Characteristics"); Console.Write("Title: "); Console.WriteLine(Book.title); Console.Write("Author: "); Console.WriteLine(Book.author); Console.Write("Year: "); Console.WriteLine(second.yearPublished); Console.Write("Pages: "); Console.WriteLine(second.Pages); Console.Write("Cover: "); Console.WriteLine(second.coverType); return 0; } }
Notice that when a variable has been declared as static,
you don't need an instance of the class to access that member variable
outside of the class. Based on this, if you declare all members of a class
as static, you don't need to declare a variable of their class in order to
access them. In the following example, the Title and Author fields of the
Book class are accessed from the Exercise class without using an instance of
the Book class:
using System; public class Book { public static string title; static public string author; } public class Exercise { static void Main() { Book.title = "Psychology and Human Evolution"; Book.author = "Jeannot Lamm"; Console.WriteLine("Book Characteristics"); Console.WriteLine("Title: "); Console.WriteLine(Book.title); Console.WriteLine("Author: "); Console.WriteLine(Book.author); Book.title = "C# First Step"; Book.author = "Alexandra Miles"; Console.WriteLine("Book Characteristics"); Console.WriteLine("Title: "); Console.WriteLine(Book.title); Console.WriteLine("Author: "); Console.WriteLine(Book.author); Console.ReadKey(); } }
In the same way, you can declare a combination of static
and non-static variables as you see fit. You just have to remember that, to
access a static variable, you don't create an instance of the class. To
access a non-static variable, you must declare a variable for the class.
Introduction
|
Like a member variable, a method of a class can be
defined as static. Such a method can access any member of the class but it
depends on how the member variable was declared. Remember that you can have
static or non-static members of a class.
Creating a Static Method
|
To define a method as static, type the static
keyword to its left. Here is an example:
public class Book
{
static void CreateBook()
{
}
}
A static method can also use an access modifier. You can
write the access modifier before or after the static
keyword. Here is an example:
using System; public class Book { private static string title; static private string author; private static int pages; static private double price; static public void CreateBook() { title = "Psychology and Human Evolution"; author = "Jeannot Lamm"; pages = 472; price = 24.95; } internal static void ShowBook() { Console.WriteLine("Book Characteristics"); Console.Write("Title: "); Console.WriteLine(Book.title); Console.Write("Author: "); Console.WriteLine(Book.author); Console.Write("Pages: "); Console.WriteLine(pages); Console.Write("Price: "); Console.WriteLine(price); } public static int Main() { return 0; } }
As mentioned for a static field, using a static method
depends on where it is being accessed. To access a static member from a
static method of the same class, you can can just use the name of the static
member. Here are examples:
using System; public class Book { static string title; static string author; static int pages; static double price; static void CreateBook() { title = "Psychology and Human Evolution"; author = "Jeannot Lamm"; pages = 472; price = 24.95; } static void ShowBook() { Console.WriteLine("Book Characteristics"); Console.Write("Title: "); Console.WriteLine(Book.title); Console.Write("Author: "); Console.WriteLine(Book.author); Console.Write("Pages: "); Console.WriteLine(pages); Console.Write("Price: "); Console.WriteLine(price); } public static int Main() { CreateBook(); ShowBook(); return 0; } }
This would produce:
Book Characteristics Title: Psychology and Human Evolution Author: Jeannot Lamm Pages: 472 Price: 24.95
You can also type the name of the class, followed by a
period, followed by the member. Here are examples:
using System; public class Book { . . . No Change static void CreateBook() { . . . No Change } static void ShowBook() { . . . No Change } public static int Main() { Book.CreateBook(); Book.ShowBook(); return 0; } }
To access a static member outside of its class, type the
name of the class, followed by a period, followed by the member. Here are
examples:
using System;
public class Book
{
. . . No Change
static public void CreateBook()
{
. . . No Change
}
internal static void ShowBook()
{
. . . No Change
}
}
public class Exercise
{
public static int Main()
{
Book.CreateBook();
Book.ShowBook();
return 0;
}
}
Introduction
|
Like a variable or a method, a class can be made static.
A static class:
- Is a class whose members must be accessed without an instance of the class. In other words, the members of a static class must be accessed directly from (using the name of) the class, using the period operator
- Is a class whose members must be created as static. In other words, you cannot add a non-static member to a static class: all members, except for constants, must be static
Creating a Static Class
|
To create a static class, precede the class
keyword with the static keyword. Based on the above two rules, here
is an example:
using System; public static class Square { public static double side; public static double Perimeter() { return side * 4; } public static double Area() { return side * side; } } public class Exercise { public static int Main() { Square.Side = 36.84; Console.WriteLine("Square Characteristics"); Console.Write("Side: "); Console.WriteLine(Square.side); Console.Write("Perimeter: "); Console.WriteLine(Square.Perimeter()); Console.Write("Area: "); Console.WriteLine(Square.Area()); return 0; } }
This would produce:
Square Characteristics Side: 36.84 Perimeter: 147.36 Area: 1357.1856 Press any key to continue . . .
If you create a class marked as static, you cannot
derive a class from it.
Static Constructors
|
Like a normal method, a constructor can be made static.
There are rules you must follow. If you want to use a static constructor,
you must explicitly create it (the compiler doesn't create a static
constructor for you).
The static constructor must become the default
constructor. That is, you must create a constructor that doesn't take any
argument. Here is an example:
public class Person { public string firstName; static Person() { } }
If you create a static constructor, you cannot directly
access the non-static fields of the class:
You can still access any field of the class as you see
fit. Here are examples:
using System; public class Person { public string firstName; static Person() { } } public class Exercise { public static int Main() { Person pers = new Person(); pers.firstName = "Gertrude"; Console.WriteLine("Personal Identification"); Console.Write("Name: "); Console.WriteLine(pers.firstName); return 0; } }
To use a static constructor, you have various options.
To initialize a member variable in the static constructor, you can declare a
variable for the class and access the member variable. Here is an example:
public class Person
{
public string firstName;
static Person()
{
Person pers = new Person();
pers.firstName = "Gertrude";
}
}
In reality, one of the reasons for using a static
constructor is to initialize the static fields of the class or take any
action that would be shared by all instances of the class. Therefore,
another option to use a static constructor is to initialize the static
member variables. After doing this, when accessing the initialized static
field(s), it(they) would hold the value(s) you gave it(them). Here is an
example:
using System; public class Person { public static string firstName; static Person() { firstName = "Gertrude"; } } public class Exercise { public static int Main() { Console.WriteLine("Personal Identification"); Console.Write("Name: "); Console.WriteLine(Person.firstName); return 0; } }
This would produce:
Personal Identification Name: Gertrude Press any key to continue . . .
Because the constructor is static, you cannot access it
by declaring a variable for the class.
Another rule to observe with a static constructor is
that you must not add an access modifier to it. The following will result in
an error:
public class Person
{
public static Person()
{
}
}
You can create a class that uses a combination of a
static constructor and one or more other (non-static) constructors. Here is
an example:
public class Person { public string firstName; public string lastName; static Person() { } public Person(string first, string last) { firstName = first; lastName = last; } }
If you create such a class and if you want to declare a
variable for it, the default constructor doesn't exist or is not available.
If you want to declare a variable, you must use a constructor that takes an
argument. Here is an example:
using System; public class Person { public string firstName; public string lastName; static Person() { } public Person(string first, string last) { firstName = first; lastName = last; } } public class Exercise { public static int Main() { Person pers = new Person("Gertrude", "Monay"); Console.WriteLine("Personal Identification"); Console.Write("First Name: "); Console.WriteLine(pers.firstName); Console.Write("Last Name: "); Console.WriteLine(pers.lastName); return 0; } }
This would produce:
Personal Identification First Name: Gertrude Last Name: Monay Press any key to continue . . .
Based on this, you should create a static constructor
only if you have a good reason.
The Scope and Lifetime of a Variable
|
Introduction
|
We have seen many examples of declaring local variables.
Here is an example:
using System;
public class Exercise
{
public static int Main()
{
int number;
return 0;
}
}
In some cases, you may want a variable that can be
accessed and modified by various methods of the same class. To do this, you
can declare the variable outside of any method. Such a variable is referred
to as global.
Creating and Using a Global Variable
|
As stated already, to create a global variable, declare
it outside of any method but inside the class. Here is an example:
using System;
public class Exercise
{
int number;
public static int Main()
{
return 0;
}
}
After declaring the variable, you can use any methods
inside the class to access it, such as changing its value. Here are
examples:
using System; public class Exercise { int number; public void Modify() { number = 28; } public void Change() { number = 405; } public static int Main() { Exercise exo = new Exercise(); Console.Write("Number: "); Console.WriteLine(exo.number); exo.Modify(); Console.Write("Number: "); Console.WriteLine(exo.number); exo.Change(); Console.Write("Number: "); Console.WriteLine(exo.number); return 0; } }
This would produce:
Number: 0 Number: 28 Number: 405 Press any key to continue . . .
You can also use a method to show the value of the
global variable:
using System;
public class Exercise
{
int number;
public void Modify()
{
number = 28;
}
public void Change()
{
number = 405;
}
public void Show()
{
Console.Write("Number: ");
Console.WriteLine(number);
}
public static int Main()
{
Exercise exo = new Exercise();
exo.Show();
exo.Modify();
exo.Show();
exo.Change();
exo.Show();
return 0;
}
}
Static and Global Variables
|
Unlike C++, you cannot declare a static variable inside
a method. The solution is to declare it outside any method. After doing
that, you can access the variable from any method that needs it. Here is an
example:
using System;
public class Exercise
{
static int number;
public void Modify()
{
number = 28;
}
public void Change()
{
number = 405;
}
public void Show()
{
Console.Write("Number: ");
Console.WriteLine(number);
}
public static int Main()
{
Exercise exo = new Exercise();
exo.Show();
exo.Modify();
exo.Show();
exo.Change();
exo.Show();
return 0;
}
}
Characteristics of Static Members
|
Unlike C/C++, in C#, you can create a constant variable
in a class. As done in Lesson
3 when studying variables, to declare a constant variable, type the
const keyword to the left of the variable. Once again, when declaring a
constant, you must initialize it with an appropriate constant value.
If a class contains fields and methods, the (non-static)
field members are automatically available to the method(s) of the class,
even fields that are private. When accessing a field or a method from
another method of the class, to indicate that the member you are accessing
belongs to the same class, you can precede it with an object called this
and the period operator. Here are examples:
public class House { internal char propertyType; internal uint bedrooms; internal void Display() { Console.WriteLine("=//= Altair Realtors =//="); Console.WriteLine("Properties Inventory"); ; Console.Write("Property Type: "); Console.WriteLine(this.propertyType); Console.Write("Bedrooms: "); Console.WriteLine(this.bedrooms); } } public class Exercise { public static int Main() { House h = new House(); h.Display(); return 0; } }
When using this, you can access any member of a
class within any method of the same class. There are rules you must observe
when using this:
- The this object can never be declared: it is automatically implied when you create a class
- this cannot be used in a class A to access a member of class B
- this cannot be used in a static method
No comments:
Post a Comment