C# is a language designed to interpret "real-life" objects into syntax the computer can understand. Real-life objects are made up of data and functionality. Since C# is designed to be a true object-oriented language, all code is based on the class. The class is the name of the type that you use to define the relationship between data and functions or methods. The class declaration in C# also includes the class definition, so it is the one-stop place where everything about the class is defined.
| Note |
The declaration of a class does not result in memory being reserved. Memory will not be allocated until an instance of the class is created. Each instance of a class contains unique memory locations for data members of the instance. |
Another key feature of classes in C# is the idea of encapsulation. Encapsulation is the process of controlling what is publicly available to clients that instantiate the class. (See the "Core OOP Concepts" section later in this chapter for more information about encapsulation.)
If you were to examine a class, you would find that it has six main parts, as shown in Table 5-1.
|
Component |
Description |
|---|---|
|
Fields |
Used to store variables in a class |
|
Properties |
Used to expose fields to client code |
|
Methods |
Provide actions for the class by manipulating fields and properties |
|
Constructors |
Initialize fields to values preferred for a class |
|
Destructors |
Called by garbage collectors |
|
Dispose methods |
Called by clients to clean up objects on their time schedule |
When you are declaring a new class, you should set the accessibility of its members by using the access specifiers listed in Table 5-2.
|
Access Specifier |
Description |
|---|---|
|
public |
No access limitation |
|
protected |
Access limited to containing classes or derived classes |
|
internal |
Access limited to this program |
|
protected internal |
Access limited to this program or derived classes |
|
private |
Access limited to containing types |
The following example demonstrates declaring and defining a class.
using System;
namespace Client.Chapter_5___Building_Your_Own_Classes
{
//Class definition
public class DeclaringandDefiningClasses
{
//Fields
static private int MyInt = 5;
//Access Specifiers
static public int MyInt2 = 10;
static public int[] MyIntArray;
static private int ObjectCount = 0;
//Methods
static void Main(string[] args)
{
MyIntArray = new int[10];
ObjectCount++;
}
public static int MyMethod(int myInt)
{
MyInt = MyInt + myInt;
return MyInt;
}
private static long MyLongMethod(ref int myInt)
{
return myInt;
}
}
}