Staticity
Staticity
IIntroduction
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:
public class Book
{
public string title;
public string author;
public int yearPublished;
public int numberOfPages;
public string coverType;
}
public class Exercise
{
static void Main()
{
var written = new Book();
var bought = new Book();
return 0;
}
}
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 int yearPublished; public int numberOfPages; public string coverType; } public class Exercise { static void 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 int yearPublished; public int pages; public string coverType; } public class Exercise { static void 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); } }
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); } static void 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 } static void 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;
}
}
Static Classes
Introduction
Like a variable or a method, a class can be made static. A static class:
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; } }
If you create a class marked as static, you cannot derive a class from it.
Using a Static Class
To use a static class, just type its name where you want to use it. To access a member of the class, apply a period to the name followed by the desired member. 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
{
static void 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 . . .
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 { static void 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 { static void 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 { static void 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.
Static Classes and Namespaces
Introduction
When creating a static class, you can include it in a namespace. Here is an example:
namespace BusinessManagement { static class LoanApplicant { public static long AccountNumber = 402_924_759; public static string FullName = "Joseph Nyate"; } }
Using a Static Class of a Namespace
If the code where you want to access a static class is in the same namespace as the static class, you can use the class by its name. Here is an example:
namespace BusinessManagement { public class Exercise { static void Main() { System.Console.WriteLine("Loan Application"); System.Console.Write("Account #: "); System.Console.WriteLine(LoanApplicant.AccountNumber); System.Console.Write("Applicant Name: "); System.Console.WriteLine(LoanApplicant.FullName); return 0; } } } namespace BusinessManagement { static class LoanApplicant { public static long AccountNumber = 402_924_759; public static string FullName = "Joseph Nyate"; } }
As we have learned in this and the previous lesson, if the class was created in a namespace different from the area where you want to use it, one option is to fully qualify the name of the class. Here are examples:
namespace BusinessManagement { public class Exercise { static void Main() { System.Console.WriteLine("Loan Application"); System.Console.Write("Account #: "); System.Console.WriteLine(LoanApplicant.AccountNumber); System.Console.Write("Applicant Name: "); System.Console.WriteLine(LoanApplicant.FullName); System.Console.Write("Loan Amount: "); System.Console.WriteLine(Information.Evaluation.LoanAmount); System.Console.Write("Interest Rate: "); System.Console.Write(Information.Evaluation.InterestRate); System.Console.WriteLine("%"); System.Console.Write("Perdiods: "); System.Console.Write(Information.Evaluation.Periods); System.Console.WriteLine(" Months"); return 0; } } } namespace BusinessManagement { static class LoanApplicant { public static int AccountNumber = 402_924_759; public static string FullName = "Joseph Nyate"; } } namespace Information { static class Evaluation { public static double LoanAmount = 2460; public static double InterestRate = 14.65; // % public static double Periods = 42d; } }
Another option is to first add a using line that includes the static class's namespace, then use the name of the class. Here is an example:
namespace BusinessManagement
{
using Information;
public class Exercise
{
static void Main()
{
System.Console.WriteLine("Loan Application");
System.Console.Write("Account #: ");
System.Console.WriteLine(LoanApplicant.AccountNumber);
System.Console.Write("Applicant Name: ");
System.Console.WriteLine(LoanApplicant.FullName);
System.Console.Write("Loan Amount: ");
System.Console.WriteLine(Evaluation.LoanAmount);
System.Console.Write("Interest Rate: ");
System.Console.Write(Evaluation.InterestRate);
System.Console.WriteLine("%");
System.Console.Write("Perdiods: ");
System.Console.Write(Evaluation.Periods);
System.Console.WriteLine(" Months");
return 0;
}
}
}
namespace BusinessManagement
{
static class LoanApplicant
{
public static int AccountNumber = 402_924_759;
public static string FullName = "Joseph Nyate";
}
}
namespace Information
{
static class Evaluation
{
public static double LoanAmount = 2460;
public static double InterestRate = 14.65; // %
public static double Periods = 42d;
}
}
As another option, in the top section of the code, type using static followed by the name of the namespace, a period, and the name of the class. Then, in the code, directly access any of the members of the static class. Here is an example:
namespace BusinessManagement { using static Information.Evaluation; public class Exercise { static void Main() { System.Console.WriteLine("Loan Application"); System.Console.Write("Account #: "); System.Console.WriteLine(LoanApplicant.AccountNumber); System.Console.Write("Applicant Name: "); System.Console.WriteLine(LoanApplicant.FullName); System.Console.Write("Loan Amount: "); System.Console.WriteLine(LoanAmount); System.Console.Write("Interest Rate: "); System.Console.Write(InterestRate); System.Console.WriteLine("%"); System.Console.Write("Perdiods: "); System.Console.Write(Periods); System.Console.WriteLine(" Months"); return 0; } } } namespace BusinessManagement { static class LoanApplicant { public static int AccountNumber = 402_924_759; public static string FullName = "Joseph Nyate"; } } namespace Information { static class Evaluation { public static double LoanAmount = 2460; public static double InterestRate = 14.65; // % public static double Periods = 42d; } }
Console is a Static Class
As we have seen so far, to display something a in a DOS window, you can use the Console class defined in the System namespace. Actually, Console is a static class. As such, to use it, in the top section of your code, you can write using static System.Console;. Then, in your code, directly access any of its members. Here is an example:
using static System.Console; using static Information.Evaluation; namespace BusinessManagement { public class Exercise { static void Main() { WriteLine("Loan Application"); Write("Account #: "); WriteLine(LoanApplicant.AccountNumber); Write("Applicant Name: "); WriteLine(LoanApplicant.FullName); Write("Loan Amount: "); WriteLine(LoanAmount); Write("Interest Rate: "); Write(InterestRate); WriteLine("%"); Write("Perdiods: "); Write(Periods); WriteLine(" Months"); return 0; } } } namespace BusinessManagement { static class LoanApplicant { public static long AccountNumber = 402_924_759; public static string FullName = "Joseph Nyate"; } } namespace Information { static class Evaluation { public static double LoanAmount = 2460; public static double InterestRate = 14.65; // % public static double Periods = 42d; } }
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
{
static void 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;
static void 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 static System.Console; public class Exercise { int number; public void Modify() { number = 28; } public void Change() { number = 405; } static void Main() { Exercise exo = new Exercise(); Write("Number: "); WriteLine(exo.number); exo.Modify(); Write("Number: "); WriteLine(exo.number); exo.Change(); Write("Number: "); 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 static System.Console;
public class Exercise
{
int number;
public void Modify()
{
number = 28;
}
public void Change()
{
number = 405;
}
public void Show()
{
Write("Number: ");
WriteLine(number);
}
static void 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 static System.Console;
public class Exercise
{
static int number;
public void Modify()
{
number = 28;
}
public void Change()
{
number = 405;
}
public void Show()
{
Write("Number: ");
WriteLine(number);
}
static void 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 previous lessons about variables, to create a constant, 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:
using static System.Console; public class House { internal string propertyType; internal int bedrooms; internal void Display() { WriteLine("=//= Altair Realtors =//="); WriteLine("Properties Inventory"); ; Write("Property Type: "); WriteLine(this.propertyType); Write("Bedrooms: "); WriteLine(this.bedrooms); } } public class Exercise { static void 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 Main Function of an Application
Introduction
A C# application that executes in a computer application must have a function named Main. The Main() function must be created as static.
The Return Type of the Main Function
The Main() function is usually made to return void. To create a void Main() function using skeleton code, right-click the section where you want to add it and click Insert Snippet... Double-click Visual C# and double-click svm (stands for "static void Main"):
Another way to implement the Main() function is to make it return an integer. The rule is the same as for any method of type int. The Main() function can return any type of integer as long as it is a valid integer. Here is an example:
class Exercise { static int Main() { return 244006; } }
To use skeleton code to create a Main() function that returns an integer, right-click the section where you want to add it and click Insert Snippet... Double-click Visual C# and double-click sim (stands for "static int Main").
The Access of the Main Function
Like any regular method, the Main() function can use an access level. Normally, any of them will do: private, public, or internal.
The Main Class of an Application
When you create an application in C#, that is, an application that will execute as a computer application, you must create a(t least one) class. In that class, you must include a static method named Main. Here is an example:
public class Exercise { public static void Main() { } }
In the class that contains the Main() method, you can create other methods and you can create fields as necessary. To access the members of that class from the Main() method, you have two options.
You can create regular members in the class that contains the Main() method. If you want to access one of those members in the Main() method, you must declare a variable of the class and then access the member from that variable. Here are examples:
using static System.Console; public class Vaccination { string Interest = "Preventable Diseases"; void Introduce() { WriteLine("A vaccination is a type of injected medication that mimics a person's immune system to simulate a pathogen. The end goal is to create a situation of immunity."); } string SpecifyOccurrence() => "A vaccination must be regulated by a government."; internal static int Main() { WriteLine("Department of Health"); WriteLine("--------------------------------------------------"); Vaccination injection = new Vaccination(); WriteLine(injection.Interest); injection.Introduce(); WriteLine("--------------------------------------------------"); WriteLine(injection.SpecifyOccurrence()); WriteLine("=================================================="); return 0; } }
If you want to directly access a member of that class in the Main() method, you must create that member as static. Here are examples:
using static System.Console; public class Vaccination { string Interest = "Preventable Diseases"; void Introduce() { WriteLine("A vaccination is a type of injected medication that mimics a person's immune system to simulate a pathogen. The end goal is to create a situation of immunity."); } string SpecifyOccurrence() => "A vaccination must be regulated by a government."; static string vaccinationName = "Quinimax Injection"; static void DefineVeccination() { WriteLine("Quinimax Injection is a type of vaccination used to fight malaria, varicose, and other types of preventable deseases."); } internal static int Main() { WriteLine("Department of Health"); WriteLine("--------------------------------------------------"); Vaccination injection = new Vaccination(); WriteLine(injection.Interest); injection.Introduce(); WriteLine(injection.SpecifyOccurrence()); WriteLine("=================================================="); WriteLine("--------------------------------------------------"); WriteLine("Vaccination Name: {0}", vaccinationName); DefineVeccination(); WriteLine("=================================================="); return 0; } }
|
||
Previous | Copyright © 2008-2019, FunctionX | Next |
|