C# Basic (3)

1.Read-Only Fields

public readonly int ScreenWidth;

So what does a programmer do when the need arises for a field with a value that won’t be known until run time and should not be changed once it’s been initialized? When you define a field with the readonly keyword, you have the ability to set that field’s value in one place: the constructor. After that point, the field cannot be changed by either the class itself or the class’s clients.

 

2.

To inherit one class from another, you would use the following syntax:

class <derivedClass>: <baseClass>

C# does not support multiple inheritance through derivation.  A class can never be used as a base class, you use the sealed modifier when defining the class. The only restriction is that an abstract class cannot be used as a sealed class because by their nature abstract classes are meant to be used as base classes.

It is better to use private to modifier the elements(not method)

sealed class MyPoint


3.  The only difference between the ref keyword and the out keyword is that the out keyword doesn’t require the calling code to initialize the passed arguments first, while ref should.

using System;

class Color
{
    public Color()
    {
        this.red = 255;
        this.green = 0;
        this.blue = 125;
    }

    protected int red;
    protected int green;
    protected int blue;

    public void GetColors(ref int red, ref int green, ref int blue)
    {
        red = this.red;
        green = this.green;
        blue = this.blue;
    }
}

class RefTest2App
{
    public static void Main()
    {
        Color color = new Color();
        int red = 0;
        int green = 0;
        int blue = 0;
        color.GetColors(ref red, ref green, ref blue);
        Console.WriteLine("red = {0}, green = {1}, blue = {2}",
red, green, blue);
    }
}

 

using System;

class Color
{
    public Color()
    {
        this.red = 255;
        this.green = 0;
        this.blue = 125;
    }

    protected int red;
    protected int green;
    protected int blue;

    public void GetColors(out int red, out int green, out int blue)
    {
        red = this.red;
        green = this.green;
        blue = this.blue;
    }
}

class OutTest1App
{
    public static void Main()
    {
        Color color = new Color();
        int red;
        int green;
        int blue;
        color.GetColors(out red, out green, out blue);
        Console.WriteLine("red = {0}, green = {1}, blue = {2}",
                    red, green, blue);
    }
}

out could be used because the method being called wasn’t dependent on the value of the variable being passed.

using System;

class Window
{
    public Window(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    protected int x;
    protected int y;

    public void Move(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public void ChangePos(ref int x, ref int y)
    {
        this.x += x;;
        this.y += y;

        x = this.x;
        y = this.y;
    }
}

class OutTest2App

{
    public static void Main()
    {
        Window wnd = new Window(5, 5);

        int x = 5;
        int y = 5;

        wnd.ChangePos(ref x, ref y);
        Console.WriteLine("{0}, {1}", x, y);

        x = -1;
        y = -1;
        wnd.ChangePos(ref x, ref y);
        Console.WriteLine("{0}, {1}", x, y);
    }
}

As you can see, the method being called—Window.ChangePos—bases its work on the values being passed in. In this case, the ref keyword forces the caller to initialize the value so that the method will function properly.

 

4. Sometimes the number of arguments that will be passed to a method won’t be known until run time. You can specify a variable number of method parameters by using the params keyword and by specifying an array in the method’s argument list.

using System;

class Point
{
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public int x;
    public int y;
}

class Chart
{
    public void DrawLine(params Point[] p)
    {
        Console.WriteLine("\nThis method would print a line " + 
                          "along the following points:");
        for (int i = 0; i < p.GetLength(0); i++)

        {
            Console.WriteLine("{0}, {1}", p[i].x, p[i].y);
        }
    }
}

class VarArgsApp
{
    public static void Main()
    {
        Point p1 = new Point(5,10);
        Point p2 = new Point(5, 15);
        Point p3 = new Point(5, 20);

        Chart chart = new Chart();
        chart.DrawLine(p1, p2, p3);        
    }
}

The DrawLine method tells the C# compiler that it can take a variable number of Point objects.

 

5.

using System;

class Employee
{
    public void CalculatePay()
    {
        Console.WriteLine("Employee.CalculatePay()");
    }
}

class SalariedEmployee : Employee
{
    // The new keyword enables you to override the 
    // base class' implementation.
    new public void CalculatePay()
    {
        Console.WriteLine("SalariedEmployee.CalculatePay()");
    }
}

class Poly1App
{
    public static void Main()
    {
        Poly1App poly1 = new Poly1App();

        Employee baseE = new Employee();
        baseE.CalculatePay();

        SalariedEmployee s = new SalariedEmployee();
        s.CalculatePay();
    }
}

 

6. Polymorphism enables you to define a method multiple times throughout your class hierarchy in such a way that the runtime calls the appropriate version of that method depending on the exact object being used.

early binding: When the code was compiled, the C# compiler looked at the call to emp.CalculatePay and determined the address in memory that it would need to jump to when the call is made.

Late binding means that the compiler does not select the method to execute until run time.

To force the compiler to call the correct version of an upcasted object’s method, we use two new keywords: virtual and override. The virtual keyword must be used on the base class’s method, and the override keyword is used on the derived class’s implementation of the method.

using System;

class Employee
{
    public Employee(string name)
    {
        this.Name = name;
    }

    protected string Name;
    public string name

    {
        get
        {
            return this.Name;
        }
    }

    virtual public void CalculatePay()
    {
        Console.WriteLine("Employee.CalculatePay called for {0}", 
                          name);
    }
}

class ContractEmployee : Employee
{
    public ContractEmployee(string name)
    : base(name)
    {
    }
    override public void CalculatePay()
    {
        Console.WriteLine("ContractEmployee.CalculatePay called for {0}", 
                          name);
    }
}

class SalariedEmployee : Employee
{
    public SalariedEmployee (string name)
    : base(name)
    {
    }
    override public void CalculatePay()
    {
        Console.WriteLine("SalariedEmployee.CalculatePay called for {0}", 
                          name);
    }
}

class Poly3App
{
    protected Employee[] employees;
    public void LoadEmployees()
    {
        // Simulating loading from a database.
        employees = new Employee[2];

        employees[0] = new ContractEmployee("Kate Dresen");
        employees[1] = new SalariedEmployee("Megan Sherman");
    }

    public void DoPayroll()
    {
        foreach(Employee emp in employees)
        {
            emp.CalculatePay();
        }
    }

    public static void Main()
    {
        Poly3App poly3 = new Poly3App();
        poly3.LoadEmployees();
        poly3.DoPayroll();
    }
}

Running the code at this point should yield the following results:

c:\>Poly3App
ContractEmployee.CalculatePay called for Kate Dresen
SalariedEmployee.CalculatePay called for Megan Sherman

Virtual methods cannot be declared as private because, by definition, they would not be visible in the derived classes.

 

7. Static Methods

using System;

class SQLServerDb
{
    // Bunch of other nonsalient members.
    public static void RepairDatabase()
    {
        Console.WriteLine("repairing database...");
    }
}

class StaticMethod1App
{
    public static void Main()
    {
        SQLServerDb.RepairDatabase();
    }
}

Defining a method as static involves using the static keyword. The user then employs the Class.Method syntax to call the method. Note that this syntax is necessary even if the user has a reference to an instance of the class.

a static method can access any static member within the class, but it cannot access an instance member.

 


Advertisements
This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s