C Sharp Programming/Classes
From Wikibooks, the open-content textbooks collection
As in other object-oriented programming languages, the functionality of a C# program is implemented in one or more classes. The methods and properties of a class contain the code that defines how the class behaves.
C# classes support information hiding by encapsulating functionality in properties and methods and by enabling several types of polymorphism, including subtyping polymorphism via inheritance and parametric polymorphism via generics.
Several types of C# classes can be defined, including instance classes (standard classes that can be instantiated), static classes, and structures.
Classes are defined using the keyword "class" followed by an identifier to name the class. Instances of the class can then be created with the "new" keyword followed by the name of the class. The code below defines a class called Employee with properties Name and Age and with empty methods GetPayCheck() and Work(). It also defines a Sample class that instantiates and uses the Employee class:
public class Employee
{
private string _name;
private int _age;
public string Name
{
set { _name = value; }
get { return _name; }
}
public int Age
{
set { _age = value; }
get { return _age; }
}
public void GetPayCheck()
{
}
public void Work()
{
}
}
public class Sample
{
public static void Main()
{
Employee Marissa = new Employee();
Marissa.Work();
Marissa.GetPayCheck();
}
}
Contents |
[edit] Methods
C# methods are class members containing code. They may have a return value and a list of parameters, as well as a generic type declaration. Like fields, methods can be static (associated with and accessed through the class) or instance (associated with and accessed through an object instance of the class).
[edit] Constructors
A class's constructors control its initialization. A constructor's code executes to initialize an instance of the class when a program requests a new object of the class's type. Constructors often set properties of their classes, but they are not restricted to doing so.
Like other methods, a constructor can have parameters. To create an object using a constructor with parameters, the new command accepts parameters. The code below defines and then instantiates multiple objects of the Employee class, once using the constructor without parameters and once using the version with a parameter:
public class Employee
{
public Employee()
{
System.Console.WriteLine("Constructed without parameters");
}
public Employee(string text)
{
System.Console.WriteLine(text);
}
}
public class Sample
{
public static void Main()
{
System.Console.WriteLine("Start");
Employee Alfred = new Employee();
Employee Billy = new Employee("Parameter for construction");
System.Console.WriteLine("End");
}
}
Output:
Start Constructed without parameters Parameter for construction End
Constructors can call each other:
public class Employee { public Employee(string text, int number) { ... } public Employee(string text) : this(text, 1234) // calls the above constructor with user-specified text and the default number { } public Employee() : this("default text") // calls the above constructor with the default text { } }
[edit] Finalizers
The opposite of constructors, finalizers define the final behavior of an object and execute when the object is no longer in use. Although they are often used in C++ to free memory reserved by an object, they are less frequently used in C# due to the .NET Framework Garbage Collector. An object's finalizer, which takes no parameters, is called sometime after an object is no longer referenced, but the complexities of garbage collection make the specific timing of finalizers uncertain.
public class Employee
{
public Employee(string text)
{
System.Console.WriteLine(text);
}
~Employee()
{
System.Console.WriteLine("Finalized!");
}
public static void Main()
{
Employee Marissa = new Employee("Constructed!");
Marissa = null;
}
}
Output:
Constructed! Finalized!
[edit] Properties
C# properties are class members that expose functionality of methods using the syntax of fields. They simplify the syntax of calling traditional get and set methods (a.k.a. accessor methods). Like methods, they can be static or instance.
Properties are defined in the following way:
public class MyClass
{
private int integerField = 3; // Sets integerField with a default value of 3
public int IntegerField
{
get {
return integerField; // get returns the field you specify when this property is assigned
}
set {
integerField = value; // set assigns the value assigned to the property of the field you specify
}
}
}
The C# keyword value contains the value assigned to the property. After a property is defined it can be used like a variable. If you were to write some additional code in the get and set portions of the property it would work like a method and allow you to manipulate the data before it is read or written to the variable.
using System;
public class MyProgram
{
MyClass myClass = new MyClass;
Console.WriteLine(myClass.IntegerField); // Writes 3 to the command line.
myClass.IntegerField = 7; // Indirectly assigns 7 to the field myClass.integerField
}
Using properties in this way provides a clean, easy to use mechanism for protecting data.
[edit] Indexers
C# indexers are class members that define the behavior of the array access operation (e.g. list[0] to access the first element of list even when list is not an array).
To create an indexer, use the this keyword as in the following example:
public string this[string key]
{
get { return coll[key]; }
set { coll[key] = value; }
}
This code will create a string indexer that returns a string value. For example, if the class was EmployeeCollection, you could write code similar to the following:
EmployeeCollection e = new EmployeeCollection();
.
.
.
string s = e["Jones"];
e["Smith"] = "xxx";
[edit] Events
C# events are class members that expose notifications to clients of the class.
[edit] Operator overloading
C# operator definitions are class members that define or redefine the behavior of basic C# operators (called implicitly or explicitly) on instances of the class:
public class Complex { private double re, im; public double Real { get { return re; } set { re = value; } } public double Imaginary { get { return im; } set { im = value; } } // binary operator overloading public static Complex operator +(Complex c1, Complex c2) { return new Complex() { Real = c1.Real + c2.Real, Imaginary = c1.Imaginary + c2.Imaginary }; } // unary operator overloading public static Complex operator -(Complex c) { return new Complex() { Real = -c.Real, Imaginary = -c.Imaginary }; } // cast operator overloading (both implicit and explicit) public static implicit operator double(Complex c) { // return the modulus - sqrt(x^2 + y^2) return Math.Sqrt(Math.Pow(c.Real, 2) + Math.Pow(c.Imaginary, 2)); } public static explicit operator string(Complex c) { // we should be overloading the ToString() method, but this is just a demonstration return c.Real.ToString() + " + " + c.Imaginary.ToString() + "i"; } } public class StaticDemo { public static void Main() { Complex number1 = new Complex() { Real = 1, Imaginary = 2 }; Complex number2 = new Complex() { Real = 4, Imaginary = 10 }; Complex number3 = number1 + number2; // number3 now has Real = 5, Imaginary = 12 number3 = -number3; // number3 now has Real = -5, Imaginary = -12 double testNumber = number3; // testNumber will be set to the absolute value of number3 Console.WriteLine((string)number3); // This will print "-5 + -12i". // The cast to string was needed because that was an explicit cast operator. } }
[edit] Structures
Structures, or structs, are defined with the struct keyword followed by an identifier to name the structure. They are similar to classes, but have subtle differences. Structs are used as lightweight versions of classes that can help reduce memory management efforts when working with small data structures. In most situations, however, using a standard class is a better choice.
The principal difference between structs and classes is that instances of structs are values whereas instances of classes are references. Thus when you pass a struct to a function by value you get a copy of the object so changes to it are not reflected in the original because there are now two distinct objects but if you pass an instance of a class by value then there is only one instance.
The Employee structure below declares a public and a private field. Access to the private field is granted through the public property "Name":
struct Employee
{
private string name;
public int age;
public string Name
{
set { name = value; }
get { return name; }
}
}
[edit] Static classes
Static classes are commonly used to implement a Singleton Pattern. All of the methods, properties, and fields of a static class are also static (like the WriteLine() method of the System.Console class) and can thus be used without instantiating the static class:
public static class Writer
{
public static void Write()
{
System.Console.WriteLine("Text");
}
}
public class Sample
{
public static void Main()
{
Writer.Write();
}
}