Wednesday, March 31, 2010

What is base class of page in ASP.NET?

Single – File Pages: - In a single file page, the markup, server – side elements, and event-handling code are all in a single .aspx file. The base class of single – file page is Page class which is under System.Web.UI namespace.

Code – Behind Pages: - In the code – behind model, the page’s markup and server-side elements, including control declarations, are in an .aspx file, while our page code is in a separate code file. The code file contains a partial class – that is, a class declaration with the keyword partial indicating that it contains only some of the total code that makes up the full class for the page. In the partial class, we add the code that our application requires for the page. This typically consists of event handlers, but can include any methods or properties that we need. The code – behind file contains a partial class that inherits from a base page class. The base page class can be the Page class, or it can be another class that derives for Page.

Wednesday, March 24, 2010

Hiding Interface Members

We can also hide base class members on interfaces. Suppose that we have two interfaces: IBase and IDerived. As the name indicates, IDerived is derived from IBase. The following is a declaration of a property M1 in the interface IBase.
interface IBase
{
    int M1 {get; set; }
}
In the same program, we can declare a method with the same name, M1 on the interface IDerived:
interface IDerived: IBase
{
    new int M1();
}
With this declaration, the member M1 on the derived interface hides the member M1 on the base interface. In this case, it is necessary to use explicit interface implementation in any class that implements these interfaces:
class MyClass: IDerived
{
    private int m1;
    //Explicit implementation of the property M1:
    int IBase.M1
    {
        get { return m1; }
        set { m1 = value; }
    }
    // Explicit implementation of the method M1:
    void IDerived.M1() { }
}
It is also possible to implement the property explicitly and the method normally, as shown in this example:
class MyClass: IDerived
{
    private int m1;
    //Explicit implementation of the property:
    int IBase.M1
    {
        get { return m1; }
        set { m1 = value; }
    }
    // Normal implementation of the method:
    public void M1()
    {
    }
}
A third possibility is to implement the method explicitly and the property normally, as shown below:
class MyClass : IDerived
{
    private int m1;
    //Normal implementation of the property:
    public int M1
    {
        get { return m1; }
        set { m1 = value; }
    }
    //Explicit implementation of the method:
    void IDerived.M1() { }
}
In the following example, one of the explicit alternative implementations of method and property is demonstrated.
//Example 8-6.cs
//Hiding interface members
using System;
interface IBase
{
    int M1 { set;  get; }
}
interface  IDerived: IBase
{
    //Declare a method that hides the property
    // On the IBase interface:
    new void M1();
}
class MyClass: IDerived
{
    private int x;
    //Explicit implementation of the property:
    int IBase.M1
    {
        get { return x; }
        set { x = value; }
    }
    //Explicit implementation of the method:
    void IDerived.M1()
    {
        Console.WriteLine(“Hi, I am the M1 method!”);
    }
}
class MainClass
{
    static void Main()
    {
        // Create a class object:
        MyClass mc = new MyClass();
        //Create an IDerived object:
        IDerived mi1 = (IDerived)mc;
        //Create an IBase object:
        IBase mi2 = (IBase)mc;
        //Use the property:
        mi2.M1 = 123;
        //Call the method:
        mi1.M1();
        //Display the property:
        Console.WriteLine(“I am the M1 property. My value is {0}.”, mi2.M1);
    }
}

What is Versioning?

Using the new modifier to hide the inherited members is similar to overriding methods using the override modifier. Both are used to design a new version of a program while maintaining backward compatibility with previous versions of the program. For example, assume that we are inheriting a class product by Acme Company called AcmeClass:
public class AcmeClass //AcmeClass:
{
    //…
}
public class MyClass: AcmeClass // your class
{
    //…
}
Suppose that we needed to add a method of our own named MyMethod, like this:
public class MyClass: AcmeClass
{
    public virtual MyMethod()
    {
        //The new method in our program.
    }
    //…
}
Our program was working just fine until Acme produced a new version of its program that includes a method called MyMethod, which does the same work:
public class AcmeClass
{
    public virtual MyMethod()
    {
        //The new method in Acme’s program v2.0.
    }
}
Now we have a problem. The solution is to just use the new modifier to declare MyMethod in our program. This will emphasize our intention to hide the method MyMethod in the second version of AcmeClass. For example:
public class MyClass: AcmeClass
{
    public new virtual MyMethod()
    {
        //….
    }
}
Problem solved.
We can, as an alternative, use the override modifier if we plan to override MyMethod in the base class.
In the following example the class MyDerivedClass inherits the class MyBaseClass. Each class contains a member class called MyClass. In order to hide MyClass in the base class, the new modifier is used in the class declaration. This way, it becomes possible to access members in both classes and use their members.
//Example 8-5.cs
//Hiding members using the new modifier
using System;
public class MyBaseClass
{
    public class MyClass
    {
        public int myInt = 123;
        public virtual string MyMethod()
        {
            return “Hello from the base class!”;
        }
    }
}
public class MyDerivedClass : MyBaseClass
{
    //The following nested class hides the base class member:
    new public class MyClass //notice the new modifier
    {
        public int myInt = 321;
        public virtual string MyMethod()
        {
            return “Hello from the derived class!”;
        }
    }
    static void Main()
    {
        //Create an object from the “new” MyClass:
        MyClass myObj1 = new MyClass();
        //Create an object from the hidden MyClass:
        MyBaseClass.MyClass myObj2 = new MyBaseClass.MyClass();
        Console.WriteLine(“Value from the ‘new’ MyClass: {0}”, myObj1.myInt);
        Console.WriteLine(“Value from the ‘hidden’ MyClass: {0}”, myObj2.myInt);
        Console.WriteLine(“Value form the ‘new’ MyClass: {0}”, myObj1.MyMethod());
        Console.WriteLine(“Message from the ‘hidden’ MyClass: {0}”, myObj2.MyMethod());
    }
}
In the preceding example we created an object of each of the classes named MyClass. Although each class contains a field and a method with the same name as those in the other class, the new modifier was used only once in declaring the class.

Hiding Members of the Base Class

We have already used the new operator to create objects. Another use of the new operator is to modify declarations of the inherited members in order to hide members with the same names in the base class. Suppose that we have a base class that contains a method called MyMethod:
public class MyBaseClass
{
    public int myInt;
    public void MyMethod() //MyMethod on the base class
    {
        //….
    }
}
When this class is inherited, the derived class will inherit all its members. Suppose that we would like to declare a new member with the same name, MyMethod, in the derived class. We can do that by using the new modifier, as shown in this example:
public class MyDerivedClass: MyBaseClass
{
    new public void MyMethod() // MyMethod on the derived class
    {
        //…
    }
}
The job of the new modifier here is to hide the member with the same name in the base class. A method that uses the new modifier hides properties, fields, and types with the same name. It also hides the methods with the same signatures. In general, declaring a member in the base class would hide any members in the base class with the same name. If we declare MyMethod in the above example without the new modifier, it still works, but we will get a compiler warning:
‘MyDerivedClass.MyMethod()’ hides inherited member
‘MyBaseClass.MyMethod()’. Use the new keyword if hiding was intended.
Notice the following when we use the new modifier:
•    We cannot use new and override in the same declaration. If we do that we get the compiler error:
A member ‘MyDerivedClass.MyMethod()’ marked as override cannot be marked as new or virtual.
•    It is possible, through, to use virtual and new in the same declaration. This emphasizes our intention to hide the member in the base class and start a new point of specialization in the inheritance hierarchy.

Using as to Test Types

The operator as is used to convert an expression to a specified reference type. It is used according to the form:
expression as type
where:
type is a reference type.
expression is the object to be converted.
If the conversion is successful, it returns the value of the expression; null otherwise.
This expression is equivalent to casting expression with type except that it doesn’t throw an exception if the conversion fails. The expression is equivalent to the following conditional expression:
expression is type ? (type) expression : (type) null;
In the following example, the method TestType is used to test objects of various types. Notice that only reference – type objects are converted.
Example 8-4
//Example 8-4.cs
// The as operator
using System;
public class MyClass
{
    static void TestType(object o)
    {
        if(o as MyClass != null)
            Console.WriteLine(“The object \”{0}\” is a class.”, o);
        else if ( o as string != null)
            Console.WriteLine(“The object \”{0}\” is a string.”, o);
        else
            Console.WriteLine(“The object \”{0}\” is not a reference type.”, o);
    }
    static void Main()
    {
        MyClass mc = new MyClass();
        string myString = “Hello, World!”;
        int myInt = 123;
        TestType(mc);
        TestType(myString);
        TestType(myInt);
    }
}

Using is to Test Types

The operator is is used to test the type of various objects at run time. It is used in the following form:
expression is type
where:
type is a reference type.
expression is the object to be tested.
The result of this operation is either true of false.
For example, the following expression:
myObj is MyClass
is used to check if the object myObj is an instance of the class MyClass. The result of the expression renders true if it is an instance of MyClass; false otherwise.
Also, the expression:
myObj is MyInterface
is used to check if the object myObj is an instance of a class that implements the interface of a class that implements the interface IMyInterface. The result is either true of false.
In the following example, the operator is is used to check if the type if an object is an instance of MyClass and the two interfaces I1 and I2.
Example: -
//Example 8-3.cs
// The is operator
using System;
interface I1
{
}
interface I2
{
}
class Class1: I1, I2
{
}
class MyClass
{
    static bool TestType(object obj)
    {
        if (obj is l1 & obj is I2 & obj is Class1}
                return true;
        else
            return false;
    }
    public static void Main()
    {
        Class1 c = new Class1();
        Console.WriteLine(“The result of the test: {0}”, TestType(c ) );

    }
}

Explicit Interface Implementation

Consider a class, MyClass, that implements an interface, IMyInterface. It is possible to implement the interface member, MyMethod, like this:
string IMyInterface.MyMethod()
{
    // interface implementation
}
In this example, MyMethod is qualified by the interface name, IMyInterface:
IMyInterface.MyMethod()
This is called explicit interface implementation. Assume that we created an object from MyClass using the following statement:
MyClass mc = new MyClass();
We can also create an interface object by casting the class object:
IMyInterface mi = (IMyInterface) mc;
In this case, we can also access MyMethod through the interface object mi. For example:
Console.Write(mi.MyMethod());
Attempting to access MyMethod through the class member mc would generate a compilation error:
Console.Write(mc.MyMethod()); //error
So, when do we need to use this code? There are cases in which the use of explicit interface implementation becomes necessary, such as when the class is implementing two interface and both interfaces contain a method named MyMethod. If the first interface object is mil and the second interface object is mi2, accessing MyMethod through interface objects does not cause any ambiguity. That is:
Console.Write(mi1.MyMethod());
Console.Write(mi2.MyMethod());
In fact, using the class object to access the method will cause ambiguity.
The following example demonstrates a temperature converter that converts from Fahrenheit to Celsius and vice versa. The program contains two interfaces: ITemp1 and ITemp2. Each contains a method named Convert. The class TempConverter explicitly implements the two interfaces. In the Main method, two interface objects, iFC and iCF, are used to access the Convert method.
// Example 8-2
// Explicit interface implementation
using System;
public interface ITemp1
{
    double Convert(double d);
}
public interface ITemp2
{
    double Convert(double d);
}
public class TempConverter: ITemp1, ITemp2
{
    double ITemp1.Convert(double d)
    {
        //Convert to Fahrenheit:
        return ( d * 1.8) + 32;
    }
    double ITemp2.Convert(double d)
    {
        //Convert to Celsius:
        return ( d – 32 ) / 1.8;
    }
}
class MyClass
{
    public static void Main()
    {
        // Create a class instance:
        TempConverter cObj = new TempConverter();
        // Create instances of interfaces
        // Create a From – Celsius – to – Fahrenheit object:
        ITemp1 iCF = (ITemp1) cObj;
        // Create From – Fahrenheit – to – Celsius object:
        ITemp2 iFC = (ITemp2) cObj;
       
        // Initialize variables:
        double F = 32;
         double C = 20;
        // Print results:
        Console.WriteLine(“Temperature {0} C in Fahrenheit: {1:F2}” , C, iCF.Convert( C ));
        Console.WriteLine(“Temperature {0} F in Celsius: { 1:F2}” , F, iFC.Convert(F));
    }
}

Interface Implementation

The interface can be implemented by a class or a struct as shown in this example:
class MyClass: IMyInterface1
{
    // class implementation
}
By this declaration the class MyClass is obligated to implement all members of the interface IMyInterface.
It is also possible for a class to implement more than one interface:
class MyClass: IMyInterface1, IMyInterface2
{
    //class implementation
}
A class can also implement another class in addition to the interfaces:
class MyClass: MyBaseClass, IMyInterface1, IMyInterface2
{
    //class implementation
}
In the following example, the class Point implements the interface the interface IPoint. Notice that all the fields are included in the class but none are included in the interface.
//Example 8-1.cs
//Interface example
using System;
interface IPoint
{
    //Property signatures:
    int Myx
    {
        get; set;
    }
    int Myy
    {
        get; set;
    }
}
class Point: IPoint
{
    //Fields:
    private int x;
    private int y;
    //constructor:
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
    //Property implementation:
    public int Myx
    {
        get { return x; }
        set { x = value; }
    }
    public int Myy
    {
        get  { return y; }
        set ( y = value; }
    }
    public static void DisplayMyPoint(IPoint myPoint)
    {
        Console.WriteLine(“({0},{1}”, myPoint.Myx, myPoint.Myy);
    }
}
class MyClass
{
    static void Main()
    {
        Point myPoint = new Point(12,300);
        Console.Write(“My point is created at: “);
        Point.DisplayMyPoint(myPoint);
    }
}

Notes about the preceding example:
I.    If we don’t implement all the members of the interface, we get a compilation error. Try commenting the properties (Myx and Myy) in the class to see the compiler error message.
II.    Notice also that it is possible to pass a parameter of the type IPoint to the method DisplayMyPoint. We can, of course, pass a parameter of the type Point instead.
III.    Notice also that it is possible to pass a parameter of the type IPoint to the method DisplayMyPoint. We can, of course, pass a parameter of the type Point instead.

Declaring an Interface

Declare an interface by using the interface keywords shown in this example:
interface IMyInterface
{
    // interface members
}
The declaration can be modified with a valid combination of access modifiers or the new keyword. It can also be preceded by attributes. The members of an interface can include:
•    Method
•    Properties
•    Indexers
•    Events
The interface cannot, however, contain fields. Interface members are public by default. We cannot use accessibility on them.
The members of an interface are the signatures of methods, properties, indexers, or events. For example:
interface ICounter
{
    void Count(int i);
    int SetCounter();
}
As we can see in this declaration, the interface contains only the names, types, and parameters of methods.
An interface might implement one or more interface, as shown in the following example:
interface IMyInterface: Interface1, Interface2
{
    //interface members
}

Emulating Unions

It is possible to use attributes to emulate unions in C++, as shown in the following example:
[type: StructLayout(LayoutKind.Explicit)]
public struct UnionStruct
{
    [field: FieldOffset(0)]    //offset #0
    public int I;
    [field: FieldOffset(0)]    //offset #0
    public double d;
}
In this example, two attributes are used:
[type: StructLayout(LayoutKine.Explicit)]
[field: FieldOffset(0)]
The first attributes targets the struct, and the second targets a field of the struct. Notice that the words “type” and “field” in these attributes can be omitted because they are obvious.
Using these two attributes, it is possible to store two numbers, an int and a double, in the same memory location. The two numbers are different in size but they both start at offset 0. It is possible, of course, to use any offset, such as FieldOffset(2) or FieldOffset(5). It is also possible to store any number of different types in the same location as long as we don’t use them at the same time. In the following example, more types are added to the union.
//Example 7-8.cs
//Union emulation
using System;
using System.Runtime.InteropServices;
[StructLaout(LayoutKind.Explicit)]
public struct UnionStruct
{
    [FieldOffset(0)]
    public int i;
    [FieldOffset(0)]
    public double d;
    [FieldOffset(0)]
    public char c;
    [FieldOffset(0)]
    public byte b;
}
class MyClass
{
    static void Main()
    {
        unionStruct u = new UnionStruct();
        u.i = 13;
        Console.WriteLine(“Integer = {0}”, u.i);

        u.d = 12.34;
        Console.WriteLine(“Double = {0}”, u.d);
        u.c = (char)65;
        Console.WriteLine(“Character = {0}”, u.c);
        u.b = 127;
        Console.WriteLine(“Byte = {0}”, u.b);
       
    }
}

Calling Native Functions

To call a naïve function (outside the .NET Framework), such as MessageBoxA, use the DllImportAttribute attribute like this example:
[DllImport(“user32.dll”)]
To use this function in our C# program, do the following:
1)    Declare the function as a C# method by using the two modifiers extern and static:
static extern int MessageBox(int h, string m, string c, int type);
2)    Add the attribute DllImport right before the declaration:
[DllImport(“user32.dll”)]
static extern int MessageBoxA(int h, string m, string c, int type);
This attribute tells the program that the required function exists in the library user32.dll.
3)    Add the following directive to our program:
using System.Runtime.InteropServices;
Example shows the complete program, which results in a message box titled “My Message Box” that contains the phrase “Hello, World!”
//Example 7-7.cs
//Calling native functions
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
    [method: DllImport(“user32.dll”)]
    static extern int MessageBoxA(int h, string m, string c, int type);
    static ing Main()
    {
        return MessageBoxA(0, “Hello, World!”, “My Message Box”, 0);
    }
}

Combining Attributes

Attributes can be grouped or combined. For example, we can group the two attributes Obsolete and Conditional as shown in this example:
[Obsolete]
[Conditional (“TRACE”)]
We can also combine the attributes by listing them inside a pair of square brackets and separating them with commas:
[Obsolete, Conditional (“TRACE”)]
We can also combine the two styles together as shown in this example, which used three attributes:
[Serializable]
[Obsolete, Conditional (“TRACE”)]
The following example demonstrates combining attributes.
//Attribute example
#define TRACE
using System;
using System.Diagnostics;
public class MyClass
{
    [Obsolete(“Please use MyNewMethod.”, false)]
    [Conditional(“TRACE”)]
    public void MyMethod(string s)
    {
        Console.WriteLine(s);
    }
    static void Main()
    {
        MyClass mc = new MyClass();
        mc.MyMethod(“The conditional method is executed.”);
        Console.WriteLine(“End execution.”);
    }
}

The Conditional Attribute

This attribute is in the namespace System.Diagnostics. It is used to execute a method if a specific constant is defined in the program. For example:
[Conditional(“MYCONSTANT”)]
Public void MyMethod(string s) { }
MyMethod is only executed if the constant MYCONSTANT is defined in the program with a preprocessor directive:
#define MYCONSTANT
If the constant is not defined, the execution resumes and the attribute are ignored. The target method must be of the void type.

Attribute Parameters

Consider this example, which indicates a deprecated method by applying the ObsoleteAttribute attribute:
[Obsolete]
public static void MyMethod()
{
    //The body of the obsolete method.
}
When MyMethod is executed, we get the warning:
‘MyClass.MyMethod()’ is obsolete.
Some attributes such as Obsolete allow the programmer to provide extra information on using the deprecated method. We can do this by using the following modified version, which includes two parameters:
[System.Obsolete(“Use MyNewMethod instead.”, false)]
public static void MyMethod()
{
    //The body of the obsolete method.
}
When we compile this method, the compiler generates the warning:
‘MyClass.MyMethod()’ is obsolete: ‘Use MyNewMethod instead.’
The first parameter contains the string message that we would like to add. The second parameter causes the compilation to generate either an error or a warning, depending on whether it is false or true. The default value is false.

Attributes

Attributes are additional declarative information that can modify the declaration of program entities (types, members, parameters, and so forth). At run time the compiler can retrieve this information through a process called reflection. Attributes can be either predefined or user – defined. In most cases, programmers use the predefined attributes. Attributes server different purpose, such as marking a method as deprecated, indicating conditional compilation, setting a type layout, and so forth.
Attributes are derived from the abstract class System.Attribute, which defines the services of attributes. By convention, all attributes have the suffix Attribute, sucha as DIIImportAttribute. We can skip the suffix and just use the attribute alias, which is DllImport.
The attribute is written between brackets like this example:
[method:DllImport(“user32.dll”)]
Notice that brackets are part of the attribute syntax. Do not confuse these brackets with those that indicate the optional part of the syntax.
The word “method” in this in this attribute represents the target to which the attribute is applied. In this example, the attribute applied is to a method in the library user32.dll. In most cases, the target is opetional; it is necessary only if there is ambiguity. For instance, add the target if the attribute can be applied to a method or a return type.
In this example, the attribute is written without the target element:
[DllImport(“user32.dll”)]
Target elements can be any of the following:
•    assembly
•    field
•    event
•    method
•    parameter
•    property
•    return
•    type
When using an attribute, either qualify its name or use the appropriate using directive. The following are some commonly used attributes that exist in various namespaces:
•    System.Obsolete.Attribute
•    System.Diagnostics.ConditionalAttribute
•    System.Runtime.InteropServices.DllImportAttribute
•    System.Xml.Serialization.XmlArrayAttribute

Using .NET Methods with enums

If we have an enum like this one:
enum Color { Red = 1, Green, Blue };
We can declare a blue color object using the following statement:
Color c = Color.Blue;
We can display the name of this element simply by using the ToString method like this:
Console.WriteLine( c );
This statement displays the string Blue.
We can also use the methods of the System.Enum structure. This structure includes various methods to process enums. One useful method, which is used to display the name of any enum element, is GetName. If we declare a general Color object like this:
Color c = new Color();
We can use this method to display a specific element by using its numeric value. For example, we can display the name of the element whose value is 2 by using the following statement:
Console.WriteLine(Enum.GetName(c.GetType(),2));
This statement displays the string Green.
Another useful method is GetNames. It stores the names of the enum elements in a string array. For example, we can store all the Color names in an array like this:
string[] colorNames = Enum.GetNames(c.GetType());
We can then display this array by using a repetition loop.
These methods are demonstrated in the following example.
//Example 7-5.cs
//Using System.Enum methods
using System;
//Declare the Color enum:
enum Color { Red = 1, Green, Blue }
class MyClass
{
    static void Main()
    {
        //Declare a blue color object:
        Color myColor = Color.Blue;
        //Display the color name using ToString:
        Console.WriteLine(“My color is: {0}”, myColor);     //Blue

        //Declare a color object:
        Color yourColor = new Color();
        //Display the color whose value is 2 by using the GetName method:
        Console.WriteLine(“Your color is : {0}” , Enum.GetName(yourColor.GetType(), 2));    //Green
        //Display all the color names using the GetNames method:
        Console.WriteLine(“Your colors are: “);
        //Declare a string array for colors:
        string[] colorNames = Enum.GetNames(yourColor.GetType());
        foreach(string s in colorNames)
            Console.WriteLine(“{0}”, s);
    }
}

Using Enumerations

In order to use one of the enumerators, we must qualify it with the enumeration name. For example, the elements of the WeekDays enumeration are WeekDays.Sun, WeekDays.Mon, and so forth.
However, to convert an enum element to an integral type we must use a cast. For example:
int monday = (int) WeekDays.Mon;
long monday = (long) WeekDays.Mon;
In the following example, we declare three enumerations for WeekDays, Seasons, and Grades, This example demonstrates the various enumeration rules explained in the preceding sections.
//Example 7-4
//enum example
using System;
enum WeekDays {Sum, Mon, Tue, Wed, Thu, Fri, Sat };
enum Seasons { Summer = 1, Fall, Winter, Spring };
enum Grades { Pass = 65, Good = 75, VeryGood = 85, Distinct = 100 };
class MyClass
{
    static void Main()
    {
        int Sunday = (int) WeekDays.Sun;
        short summer = (short) Seasons.Summer;
        byte vGood = (byte) Grades.VeryGood;
        Console.WriteLine(“Sunday = {0}”, sunday);
        Console.WriteLine(“Summer = {0}”, summer);
        Console.WriteLine(“Very Good = {0}”, vGood);
    }
}

Declaring Enumerations

We can declare the enumeration by using the enum keyword, as shown in the following example that enumerates the seasons of the year:
enum  Seasons{ Summer, Fall, Winter, Spring };
Each enumeration element (enumerator) has a value. The value of the first enumerator is 0 by default. The value of each successive element is incremented by 1. Thus the values of the elements in this enum are:
enum Seasons
{
    Summer,    //0
    Fall,        //1
    Winter,    //2
    Spring    //3
};
We can force the elements to start at 1 as in this example:
enum Seasons { Summer = 1, Fall, Winter, Spring };
In this enumeration, the values of the successive elements are indicated below:
enum Seasons
{
    Summer = 1,
    Fall,        //2
    Winter,     //3
    Spring    //4
};
We can assign a value to any element – not necessarily the first one:
enum WeekDays { Sat, Sun, Mon = 9, Thu, Wed, Thu, Fri };
This will make the values of the elements that follow Mon 10, 11, 12, and 13. However, Sat and Sun will still be 0 and 1.
We can also assign integers to the elements as appropriate. In this example, scores that correspond to grades are assigned:
enum Grades { Pass = 65, Good = 75, VeryGood = 85, Distinct = 100 };
We can choose another underlying type rather than int, such as long, if we need to use numbers in that range for the elements:
    enum Color: long {Red, Green, Blue};
The enumeration identifier is followed by a colon and then the underlying type.

Enumerations

The enumeration type is a value type used to store a set of named constants such as days of the week, months of the year, and so forth, Each enumeration has an underlying type (also called the base type), which can be any one of the integral types (byte, sbyte, short, ushort, int, uint, long, or ulong). The default underlying type is int. The enumeration is usually referred to as enum.

Passing Structs and Classes to Methods

Structs, being value types, are created on the stack. When passed to methods, they are passed by value. Since classes are reference types, they are created on the heap. When passed to methods, they are passed by reference.
The following example demonstrates this concept. In the example, we declare a class called MyClass and a struct called MyStruct. Then we instantiate the class and the struct and initialize the field in each with value 555. We pass both objects to the methods MyMethod1 and MyMethod2 to change their fields to 100. The output, however, indicates that the field of the class has changed but not that of the struct.
//Example7-3.cs
//Passing struct & class objects to methods
using System;
class MyClass
{
    public int classField;
}
struct MyStruct
{
    public int structField;
}
class MainClass
{
    public static void MyMethod1(MyStruct s)
    {
        s.structField = 100;   
    }
    public static void MyMethod2(MyClass c)
    {
        c.classField = 100;
    }
    static void Main()
    {
        //Create class and struct objects:
        MyStruct sObj = new MyStruct();
        MyClass cObje = new MyClass();
        //Initialize the values of struct and class objects:
        sObj.structField = 555;
        cObj.classField = 555;

        //Display results:
        Console.WriteLine(“Results before calling methods:”);
        Console.WriteLine(“Struct member = {0}”, sObj.structField);
        Console.WriteLine(“Class member = {0}\n”,cObj.classField);

        //Change the values through methods:
        MyMethod1(sObj);
        MyMethod2(cObj);
        //Display results:
        Console.WriteLine(“Results after calling methods:”);
        Console.WriteLine(“Struct member = {0}”, sObj.structField);
        Console.WriteLine(“Class member = {0}” , cObj.classField);
    }
}

Declaring and Using Structs

To declare a struct, use the keyword like this example:
struct MyStruct
{
    //The struct members
}
We can modify the declaration with any valid combination of access modifiers or the new keyword. When we use a struct, keep in mind the following points:
•    Unlike classes, the fields of a struct cannot be initialized. That means that the following statements will generate error messages:
struct MyStruct
{
int x = 0; //error
int y = 0; //error
}
•    A struct can use one or more constructors, but we cannot declare a default constructor (parameter less constructor) for a struct. Thus, the following constructor is invalid:
struct MyStruct
{
    MyStruct()    //error
    {
        //….
    }
}
The compiler always provides a default constructor to initialize the members of a struct to their default values.
•    Like classes, we can use the new operator to create struct objects as shown in the following example:
MyStruct ms = new MyStruct();
Unlike classes, we can declare an object without the new operator, like this:
MyStruct ms;
In the latter case, we must initialize the struct fields before using it.
As mentioned in the preceding chapters, a struct cannot be inherited or inherit from another type but it can implement one or more interfaces. For example:
struct MyStruct: IMyInterface
{
    //….
}
Although structs cannot inherit other types, the struct type itself descends from the Object class.
The following example demonstrates the Color struct, which contains three fields (r, g, and b) representing the three basic colors (red, green, and blue). The program uses a constructor to create two objects with different colors.
//Example 7-1.cs
//struct example
using System;
public struct Color
{
    //Fields:
    private int r;
    private int g;
    private int b;

    //Constructor:
    public Color(int r, int g, int b)
    {
        this.r = r;
        this.g = g;
        this.b = b;
    }
    //Overriding the method ToString():
    public override string ToString()
    {
        return (String.Format(“Red = {0}, Green = {1}, Blue = {2}”, r, g, b));
    }
   
}
class MyClass
{
    static void Main()
    {
        //Declare objects:
        Color c1 = new Color();     //uses the default values
        Color c2 = new Color(100,100,0);
        //Display objects:
        Console.WriteLine(“The first object:”);
        Console.WriteLine(“The colors are: {0}”, c1);
        Console.WriteLine(“The second object: “);
        Console.WriteLine(“The colors are: {0}”, c2);
    }
}
In the above example, two struct instances, c1 and c2, were used. The first one uses a default constructor; therefore, all of its fields contain the value zero. The second instance is constructed using the parameters 100,100 and 0. These values are assigned to the fields r, g, and b.
The objects are displayed directly by using the statement:
Console.WriteLine(“The colors are: {0}”, c1);
This requires overriding the ToString method to display objects in the appropriate format.
In the following example, the three properties R,G, and B are used to access the private fields r, g, and b. This makes it possible to access the fields directly through the properties, which is an alternative to using constructors.
//Example 7-2.cs
//Using properties with structs
using System;
public struct Color
{
    //Fields:
    private int r;
    private int g;
    private int b;
    //Properties:
    public int R
    {
        get { return r; }
        set { r = value; }
    }
    public int G
    {
        get { return g; }
        set { r = value; }
    }
    public int G
    {
        get { return g; }
        set { g = value; }
    }
    public int B
    {
        get { return b; }
        set { b = value; }
    }
    //Override ToString():
    public override string ToString()
    {
        return (String.Format(“Red = {0}, Green = {1}, Blue = {2}”, R, G, B));
    }
}
class MyClass
{
    static void Main()
    {
        Color c1 = new Color();
        Console.WriteLine(“The colors are: {0}”, c1);
        c1.R = 100;
        c1.G = 100;
        c1.B = 0;
        Console.WriteLine(“The colors are: {0}”, c1);
    }
}
Notice in the above example that we used one object created with the default constructor. Then we used the color properties to assign color values to the corresponding fields:
    c1.R = 100;
    c1.G = 100;
    c1.B = 0;
The object was displayed twice – once with the default values and once after assigning the values to the properties. We can, of course, use a constructor with three parameters to achieve the same result.

Structs vs. Classes

The word “struct” originally an abbreviation of structure, has become a part of the programming terminology of structure, has become a part of the programming terminology. In C#, the struct is a user – defined value type. It might, however, contain members of both reference types and value types.
The struct is used to represent lightweight objects such as a point, which contains two fields( x and y). It also represent a color, which contains three fields (red, blue, and green). Although we use the Point class in the examples, the struct is a more suitable type for such objects as it consumes a small amount of memory. We can see the difference if we create a large array of points represented as classes. In this case, the required memory would be huge because each point is using a reference that points to it.

Tuesday, March 23, 2010

Overriding the ToString Method

The ToString method is one of the most important methods in the .NET library as it always works in the background with the methods Console.WriteLine. It is used to convert an expression to a string. As we know , we can use it explicitly like this:
Console.WriteLine(myVariable.ToString());
but if we omit the ToString method, which is always the case since it is embedded, we still get the same result.
This method is an override method defined in the class Sustem.AppDomain as follows:
public override string ToString();
In some cases we might need to override it to change its behavior, such as when we would like to display an object as if it were a regular variable. Instead of displaying a Point object like this (as in the example above):
Console.WriteLine(“Point #1: {0}, {1})”, p1.x,p1.y);
We can display it like this:
Console.WriteLine(“Point #1: {0}”,p1);
To do that, we must override the method ToString to be able to display objects of the type Point. Here is an example of the code to do this:
//Overriding the ToSting method:
public override string ToString()
{
    return (String.Fromat(“({0},{1})”,x,y));
}
In this code segment, the String.Format method replaces the format items, {0} and {1}, with the text equivalent to the value of the specified objects, x and y. Thus, the output of this method would be the values of the point (x,y). We can add this method to the preceding example and display the Point objects directly as single variables.

User – defined Operators

By using overloading, we can invent new roles for some operators. The need for this feature arises when we deal with objects. In some cases, we might want to test the equality between two objects using the equality operator(==). In this case, we redefine the equality operator in our program to make it work with objects.
Operator overloading is accomplished by using the keyword operator, as shown in the following example:
public static Point operator+ (Point p1, Point p2)
{
    //Implementation of the + operator:
}
This example overloads the + operator in order to use it in adding two objects of the type Point.
Adding two points means adding the x and y coordinates of each point. If the coordinates of the first point are (x1,y1) and the coordinates of the second point are (x2,y2), the result is a new point at the location (x1+x2, y1+y2). These details should be included in the implementation of overloading the operator+.
Notice in the syntax that the redefined + operator follows the keyword operator. Other examples are:
operator+
operator-
operator==
The method used for operator overloading is always static.
 The operators that are classified as binary operator on two operands, such as + and *. The operators that are classified as unary operate on one operand, such as ++ and --.
The following example overloads the + operator to add two points, p1 and p2, and displays the coordinates of the resulting point.
//Example 6-9.cs
//Overloading operators
using System;
public class Point
{
    public int x;
    public int y;
    //Constructor:
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
    //Overloading the + operator:
    public static Point operator+ (Point p1, Point p2)
    {
        //Return the sum as a point:
        return new Point(p1.x + p2.x, p1.y + p2.y);
    }
    static void Main()
    {
        Point p1 = new Point(15,33);
        Point p2 = new Point(10,12);
        //Add the two Point objects using the overloading + operator:
        Point sum = p1 + p2;
        //Display the objects:
        Console.WriteLine(“Point #1: ({0}, {1})”, p1.x, p1.y);
        Console.WriteLine(“Point#2: ({0},{1})”.p2.x,p2.y);
        Console.WriteLine(“Sum of the two points: ({0}, {1})”, sum.x, sum.y);
    }

}

Indexers

Using indexers, we can treat classes as if they were arrays or collections; that is, we can access the indexer’s elements by using square brackets ([]).  An indexer is similar to properties in that it also uses the accessors get and set to express its characteristics.
The declaration of the indexer takes the form:
indexer  - type this [parameter – type parameter]
{
    get {};
    set {};
}
Where:
indexer – type is the type of the indexer.
parameter – type is the type of the parameter.
parameter is a parameter or a parameter list.
The keyword this points to the object to which the indexer belongs.
Although the indexer doesn’t have a name, it is recognized by its signature (types and number of parameters). It is possible to modify the indexer declaration with the keyword new or one of the access modifiers.
In the following example, we declare an array and an indexer of the type string. Then the indexer is used to access the elements of the object as if they were array elements.
//Example 6.8.cs
//Indexer example
using System;
class MyClass
{
    private string[] myArray = new string[10];
    //Indexer declaration:
    public string this[int index]
    {
        get
        {
            return myArray[index];
        }
        set
        {
            myArray[index] = value;
        }
    }
}
public class MainClass
{
    public static void Main()
    {
        MyClass s = new MyClass();
        //Using the indexer to initialize the element #1 and #2:
        s[1] = “Tom”;
        s[2] = “Edison”;
        for ( int i = 0; i<5; i++)
        {
            Console.WriteLine(“Element #{0}={1}”, i, s[i]);
        }
   
    }
}
Notes on using indexers:
•    It is common to use the accessors set and get in inspecting the limits of the indexer to avoid errors.  For example:
if(!(index < 0 || index >= 10))
//…
•    It is possible for interfaces to have indexers. They are declared in the same way with the following exceptions:
o    Interface indexers don’t use modifiers.
o    There is no implementation of accessors in interfaces.
The following is an example of an interface indexer:
string this [int index]
{
    get;
    set;
}

Various Ways to Pass Parameters to Methods

There is more than one way to pass parameters to a method by reference. There are three parameter modifiers, each of which results in saving the changes of the variable values after the method returns to the caller. The three modifiers are:
•    ref
•    out
•    params
•    ref: -
As we have seen in the preceding examples, the ref keyword is used to pass variables to a method and reflect back the changes that occurred on the original variables. When we use ref to pass a variable to a method, the variable must be initialized first; otherwise, we will get a compiler error. For example:
string myVariable = “This my string”;    //initialize the variable
MyMethod(ref myVariable);        //invoke the method

When the method returns the variable, myVariable will retain the changes that occurred to it in MyMethod.

•    out: - The out keyword does the same work as the ref keyword when used as a parameter modifier. It does not require initializing the variable before passing it to the method, but it does require initializing the variable in the method itself. For example, the method might look something like this:
    void MyMethod(out string myVariable)
    {
        myVariable = “This is my string”;
    }
In order to call this method, use the out keyword:
    MyMethod(out myVariable);
The variable myVariable might not be initialized at all. It will be assigned the vale “This is my string” when the method returns to the caller. Notice that the out keyword is used in both the method header and the call.
It is possible to use more than one parameter, as in this example:
void YourMethod(out int x, out int y, out int z)
{

}
This method is called in the same way:
YourMethod(out m, out n, out l);
Note: - It is not enough to have different parameter modifiers in order to overload a method. Methods must also be different in the type of parameters they use.
In the following example, the out keyword is used to pass an uninitialized array to the method MyMethod. When the method returns to Main, its elements are initialized.
//Example 6-6.cs
//Out Example
using System;
public class MyClass
{
    public static void MyMethod(out int[] myList)
    {
        myList = new int[] {1945, 1966, 1987, 1997}; // initialize the array
    }
    public static void Main()
    {
        int [] myarray; //declare an uninitialized array
        MyMethod(out myarray); //pass it as a parameter

        //Display the array:
        for ( int i = 0; i < myarray.Length; i++)
            Console.Write(“{0} “, myarray[i]);
    }
}
Notice in the example above that MyMethod was declared static in order to be called directly without the need to create an object.
•    params: -The keyword params is used with arrays. It lets we pass any number of parameters to a method without the need to declare them in an array. This keyword is required only in the method declaration. For example, the method:
    static void MyMethod(params object[] myObjArray)
              Can be called like this:
    MyMethod(123,’A’, “My original string”);
The parameters passed in this call are all of the type object, which means they can include any types descended from the object class.
Consider also the following method:
static void MyMethod(params int[] myIntArray)
This method can be called by passing a group of integers that constitute an integer array regardless of its length, for example:
MyMethod(2,4,7);
Any method that uses the params keyword cannot use more than one parameter.
In the following example, the use of the params keyword in the declaration of the method is demonstrated. It also demonstrates the overloading of two methods with the same name and different parameters. One method uses an object array and the second method uses an integer array.  Both methods change the content of the array passed to it. The content of each array is displayed before and after the change takes inside the method.
//Example6-7.cs
//params and overloading example
using System;
public class MyClass
{
    //Declare MyMethod that uses integer parameters:
    public void MyMethod(params int[] myIntArray)
    {
        //Display the integer array before the change:
        Console.WriteLine(“My original integer list:”);
        for(int i = 0; I < myIntArray.Length; i++)
        {
            Console.WriteLine(myIntArray[i]);
        Console.WriteLine();

        //Changing the second array element:
        myIntArray[1] = 555;
        //Display the integer array after the change:
        Console.WriteLine(“My integer list after the change:”);
        for(int i = 0 ; i < myIntArray.Length; i++)
            Console.WriteLine(myIntArray[i]);
        Console.WriteLine();
        }
    //Declare MyMethod that uses object parameters:
    public void MyMethod(params object[] myObjArray)
    {
        //Display the object array before the change:
        Console.WriteLine(“My original object list:”);
        for(int i =0; i < myObjArray.Length; i++)
            Console.WriteLine(myObjArray[i]);
        Console.WriteLine();
        //Changing the third array element:
        myObjArray[2] = “My new string”;
        //Display the results after the change:
        Console.WriteLine(“My object list after the change:”);
        for(int i = 0; i < myObjArray.Length; i++)
            Console.WriteLine(myObjArray[i]);
        Console.WriteLine();
    }
}
class MainClass
{
    static void Main()
    {
        //Declare an object array:
        object[]  myObjList = new object[] {123,’A’, “My old string”};
        MyClass mc = new MyClass();
        //Pass four integers to the “first” MyMethod:
        mc.MyMethod(11,22,33,44);    //using numeric parameters
        //Pass an object array to “second” MyMethod:
        mc.MyMethod(myObjList);    //using an object array
    }
}

Passing Parameters to Methods

In C#, there are two ways to pass a parameter to a method: by value (which is the default) or by reference. Passing parameters by reference makes the changes to the variable values persist. To pass a parameter by reference, modify the parameter with the ref keyword.
The following example demonstrates swapping the values of two variables.
//Example 6-4.cs
//Swap method example – successful trial
using System;
class MyClass
{
    static void Swap(ref int x, ref int y)
    {
        int temp = x;
        x = y;
        y = temp;
    }
    static void Main()
    {
        int x = 25;
        int y = 33;
        Console.WriteLine(“Before swapping: x ={0}, y = {1}”, x,y);
        Swap(ref x, ref y);
        Console.WriteLine(“After swapping: x = {0}, y = {1}” , x, y);
       
    }
}
As we can see in the preceding example, the Swap method is using the ref keyword to modify the parameters in both the method header and the method call. This method did swap the two variables, as in indicated in the output.
In the following example, take a look at how this function will behave if we pass the parameters by value – without the keyword ref.
//Example 6-5.cs
//Swap method example – unsuccessful trial
using System;
class MyClass
{
    static void Swap(int x, int y)
    {
        int temp = x;
        x = y;
        y = temp;
        Console.WriteLine(“Values inside the method: x = {0} , y = {1}” , x ,y);
    }
    static void Main()
    {
        int x = 25;
        int y = 33;
        Console.WriteLine(“Before swapping : x = {0}, y = {1}”, x, y);
        Swap(x,y);
        Console.WriteLine(“After swapping: x={0}, y = {1}”, x, y);
    }
}
As we can see in the output, the values of x and y did not change after invoking the Swap method. The change took place only inside the method, but when the method returned to the caller, the values were the same.

Tuesday, March 16, 2010

Method Overloading

Overloading methods means that we can give the same name to more than one method and let the compiler load the appropriate method according to the number and type of parameters. It might be suitable to use method overloading if the purposes of the methods are similar. For example, if we would like to create one method to return the square root of an integer and another to return the square root of a real number, we would use the same name for both methods:
int  SquareIt(int x)
double SquareIt(double f)
Then if we use the following call:
SquareIt(3.25);
The compiler will invoke the method SquareIt(double f), which uses a real parameter.
When we use the following call:
SquareIt(44);
The compiler will invoke the method SquareIt(int x), which uses an integer parameter.
The return type does not have any effect on overloading. That means that methods might have similar names and return types, but the compiler can still differentiate between them as in the following example:
void SquareIt(int x)
void SquareIt(double f)
Note: - The binding between the specific method and the call is done at compile time, before the program runs. This is called static or early binding, as opposed to dynamic or late binding used with virtual methods.
It is also possible to overload methods that use the same type but a different number of parameters. For example:
void MyMethod(int m1) { }
void MyMethod(int m2, int m3) { }
One important use of overloading is operator overloading to invent new uses for operators.
In the following example, three methods use the name MyMethod, but each uses different parameters. The three methods are called from within the Main method and generate three different results.
Example 6-3
//Example 6-3.cs
//Overloading methods
using System;
class MyClass
{
    //Using a string parameter:
    static void MyMethod(string s1)
    {
        Console.WriteLine(s1);
    }
    //Using an integer parameter:
    static void MyMethod(int m1)
    {
        Console.WriteLine(m1);
    }
    //Using a double parameter:
    static void MyMethod(double d1)
    {
        Console.WriteLine(d1);
    }
    static void Main()
    {
        string s = “This is my string”;
        int m = 134;
        double d = 122.67;
   
        MyMethod(s);
        MyMethod(m);
        MyMethod(d);
    }
}

Abstract Classes and Methods

The purpose of an abstract class is to be inherited by other classes. It cannot be instantiated. The abstract method is, by default, a virtual method. It can exist only inside an abstract class.
Declare abstract classes or abstract methods using the abstract keyword as in this example:
abstract class MyBaseClass            //abstract class
{
    public abstract void MyMethod();  //abstract method
}
The abstract class might contain abstract methods and properties. When an abstract class is inherited, the derived class must implement all of its methods and properties. As we can see in the code segment above, the abstract method doesn’t contain any implementation. The implementation goes inside the overriding methods of the derived classes.
The following keywords are not allowed in the abstract method declaration:
•    static
•    virtual
Abstract properties are similar to abstract methods except in the way they are declared. The following example demonstrates abstract classes, methods, and properties.
//Example 2-2.cs
//Abstract classes, methods, and properties
using System;
//Abstract class:
abstract class MyBaseClass
{
    //Fields:
    protected int number = 100;
    protected string name = “Dale Sanders”;
    // Abstract method:
    public abstract void MyMethod();
    //Abstract properties:
    public abstract int Number
    { get; }
    public abstract string Name
    { get; }
}
// Inheriting the class:
class MyDerivedClass : MyBaseClass
{
    //Overriding properties:
    public override int Number
    {
        get { return number; }
    }
    public override string Name
    {
        get { return name; }
    }
    // Overriding the method:
    public override void MyMethod()
    {
        Console.WriteLine(“Number = {0}”, Number);
        Console.WriteLine(“Name = {0}”, Name);
    }
}
class MainClass
{
    public static void Main()
    {
        MyDerivedClass myObject = new MyDerivedClass();
        myObject.MyMethod();
    }
}
Note: - We now know that the override methods can override other override methods. That means that we can add another override method named MyMethod to a new class derived from MyDerivedClass. For example:
class MySecondDerivedClass : MyDerivedClass
{
    public override void MyMethod()
    {
        //Method implementation.
    }
}

Calling Members of the Base class

Sometimes when we inherit a class, the methods in the derived class can override methods in the base class. What if we wanted to call one of the overridden methods from within the derived class? The keyword base is the solution to this problem. To call an overridden method, such as GetInformation, we can call it by using this statement:
Base.GetInformation();
This statement calls the original GetInformation method, which was overridden by a method with a similar name in the derived class.
Note: - We cannot use the keyword base inside a static method.

In other cases, we need to build the object of the base class before we build the object of the derived class. We can also do that using the base keyword like the following example:

public MyDerived(int x) : base(x)
{
    //…
}
This is the constructor of the class MyDerived, which builds the base class object on the fly. We need to do this in cases when constructing the base class is necessary to construct the derived class. For example, let’s say the base class represents the area of a circle, and the derived class represents an area of a sphere (which uses the area of a circle). In this case, we must instantiate the area of the circle before we can instantiate the area of the sphere.
Example: -
//Example 6-1
//Virtual Example
using System;

//The base class:
public class AreasClass
{
    //Fields:
    protected double x,y;

    //Constructors:
    public AreaClass()
    {
    }
    public AreaClass(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
    //Methods:
    public virtual double Area()
    {
        return 0;
    }
   
}
//The point class uses a parameter less constructor:
class  Point: AreasClass
{
    public Point() : base()
    {
    }
}
//The Circle class:
class Circle: AreasClass
{
    public Circle(double r) : base (r,0)
    {
    }
    public override double Area()
    {
        //The area of a circle.
        //The radius is represented by x:
        return Math.PI *  x * x;
    }
}
//The Sphere class:
class Sphere: AreasClass
{
    public Sphere(double r): base(r,0)
    {
    }
    public override double Area()
    {
        //The radius is represented by x:
        return 4 * Math.PI * x * x;
    }
}
//The Cylinder class:
class Cylinder: AreaClass
{
    public Cylinder(double r, double h) : base (r, h)
    {
    }
    public override double Area()
    {
        //The radius is represented by x and
        //the height is represented by y:
        return 2 * Math.PI * x * x + 2 * Math.PI * x * y;
    }
}
class MyClass
{
    public static void Main()
    {
    //Receive number from the keyboard:
    Console.WriteLine(“Please enter the radius: “);
    double radius= Convert.ToDouble(Console.ReadLine());
    Console.WriteLine(“Please enter the height: “);
    double height = Convert.ToDouble(Console.ReadLine());

    //Create objects:
    Point myPoint = new Point();
    Circle myCircle = new Circle(radius);
    Sphere myShpere = new Sphere(radius);
    Cylinder myCylinder = new Cylinder(radius, height);
    //Display results:
    Console.WriteLine(“Area of our point = {0:F2}”, myPoint.Area());
    Console.WriteLine(“Area of our circle ={0:F2}”, myCircle.Area());
    Console.WriteLine(“Area of our sphere = {0:F2}”, myShpere.Area());
    Console.WriteLine(“Area of our cylinder = {0:F2}”, myCylinder.Area());
    }
}

Virtual and Override Methods

To use the polymorphic methods introduced in the preceding section, declare the DrawWindow method with the keyword virtual in the base class:
public virtual void DrawWindow()
{
       //The method definition in the base class.
}
Then, in each of the classes that inherit the base class, declare a DrawWindow method using the keyword override:
public override void DrawWindow()
{
    //The method definition in one of the derived classes.
}
The method declared with the keyword override is called an override method. It can override another method that has the same name, signature, and accessibility in the base class. When we override a method, we can change its original behavior in the derived class. An override method can override any of the methods declared with the following modifiers:
•    Virtual
•    Abstract
•    Override
When a virtual method in a derived class has the same name, accessibility, and signature as that of another method in the base class but is not qualified with the override modifier, it simply hides the method of the base class. To make the method override the one in the base class, you must modifier its declaration with the keyword override. An abstract method is implicitly a virtual method, and therefore, it can be overridden without using the virtual modifier.
Note: we cannot use the virtual modifier with the following modifiers:
Static, abstract, virtual, or new.

Polymorphism

In programming we deal with many kinds of user interface windows in the Microsoft Windows environment, such as message boxes that convey a message or a warning and windows for painting or writing. If you wrote, for example, a method called DrawWindow, we can associate this method with various objects that represent different kinds of windows. Based on the object associated with the method, the result would be different. Consider these examples:
    myButton.DrawWindow();        //draws a button
    myMsg.DrawWindow();        //draws a message box
    myPaintSurface.DrawWindow();    //draws a painting window
The three objects – myButton, myMsg, and myPaintSurface – are not instances of the same class, but instances of other classes derived from the base class that contains the original DrawWindow method. Each object is used to invoke a new definition of the method DrawWindow.

Function Members

 All members of a class or a struct (except fields and constants) are classified as function members.
Function members are:
•    Methods
•    Properties
•    Events
•    Indexers
•    User – defined operators
•    Constructors
•    Destructors

Partial Classes

Partial classes were added to C# 2005 to facilitate breaking a type (class, struct, or interface) into more than one section and each in a separate file. This is useful when writing large projects or using machine-generated code. This feature also helps developer teams to collaborate on the dame application.
To declare a partial class, all sections of the class must use the modifier partial right before the word class. Other modifiers can precede the key –word partial. The following example declares a class called TimeSheet divided into two files: -
//File1.cs
public partial class TimeSheet
{
    public void AddWorkingHours()
    {
        //…
    }
    public void CalcukateSalary()
    {
        //…
    }
}
//File2.cs
public partial class TimeSheet
{
    public void SubtractVacationTime()
    {
        //…
    }
}
On compilation, all sections of the class are put together to create the class. All the sections of course must be included in the same namespace, but cannot span assemblies.
The following rules and restrictions control the use of partial classes:
1)    All partial classes that constitute one class must use the same accessibility level.
2)    If one part of the class is declared using the modifiers abstract or sealed, the modifier will apply to the whole class.
3)    If one partial class is derived from a base class, all the other partial classes will inherit this base class even if is not mentioned in their declarations. This means that if we have two partial classes, as in this example:
partial class Employee: Person
{
    //…
}
partial class Employee: Citizen
{
    //…
}
The class Employee would effectively be:
class Employee: Person,  Citizen
{
    //…
}
4)    What applies to inheritance from classes applies to implementing interfaces.
The following example consists of two files – file1.cs and file2.cs – that contain a definition of the Employee class. Each file contains part of the class declared as partial. To compile the program, use the following command:
Csc/out:Ex5-14.exe file1.cs file2.cs
This combines the two files, file1.cs and file2.cs, and generates an executable file named Ex5-14.exe.
Example: -
//Example 5-14.cs
//file1.cs
public partial class Employee
{
    private string name;
    private string id;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    public string Id
    {
        get { return id; }
        set { id = value; }
    }
}
file2.cs
//Example 5-14.cs
//file2.cs
using System;
public partial class Employee
{
    public void DisplayInfo()
    {
        Console.WriteLine(“Employee’s name: {0}”, name);
        Console.WriteLine(“Employee’s id: {0}”, id);
    }
}
class MyClass
{
    static void Main(string[] args)
    {
        //Crate object:
        Employee emp = new Employee();
        //Read name and id:
        Console.Write(“Please enter the employee’s name: “);
        emp.Name = Console.ReadLine();
        Console.Write(“Please enter the employee’s id: “);
        emp.Id = Console.ReadLine();
        //Display information:
        emp.DisplayInfo();
    }
}

Destructors

Destructors are used to destruct objects. A destructor is declared as shown in this example:
~MyClass()
{
    //Destruction statements.
}
The destructor of a class uses the same name as the class but is preceded with the tilde (~) character. We cannot, however, call a destructor as it is called automatically when the object finished its work and goes out of scope. In case of inheritance, the destruction starts with the children and goes up in the inheritance tree.
The following example shows how destructors are called to destruct objects in the order of their position in the inheritance hierarchy.
Example: -
//Example 5-13.cs
//Destructor example
using System;
class Parent    //parents
{
    ~Parent()
    {
        Console.WriteLine(“Calling the Parent destructor.”);
    }
}
class Kid: Parent //kids
{
    ~Kid()
    {
        Console.WriteLine(“Calling the Kid destructor.”);
    }
}
class GrandKid: Kid // grandkids
{
    ~GrandKid()
    {
        Console.WriteLine(“Calling the Grandkid destructor.”);
    }
}
public class MyClass
{
    public static void Main()
    {
        GrandKid myObject = new GrandKid();
    }
}
Notice in this example that the grandkid was destructed first, then the kid, and finally the parent.
In C# we don’t need to use them because the garbage collector does that task for our automatically when the objects finish their work and are no longer in use.
In C#, we can still use destructors to clear unmanaged resources such as files and network connections.
Note: We can force the garbage collector to start the cleaning process by using the .NET GC.Collect method, but this is not recommended as it might cause undesirable results.

What is Inheritance

It is possible for a class to inherit another class as in the following example:
class MyDerivedClass: MyBaseClass
{
    // …
}
In this example, we declared the class MyDerivedClass, which inherits the class MyBaseClass. In the declaration, the colon (: ) is used between the name of the derived class and the name of the base class. Inheritance means that the derived class contains all the members of the base class. We can also add new members to the inherited members. For example, the Employee class inherits all the characteristics of the Person class and adds to them the characteristics of an Employee.
The following rules control inheritance:
1.    All members of the base class are inherited (except instance constructors, destructors, and static constructors).
2.    If we declare a member in the derived class with the same name as that in the base class, it hides the member in the base class. In that case, the member of the base class is not accessible through the derived class.
3.    Functions members in the base class can be overridden by those in the derived class, making it possible to exhibit polymorphism.
4.    In C#, a class can inherit from one class only. However, it can implement more than one interface. When a class implements an interface, it “inherits” its members.
5.    Structs cannot inherit from classes or other structs, but they can implement interfaces. They also cannot be inherited.
Note: - Sometimes the expressions specialization and generalization are used to express inheritance. For example, the Cow class specializes the Mammal class, and the Mammal class generalizes the Cow class. The base class is also referred to as superclass or parent class, and the derived class is referred to as the subclass or child class.
In the following example, the class Employee, which inherits from the class Citizen, is demonstrated.
Example: -
//Example 5-12.cs
//Inheritance example
using System;
class Citizen
{
    string idNumber = “111-2345-H”;
    string name = “Pille Mandla”;
    public void GetPersonalInfo()
    {
        Console.WriteLine(“Name: {0}”, name);
        Console.WriteLine(“ID Card Number: {0}”, idNumber);
    }
}
class Employee: Citizen
{
    string companyName = “Technology Group Inc.”;
    string CompanyID = “ENG-RES-101-C”;
    public void GetInfo()
    {
        //Calling the base class GetPersonalInfo method:
        Console.WriteLine(“Citizen’s Information: “);
        GetPersonalInfo();
        Console.WriteLine(“\nJob Information:”);
        Console.WriteLine(“Company Name: {0}”, companyName);
        Console.WriteLine(“Company ID: {0}”, companyID);
    }
}
class MainClass {
    public static void Main()
    {
        Employee E = new Employee();
        E.GetInfo();
    }
}
Notice in this example that all the member methods have the access level public. This is necessary for accessing the class fields.

Read – only Fields

The readonly keyword is used to declare read – only fields. There are only two ways to assign values to read – only fields. The first way is to assign the value in the declaration statement, as in this example:
public readonly int readOnlyInt1 = 55;
The second is to use a constructor, as in this example:
public MyClass()
{
    readOnlyInt1 = 66;
}
The following example demonstrates the read – only fields.
//Example 5-11.cs
// readonly example
using  MyClass
{
    public int myRegularInt;
    public readonly int readOnlyInt1 = 55;
    public readonly int readOnlyInt2;
    public MyClass()
    {
        readOnlyInt2 = 66;
    }
    public MyClass(int l, int m, int n)
    {
        myRegularInt = l;
        readOnlyInt1 = m;
        readOnlyInt2 = n;
    }
}
class MainClass
{
    static void Main()
    {
        MyClass obj1 = new MyClass(11,23,33); //OK
        Console.WriteLine(“obj1 fieds are: {0}, {1}, {2}” , obj1.myRegularInt, obj1.readOnlyInt1, obj1.readOnlyInt2);
        MyClass obj2 = new MyClass();
        obj2.myRegularInt = 44; //OK
        Console.WriteLine (“obj2 fields are: {0}, {1}, {2}”, obj2.myRegularInt, obj2.readOnlyInt1, obj2.readOnlyInt2);
    }    
}
Notice in this example that we cannot change the value of the read – only field in the Main method by using a statement like this:
obj1.readOnlyInt1 = 55; //error
Note:  - The difference between a read – only field and a constant field is that we can change the value of the first by using the allowed ways mentioned above. The constant fields, however, cannot be changed after declaration.

What is constructor?

A class can contain one or more methods to build and initialize objects. These methods are called constructors. Constructors are divided into three categories:
•    Instance constructors
•    Private constructors
•    Static constructors
Instance constructors: -
Instance constructors are the most common and sometimes referred to as just constructors. A constructor is named the same as the class. It is invoked when we create a new object. For example:
Point myPoint = new Point();
The class might also contain a constructor with parameters, such as:
Point myPoint = new Point(int x, int y);
If the class doesn’t contain a constructor, the default constructor is invoked. The default constructor is a parameter less constructor such as Point(). This constructor initialize the created object with default parameters – zero in case of integer fields.
Example: -
//Example 5-9.cs
//Construct example
using  System;
class Point
{
    public int x,y;
    //Default constructor:
    public Point()
    {
        x = 0;
        y = 0;
    }
    // A constructor with parameters
    public Point(int x1, int y1)
    {
        x = x1;
        y = y1;
    }
}
class MyClass
{
    static void Main()
    {
        Point p1 = new Point();
        Point p2 = new Point(2,10);
        Console.WriteLine(“First Point at: ({0}, {1})”, p1.x, p1.y);
        Console.WriteLine(“Second Point at: ({0},{1})”, p2.x,p2.y);
    }
}

Declaring Constructors: -
Although the default parameter less constructor is automatically created by the compiler, we cannot declare one constructor with parameters without declaring the parameter less constructor. The compiler provides the default constructor only if the class does not have any constructors. In other words, in order to use the statement:
Point p1 = new Point();
We must declare a parameter less constructor.
Using this: -
In C# the this keyword is used to access data members in instance constructors (methods or accessors). For example, we can declare the constructor in the preceding example like this:
public Point(int x, int y)
{
    this.x = x;
    this.y = y;
}
In this case, we can use the same names for both fields and parameters (x and y). This is because the expression “this.x” represents the field “x” of the current object, while “x” is the method parameter. It is obvious that the keyword this cannot be used with static constructors or fields.
Private Constructors: -
Private constructors are used with classes that contain only static members. Other classes, except those nested in the same class, are not allowed to crate instances of that class.
Consider the following example:
public class MyClass
{
    private MyClass() { } // private constructor
    public string comapnyName;
    public string employmentDate;
}
In this example, the private constructor is an empty constructor whose job is to prevent the generation of a default constructor for the class. Notice that the private constructor uses the access modifier private, which is a common convention but not necessary because the default access level is private. It is recommended to declare the class as a static class when its members are all static.
Static Constructors: -
A static constructor is used to initialize a class. It is called before any objects are created and before any call to any static member of the class.
In the following example, the static constructor MyClass contains two printing statements. There is also a method, MyMethod, that contains another printing statement. Notice that when MyMethod is called, the static constructor is automatically invoked.
Example: -
//Example 5-10.cs
//Static constructor example
using System;
class MyClass
{
    //Static constructor:
    static MyClass()
    {
        Console.WriteLine(“Hey, I am the static constructor!” + “I am called automatically!”);
    }
    public void MyMethod()
    {
        Console.WriteLine(“Hi, I am MyMehod. I was called after “ + “the static constructor had been invoked!”);
    }
}
class MainClass
{
    static void Main()
    {
        MyClass myObject = new MyClass();
        myObject.MyMehod();
    }
}