notes of visual basic

Upload: hariom-rai

Post on 09-Apr-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Notes of Visual Basic

    1/41

  • 8/8/2019 Notes of Visual Basic

    2/41

    variables also have a modifieroutwhich can be used before theirtype.

    public static void SumRef(ref int a, ref int b)

    {a = 4;b = 6;Console.WriteLine("The sume of elements {0} and {1} is

    {2}",a,b,a + b);}

    Now this method modifies the value of variables a and b withvalues 4 and 6. These values are retained even after the execution

    of the function gets completed.If the parameters need to be returned then they can bequalified with outmodifier or as returned parameter in methoddefinition. Here is an example of both of them, in which both ofthem return the same value:

    public static int SumOut(int a, int b, out int sum1){

    sum1 = a+b;

    Console.WriteLine("The sum1 of elements {0} and {1} is{2}",a,b,a+b);return sum1;

    }

    In main function it must be called in the next manner:

    int sume ;

    sume = SumeOut(2,2, out sume);

    Constants in C#:

    Constant type of data cannot be changed. To declare a constantthe keyword const is used. An example for the constantdeclaration is: const double PI = 3.1415;

    Values types in C#:

    Value type stores real data. When the data are queried by differentfunction a local copy of it these memory cells are created. It

  • 8/8/2019 Notes of Visual Basic

    3/41

    guarantees that changes made to our data in one function don'tchange them in some other function. Let see at a simple example:

    public class IntClass

    { public int I = 1;}

    Here we have simple class that contains only one public data fieldof integer type. Now have a look on its usage in main function:

    static void Main(string[] args){// test class

    int i = 10;int j = i;

    j = 11;IntClass ic1 = new IntClass();IntClass ic2 = ic1;ic2.I = 100;

    Console.WriteLine("value of i is {0} and j is {1}",i,j);Console.WriteLine();

    Console.WriteLine("value of ic1.I is {0} and ic2.I is{1}",ic1.I,ic2.I);Console.WriteLine();}

    Reference Types in C#:

    In the above example, assume that First we have two value typei and j. Also assume that the second variable is initialized with the

    value of the first one. It creates new copy in memory and after itthe values of these variables will be next:

    i = 10;j = i;

    There are a few more things written in the above example forexplaining the Reference Types in C#. At first, the variable ic1 ofIntClass is created using dynamic memory allocation. Then weinitialize the variable ic2 with value of ic1. This makes both the

    variables ic1 and ic2 referring to the same address. If we change avalue of ic2, it automatically changes the value of ic1.

  • 8/8/2019 Notes of Visual Basic

    4/41

  • 8/8/2019 Notes of Visual Basic

    5/41

    break;

    case Volume.Medium:

    Console.WriteLine("The volume is in the middle.");

    break;

    case Volume.High:Console.WriteLine("The volume has been turned up.");

    break;

    }

    Console.ReadLine();

    }

    }

    Properties and Fields

    Fields and properties represent information that an object contains. Fields are likevariables because they can be read or set directly

    using System;

    publicclass PropertyHolder

    {privateint someProperty = 0;

    publicint SomeProperty

    {

    get

    {

    return someProperty;

    }

    set{

    someProperty = value;

    }

    }

    }

    publicclass PropertyTester

    {

    publicstaticint Main(string[] args){

  • 8/8/2019 Notes of Visual Basic

    6/41

  • 8/8/2019 Notes of Visual Basic

    7/41

    Derived SavingsAccount Class Using protected Members of its Base

    Class: SavingsAccount.cs

    using System;

    classBankAccountPrivate

    {

    privatestring m_name;

    publicstring CustomerName

    {

    get { return m_name; }

    set { m_name = value; }}

    }

    using System;

    classBankAccountProtected

    {

    publicvoid CloseAccount(){

    ApplyPenalties();

    CalculateFinalInterest();

    DeleteAccountFromDB();

    }

    protectedvirtualvoid ApplyPenalties()

    {

    // deduct from account}

    protectedvirtualvoid CalculateFinalInterest()

    {

    // add to account

    }

    protectedvirtualvoid DeleteAccountFromDB()

    { // send notification to data entry personnel

  • 8/8/2019 Notes of Visual Basic

    8/41

    }

    }

    using System;

    classSavingsAccount : BankAccountProtected

    {

    protectedoverridevoid ApplyPenalties()

    {

    Console.WriteLine("Savings Account Applying Penalties");

    }

    protectedoverridevoid CalculateFinalInterest(){

    Console.WriteLine("Savings Account Calculating Final Interest");

    }

    protectedoverridevoid DeleteAccountFromDB()

    {

    base.DeleteAccountFromDB();

    Console.WriteLine("Savings Account Deleting Account from DB");

    }}

    Polymorphism

    When a derived class inherits from a base class, it gains all the methods, fields, properties and events

    of the base class. To change the data and behavior of a base class, you have two choices: you can

    replace the base member with a new derived member, or you can override a virtual base member.

    Replacing a member of a base class with a new derived member requires thenew keyword. If a base

    class defines a method, field, or property, the new keyword is used to create a new definition of that

    method, field, or property on a derived class. The new keyword is placed before the return type of a

    class member that is being replaced. For example:

    publicclass BaseClass

    {

    publicvoid DoWork() { }

    publicint WorkField;

    publicint WorkProperty{

    http://msdn.microsoft.com/en-us/library/51y09td4(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/51y09td4(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/51y09td4(VS.80).aspx
  • 8/8/2019 Notes of Visual Basic

    9/41

    get { return 0; }

    }

    }

    publicclass DerivedClass : BaseClass

    {

    publicnewvoid DoWork() { }

    publicnewint WorkField;

    publicnewint WorkProperty

    {

    get { return 0; }

    }

    }

    When the new keyword is used, the new class members are called instead of the base class members

    that have been replaced. Those base class members are called hidden members. Hidden class

    members can still be called if an instance of the derived class is cast to an instance of the base class.

    For example:

    DerivedClass B = new DerivedClass();

    B.DoWork(); // Calls the new method.

    BaseClass A = (BaseClass)B;

    A.DoWork(); // Calls the old method.

    In order for an instance of a derived class to completely take over a class member from a base class,

    the base class has to declare that member as virtual. This is accomplished by adding the virtual

    keyword before the return type of the member. A derived class then has the option of using the

    override keyword, instead ofnew, to replace the base class implementation with its own. For

    example:

    publicclass BaseClass

    {

    public virtual void DoWork() { }

    public virtual int WorkProperty

    {

    get { return 0; }

    }

    }

    publicclass DerivedClass : BaseClass

    {

    public override void DoWork() { }

    public override int WorkProperty

    {

    get { return 0; }

    }

    http://msdn.microsoft.com/en-us/library/9fkccyh4(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/ebca9ah3(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/9fkccyh4(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/ebca9ah3(VS.80).aspx
  • 8/8/2019 Notes of Visual Basic

    10/41

    }

    Fields cannot be virtual; only methods, properties, events and indexers can be virtual. When a derived

    class overrides a virtual member, that member is called even when an instance of that class is being

    accessed as an instance of the base class. For example:

    DerivedClass B = new DerivedClass();

    B.DoWork(); // Calls the new method.

    BaseClass A = (BaseClass)B;

    A.DoWork(); // Also calls the new method.

    Virtual methods and properties allow you to plan ahead for future expansion. Because a virtual

    member is called regardless of which type the caller is using, it gives derived classes the option to

    completely change the apparent behavior of the base class.

    Virtual members remain virtual indefinitely, no matter how many classes have been declared between

    the class that originally declared the virtual member. If class A declares a virtual member, and class B

    derives from A, and class C derives from B, class C inherits the virtual member, and has the option to

    override it, regardless of whether class B declared an override for that member. For example:

    publicclass A

    {

    public virtual void DoWork() { }

    }

    publicclass B : A{

    public override void DoWork() { }

    }

    A Base Class With a Virtual Method: DrawingObject.cs

    using System;

    publicclass DrawingObject

    { public virtual void Draw()

    {

    Console.WriteLine("I'm just a generic drawing object.");

    }

    }

    Listing 9-1 shows theDrawingObjectclass. This will be the base classfor other objects to inherit from. It has a single method namedDraw().

    TheDraw() method has a virtualmodifier. The virtualmodifier indicatesto derived classes that they can override this method. TheDraw() method

  • 8/8/2019 Notes of Visual Basic

    11/41

    of theDrawingObjectclass performs a single action of printing thestatement, "I'm just a generic drawing object.", to the console.

    Listing 9-2. Derived Classes With Override Methods: Line.cs, Circle.cs,

    and Square.cs

    using System;

    publicclass Line : DrawingObject

    {

    public override void Draw()

    {

    Console.WriteLine("I'm a Line.");

    }

    }

    publicclass Circle : DrawingObject

    {

    publicoverridevoid Draw()

    {

    Console.WriteLine("I'm a Circle.");

    }

    }

    publicclass Square : DrawingObject

    {

    public override void Draw()

    {

    Console.WriteLine("I'm a Square.");

    }

    }

    Listing 9-2 shows three classes. These classes inherit theDrawingObjectclass. Each class has aDraw() method and eachDraw() method has an

    override modifier. The override modifier allows a method to override the

    virtualmethod of its base class at run-time. The override will happenonly if the class is referenced through a base class reference. Overriding

    methods must have the same signature, name and parameters, as the

    virtualbase class method it is overriding.

    Listing 9-3. Program Implementing Polymorphism: DrawDemo.cs

  • 8/8/2019 Notes of Visual Basic

    12/41

    using System;

    publicclass DrawDemo

    {

    publicstaticint Main( ){

    DrawingObject[] dObj = new DrawingObject[4];

    dObj[0] = new Line();

    dObj[1] = new Circle();

    dObj[2] = new Square();

    dObj[3] = new DrawingObject();

    foreach (DrawingObject drawObj in dObj){

    drawObj.Draw();

    }

    return 0;

    }

    }

    Abstract class and sealed classClasses can be declared as abstract. This is accomplished by putting the keyword abstract before the

    keyword class in the class definition. For example:

    public abstract class A

    {

    // Class members here.

    }

    An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common

    definition of a base class that multiple derived classes can share. For example, a class library maydefine an abstract class that is used as a parameter to many of its functions, and require

    programmers using that library to provide their own implementation of the class by creating a derived

    class.

    Abstract classes may also define abstract methods. This is accomplished by adding the keyword

    abstract before the return type of the method. For example:

    public abstract class A

    {

    public abstract void DoWork(int i);

    }

  • 8/8/2019 Notes of Visual Basic

    13/41

    Abstract methods have no implementation, so the method definition is followed by a semicolon

    instead of a normal method block. Derived classes of the abstract class must implement all abstract

    methods. When an abstract class inherits a virtual method from a base class, the abstract class can

    override the virtual method with an abstract method. For example:

    // compile with: /target:library

    publicclass D

    {

    public virtual void DoWork(int i)

    {

    // Original implementation.

    }

    }

    public abstract class E : D

    {

    public abstract override void DoWork(int i);

    }

    publicclass F : E

    {

    public override void DoWork(int i)

    {

    // New implementation.

    }

    }

    If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class.

    A class inheriting an abstract method cannot access the original implementation of the methodin the

    previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class

    can force derived classes to provide new method implementations for virtual methods

    Sealed Classes and Class MembersClasses can be declared as sealed. This is accomplished by putting the keyword sealed before the

    keyword class in the class definition. For example:

    public sealed class D

    {

    // Class members here.

    }

    A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class.

    Sealed classes are primarily used to prevent derivation. Because they can never be used as a base

    class, some run-time optimizations can make calling sealed class members slightly faster.

  • 8/8/2019 Notes of Visual Basic

    14/41

    Interfaces

    An interface looks similar to a class. It contains methods and properties but has no

    implementation. We do not specify what the methods and properties will actually do.

    The reason is that classes and structures inherit them and they provide the actualimplementation for each interface member defined.

    The syntax for defining interface is as follows:

    interface interface-name

    {

    //members of the interface

    }

    Commonly, the name of the interface starts with the prefix `I' (though it is not a strict

    rule). The following example illustrates how to define an interface:

    interface IMyInterface { void SomeMethod(); }

    Notice that the SomeMethod() method does not have any implementation. This is

    because we do not use an interface directly in our program. We need a class or

    structure that will implement the interface:

    class MyClass : IMyInterface { public void SomeMethod()

    { Console.WriteLine("This is a method"); } }

    Here, the class MyClass implements the SomeMethod() method of the interface. An

    interface is a type of contract that specifies that the class or structure inheriting the

    interface must implement its members.

    Interface is an abstract type. It is used only for declaring type with some abstract members. Itmeans members without implementations. Please, have a look at piece of code with adeclaration for a simple interface:

    The members of interface can be methods, properties and indexers.

    interface IMyInterface

    {

    void MethodToImplement();

    }

    class InterfaceImplementer : IMyInterface

    {

    staticvoid Main()

    {

  • 8/8/2019 Notes of Visual Basic

    15/41

    InterfaceImplementer iImp = new InterfaceImplementer();

    iImp.MethodToImplement();

    }

    publicvoid MethodToImplement(){

    Console.WriteLine("MethodToImplement() called.");

    }

    }

    Multiple Inheritance using C# interfaces:

    Next feature that obviously needs to be explained is multiple inheritance using c# interfaces.This can be done using child class that inherits from any number of c# interfaces. Theinheritance can also happen with a combination of a C# .Net class and c# interfaces. Now letus see a small piece of code that demonstrate us multiple inheritance using only interfaces asparent data types.

    class ClonableNode : INode,ICloneable{

    public object Clone(){return null;}

    // INode members}

    The above example created a class ClonableNode. It implements all the functionality ofINode interface in the same way as it was done in Node class. Also it realizes Clone methodonly one item ofIClonable interface of .NET library.

    Abstract Class vs. Interface An abstract class may contain complete or incomplete methods. Interfaces can

    contain only the signature of a method but no body. Thus an abstract class canimplement methods but an interface can not implement methods.

    An abstract class can contain fields, constructors, or destructors andimplement properties. An interface can not contain fields, constructors, or

    destructors and it has only the property's signature but no implementation.

    An abstract class cannot support multiple inheritance, but an interface cansupport multiple inheritance. Thus a class may inherit several interfaces but

    only one abstract class. A class implementing an interface has to implement all the methods of the

    http://www.codersource.net/csharp_tutorial_interface.htmlhttp://www.codersource.net/csharp_tutorial_interface.html
  • 8/8/2019 Notes of Visual Basic

    16/41

    interface, but the same is not required in the case of an abstract Class.

    Various access modifiers such as abstract, protected, internal, public, virtual,etc. are useful in abstract Classes but not in interfaces.

    Abstract classes are faster than interfaces.

    Static Classes and Static Class Members

    Static classes and class members are used to create data and functions that can be accessed without

    creating an instance of the class. Static class members can be used to separate data and behavior

    that is independent of any object identity: the data and functions do not change regardless of what

    happens to the object. Static classes can be used when there is no data or behavior in the class that

    depends on object identity.

    Static ClassesA class can be declared static, indicating that it contains only static members. It is not possible to

    create instances of a static class using the new keyword. Static classes are loaded automatically by

    the .NET Framework common language runtime (CLR) when the program or namespace containing

    the class is loaded.

    Use a static class to contain methods that are not associated with a particular object. For example, it

    is a common requirement to create a set of methods that do not act on instance data and are not

    associated to a specific object in your code. You could use a static class to hold those methods.

    The main features of a static class are:

    They only contain static members.

    They cannot be instantiated.

    They are sealed.

    They cannot containInstance Constructors (C# Programming Guide).

    Creating a static class is therefore much the same as creating a class that contains only static

    members and a private constructor. A private constructor prevents the class from being instantiated.

    The advantage of using a static class is that the compiler can check to make sure that no instance

    members are accidentally added. The compiler will guarantee that instances of this class cannot be

    created.

    Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a

    constructor, although it is still possible to declare a static constructor to assign initial values or set up

    some static state.

    When to Use Static ClassesSuppose you have a class CompanyInfo that contains the following methods to get information

    about the company name and address.

    class CompanyInfo

    {

    publicstring GetCompanyName() { return"CompanyName"; }

    http://msdn.microsoft.com/en-us/library/98f28cdx(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/51y09td4(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/k6sa6h87(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/k6sa6h87(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/98f28cdx(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/51y09td4(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/k6sa6h87(VS.80).aspx
  • 8/8/2019 Notes of Visual Basic

    17/41

    publicstring GetCompanyAddress() { return"CompanyAddress"; }

    //...

    }

    These methods do not need to be attached to a specific instance of the class. Therefore, instead of

    creating unnecessary instances of this class, you can declare it as a static class, like this:

    staticclass CompanyInfo

    {

    publicstaticstring GetCompanyName() { return"CompanyName"; }

    publicstaticstring GetCompanyAddress() { return

    "CompanyAddress"; }

    //...

    }

    Use a static class as a unit of organization for methods not associated with particular objects. Also, a

    static class can make your implementation simpler and faster because you do not have to create an

    object in order to call its methods. It is useful to organize the methods inside the class in a meaningful

    way, such as the methods of theMathclass in theSystemnamespace.

    Static Members

    A static method, field, property, or event is callable on a class even when no instance of the class has

    been created. If any instances of the class are created, they cannot be used to access the static

    member. Only one copy of static fields and events exists, and static methods and properties can only

    access static fields and static events. Static members are often used to represent data or calculations

    that do not change in response to object state; for instance, a math library might contain static

    methods for calculating sine and cosine.

    Static class members are declared using the static keyword before the return type of the member, for

    example:

    publicclass Automobile

    {

    publicstaticint NumberOfWheels = 4;

    publicstaticint SizeOfGasTank

    {

    get

    {

    return 15;

    }

    }

    publicstaticvoid Drive() { }

    publicstatic event EventType RunOutOfGas;

    //other non-static fields and properties...

    }

    Static members are initialized before the static member is accessed for the first time, and before the

    static constructor, if any is called. To access a static class member, use the name of the class instead

    of a variable name to specify the location of the member. For example:

    Automobile.Drive();

    http://msdn.microsoft.com/en-us/library/system.math(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/system.math(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/system.math(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/system(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/system(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/system(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/system.math(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/system(VS.80).aspx
  • 8/8/2019 Notes of Visual Basic

    18/41

    int i = Automobile.NumberOfWheels;

    ExampleHere is an example of a static class that contains two methods that convert temperature from Celsius

    to Fahrenheit and vice versa:

    publicstaticclass TemperatureConverter

    {

    publicstatic double CelsiusToFahrenheit(string

    temperatureCelsius)

    {

    // Convert argument to double for calculations.

    double celsius = System.Double.Parse(temperatureCelsius);

    // Convert Celsius to Fahrenheit.

    double fahrenheit = (celsius * 9 / 5) + 32;

    return fahrenheit;

    }

    publicstatic double FahrenheitToCelsius(string

    temperatureFahrenheit)

    {

    // Convert argument to double for calculations.

    double fahrenheit =

    System.Double.Parse(temperatureFahrenheit);

    // Convert Fahrenheit to Celsius.

    double celsius = (fahrenheit - 32) * 5 / 9;

    return celsius;

    }

    }

    class TestTemperatureConverter

    {

    staticvoid Main()

    {

    System.Console.WriteLine("Please select the convertor

    direction");

    System.Console.WriteLine("1. From Celsius to Fahrenheit.");

    System.Console.WriteLine("2. From Fahrenheit to Celsius.");

    System.Console.Write(":");

  • 8/8/2019 Notes of Visual Basic

    19/41

    string selection = System.Console.ReadLine();

    double F, C = 0;

    switch (selection)

    {

    case"1":

    System.Console.Write("Please enter the Celsius

    temperature: ");

    F =

    TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());

    System.Console.WriteLine("Temperature in Fahrenheit:

    {0:F2}", F);

    break;

    case"2":

    System.Console.Write("Please enter the Fahrenheit

    temperature: ");

    C =

    TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());

    System.Console.WriteLine("Temperature in Celsius:

    {0:F2}", C);

    break;

    default:System.Console.WriteLine("Please select a

    convertor.");

    break;

    }

    }

    }

    Partial Classes and Methods (C# Programming Guide)

    It is possible to split the definition of a class or a struct, aninterface or a method over two or more

    source files. Each source file contains a section of the type or method definition, and all parts are

    combined when the application is compiled.

    Partial ClassesThere are several situations when splitting a class definition is desirable:

    When working on large projects, spreading a class over separate files enables multiple

    programmers to work on it at the same time.

    http://msdn.microsoft.com/en-us/library/0b0thckt.aspxhttp://msdn.microsoft.com/en-us/library/ah19swz4.aspxhttp://msdn.microsoft.com/en-us/library/ah19swz4.aspxhttp://msdn.microsoft.com/en-us/library/87d83y5b.aspxhttp://msdn.microsoft.com/en-us/library/87d83y5b.aspxhttp://msdn.microsoft.com/en-us/library/0b0thckt.aspxhttp://msdn.microsoft.com/en-us/library/ah19swz4.aspxhttp://msdn.microsoft.com/en-us/library/87d83y5b.aspx
  • 8/8/2019 Notes of Visual Basic

    20/41

  • 8/8/2019 Notes of Visual Basic

    21/41

    }

    }

    Using Constructors

    Constructors are classmethods that are executed when an object of a given type is created.

    Constructors have the same name as the class, and usually initialize the data members of the new

    object.

    In the following example, a class named Taxi is defined by using a simple constructor. This class is

    then instantiated with the newoperator. The Taxi constructor is invoked by the new operator

    immediately after memory is allocated for the new object.

    publicclass Taxi

    {

    publicbool isInitialized;

    public Taxi()

    {

    isInitialized = true;

    }

    }

    class TestTaxi

    {

    staticvoid Main()

    {

    Taxi t = new Taxi();Console.WriteLine(t.isInitialized);

    }

    }

    A constructor that takes no parameters is called a default constructor. Default constructors are

    invoked whenever an object is instantiated by using the new operator and no arguments are provided

    to new. For more information, see Instance Constructors (C# Programming Guide).

    Unless the class isstatic, classes without constructors are given a public default constructor by the C#

    compiler in order to enable class instantiation. For more information, seeStatic Classes and Static

    Class Members (C# Programming Guide).

    You can prevent a class from being instantiated by making the constructor private, as follows:

    class NLog

    {

    // Private Constructor:

    private NLog() { }

    publicstatic double e = Math.E; //2.71828...

    }

    http://msdn.microsoft.com/en-us/library/0b0thckt.aspxhttp://msdn.microsoft.com/en-us/library/0b0thckt.aspxhttp://msdn.microsoft.com/en-us/library/51y09td4.aspxhttp://msdn.microsoft.com/en-us/library/51y09td4.aspxhttp://msdn.microsoft.com/en-us/library/k6sa6h87.aspxhttp://msdn.microsoft.com/en-us/library/98f28cdx.aspxhttp://msdn.microsoft.com/en-us/library/98f28cdx.aspxhttp://msdn.microsoft.com/en-us/library/79b3xss3.aspxhttp://msdn.microsoft.com/en-us/library/79b3xss3.aspxhttp://msdn.microsoft.com/en-us/library/79b3xss3.aspxhttp://msdn.microsoft.com/en-us/library/0b0thckt.aspxhttp://msdn.microsoft.com/en-us/library/51y09td4.aspxhttp://msdn.microsoft.com/en-us/library/k6sa6h87.aspxhttp://msdn.microsoft.com/en-us/library/98f28cdx.aspxhttp://msdn.microsoft.com/en-us/library/79b3xss3.aspxhttp://msdn.microsoft.com/en-us/library/79b3xss3.aspx
  • 8/8/2019 Notes of Visual Basic

    22/41

    Instance Constructors

    Instance constructors are used to create and initialize any instance member variables when you use

    the newexpression to create an object of a class. To initialize a static class, or static variables in a

    non-static class, you must define a static constructor.

    The following example shows an instance constructor:

    class CoOrds

    {

    publicint x, y;

    // constructor

    public CoOrds()

    {

    x = 0;

    y = 0;

    }

    }

    This instance constructor is called whenever an object based on the CoOrds class is created. A

    constructor like this one, which takes no arguments, is called a default constructor. However, it is

    often useful to provide additional constructors. For example, we can add a constructor to the CoOrds

    class that allows us to specify the initial values for the data members:

    // tcA constructor with two arguments:

    public CoOrds(int x, int y)

    {

    this.x = x;

    this.y = y;

    }

    This allows CoOrd objects to be created with default or specific initial values, like this:

    CoOrds p1 = new CoOrds();

    CoOrds p2 = new CoOrds(5, 3);

    If a class does not have a default constructor, one is automatically generated and default values are

    used to initialize the object fields, for example, an intis initialized to 0. For more information on

    default values, seeDefault Values Table (C# Reference). Therefore, because the CoOrds class default

    constructor initializes all data members to zero, it can be removed altogether without changing how

    the class works. A complete example using multiple constructors is provided in Example 1 later in this

    topic, and an example of an automatically generated constructor is provided in Example 2.

    Instance constructors can also be used to call the instance constructors of base classes. The class

    constructor can invoke the constructor of the base class through the initializer, as follows:

    http://msdn.microsoft.com/en-us/library/51y09td4.aspxhttp://msdn.microsoft.com/en-us/library/51y09td4.aspxhttp://msdn.microsoft.com/en-us/library/0b0thckt.aspxhttp://msdn.microsoft.com/en-us/library/98f28cdx.aspxhttp://msdn.microsoft.com/en-us/library/5kzh1b5w.aspxhttp://msdn.microsoft.com/en-us/library/5kzh1b5w.aspxhttp://msdn.microsoft.com/en-us/library/83fhsxwc.aspxhttp://msdn.microsoft.com/en-us/library/83fhsxwc.aspxhttp://msdn.microsoft.com/en-us/library/51y09td4.aspxhttp://msdn.microsoft.com/en-us/library/0b0thckt.aspxhttp://msdn.microsoft.com/en-us/library/98f28cdx.aspxhttp://msdn.microsoft.com/en-us/library/5kzh1b5w.aspxhttp://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
  • 8/8/2019 Notes of Visual Basic

    23/41

    C#

    Copy Code

    class Circle : Shape

    {

    public Circle(double radius)

    : base(radius, 0)

    {

    }

    }

    In this example, the Circle class passes values representing radius and height to the constructor

    provided by Shape from which Circle is derived. A complete example using Shape and Circle

    appears in this topic as Example 3.

    Example 1

    The following example demonstrates a class with two class constructors, one without arguments andone with two arguments.

    C#

    Copy Code

    class CoOrds

    {

    publicint x, y;

    // Default constructor:

    public CoOrds()

    {

    x = 0;

    y = 0;

    }

    // tcA constructor with two arguments:

    public CoOrds(int x, int y)

    {

    this.x = x;

    this.y = y;

    }

    // Override the ToString method:

    public override string ToString()

    {

    return (String.Format("({0},{1})", x, y));

    }

    }

    class MainClass

  • 8/8/2019 Notes of Visual Basic

    24/41

    {

    staticvoid Main()

    {

    CoOrds p1 = new CoOrds();

    CoOrds p2 = new CoOrds(5, 3);

    // Display the results using the overriden ToString method:

    Console.WriteLine("CoOrds #1 at {0}", p1);

    Console.WriteLine("CoOrds #2 at {0}", p2);

    Console.ReadKey();

    }

    }

    /* Output:

    CoOrds #1 at (0,0)

    CoOrds #2 at (5,3)

    */

    Example 2

    In this example, the class Person does not have any constructors, in which case, a default

    constructor is automatically provided and the fields are initialized to their default values.

    C#

    Copy Code

    publicclass Person

    {

    publicint age;

    publicstring name;

    }

    class TestPerson

    {

    staticvoid Main()

    {

    Person person = new Person();

    Console.WriteLine("Name: {0}, Age: {1}", person.name,

    person.age);

    // Keep the console window open in debug mode.

    Console.WriteLine("Press any key to exit.");

    Console.ReadKey();

    }

    }

    // Output: Name: , Age: 0

  • 8/8/2019 Notes of Visual Basic

    25/41

    Notice that the default value ofage is 0 and the default value ofname is null. For more information

    on default values, seeDefault Values Table (C# Reference).

    Example 3

    The following example demonstrates using the base class initializer. The Circle class is derived from

    the general class Shape, and the Cylinder class is derived from the Circle class. The constructor

    on each derived class is using its base class initializer.

    C#

    Copy Code

    abstract class Shape

    {

    publicconst double pi = Math.PI;

    protected double x, y;

    public Shape(double x, double y)

    {

    this.x = x;

    this.y = y;

    }

    public abstract double Area();

    }

    class Circle : Shape

    {

    public Circle(double radius)

    : base(radius, 0)

    {

    }

    public override double Area()

    {

    return pi * x * x;

    }

    }

    class Cylinder : Circle

    {

    public Cylinder(double radius, double height)

    : base(radius)

    {

    y = height;

    }

    public override double Area()

    {

    http://msdn.microsoft.com/en-us/library/83fhsxwc.aspxhttp://msdn.microsoft.com/en-us/library/83fhsxwc.aspxhttp://msdn.microsoft.com/en-us/library/83fhsxwc.aspxhttp://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
  • 8/8/2019 Notes of Visual Basic

    26/41

  • 8/8/2019 Notes of Visual Basic

    27/41

    If all the methods in the class are static, consider making the complete class static. For more

    information seeStatic Classes and Static Class Members (C# Programming Guide).

    Example

    The following is an example of a class using a private constructor.

    C#Copy Code

    publicclass Counter

    {

    private Counter() { }

    publicstaticint currentCount;

    publicstaticint IncrementCount()

    {

    return ++currentCount;

    }

    }

    class TestCounter

    {

    staticvoid Main()

    {

    // If you uncomment the following statement, it will generate

    // an error because the constructor is inaccessible:

    // Counter aCounter = new Counter(); // Error

    Counter.currentCount = 100;

    Counter.IncrementCount();

    Console.WriteLine("New count: {0}", Counter.currentCount);

    // Keep the console window open in debug mode.

    Console.WriteLine("Press any key to exit.");

    Console.ReadKey();

    }

    }

    // Output: New count: 101

    Notice that if you uncomment the following statement from the example, it will generate an error

    because the constructor is inaccessible because of its protection level:

    Static Constructors

    A static constructor is used to initialize any static data, or to perform a particular action that needs

    performed once only. It is called automatically before the first instance is created or any static

    members are referenced.

    C#

    Copy Code

    http://msdn.microsoft.com/en-us/library/79b3xss3.aspxhttp://msdn.microsoft.com/en-us/library/79b3xss3.aspxhttp://msdn.microsoft.com/en-us/library/98f28cdx.aspxhttp://msdn.microsoft.com/en-us/library/79b3xss3.aspxhttp://msdn.microsoft.com/en-us/library/98f28cdx.aspx
  • 8/8/2019 Notes of Visual Basic

    28/41

  • 8/8/2019 Notes of Visual Basic

    29/41

    protectedstatic readonly DateTime globalStartTime;

    // Property for the number of each bus.

    protectedint RouteNumber { get; set; }

    // Static constructor to initialize the static variable.

    // It is invoked before the first instance constructor is run.

    static Bus()

    {

    globalStartTime = DateTime.Now;

    // The following statement produces the first line of

    output,

    // and the line occurs only once.

    Console.WriteLine("Static constructor sets global start time

    to {0}",

    globalStartTime.ToLongTimeString());

    }

    // Instance constructor.

    public Bus(int routeNum)

    {

    RouteNumber = routeNum;

    Console.WriteLine("Bus #{0} is created.", RouteNumber);}

    // Instance method.

    publicvoid Drive()

    {

    TimeSpan elapsedTime = DateTime.Now - globalStartTime;

    // For demonstration purposes we treat milliseconds as

    minutes to simulate

    // actual bus times. Do not do this in your actual bus

    schedule program!

    Console.WriteLine("{0} is starting its route {1:N2} minutes

    after global start time {2}.",

    this.RouteNumber,

    elapsedTime.TotalMilliseconds,

    globalStartTime.ToShortTimeString())

    ;

    }

    }

  • 8/8/2019 Notes of Visual Basic

    30/41

    class TestBus

    {

    staticvoid Main()

    {

    // The creation of this instance activates the static

    constructor.

    Bus bus1 = new Bus(71);

    // Create a second bus.

    Bus bus2 = new Bus(72);

    // Send bus1 on its way.

    bus1.Drive();

    // Wait for bus2 to warm up.

    System.Threading.Thread.Sleep(25);

    // Send bus2 on its way.

    bus2.Drive();

    // Keep the console window open in debug mode.

    System.Console.WriteLine("Press any key to exit.");

    System.Console.ReadKey();

    }}

    /* Sample output:

    Static constructor sets global start time to 3:57:08 PM.

    Bus #71 is created.

    Bus #72 is created.

    71 is starting its route 6.00 minutes after global start time

    3:57 PM.

    72 is starting its route 31.00 minutes after global start time

    3:57 PM.

    */

    Boxing and unboxing

    all types used in C#. All these types can be cast to another type using special rules. Animplicit casting can be done with types when values of variables can be converted withoutlosing of any data. There is special type of implicit casting called boxing. This enables us toconvert any type to the reference type or to the object type. Boxing example:

    // boxingchar ch = 'b';object obj = ch;Console.WriteLine("Char value is {0}",ch);

  • 8/8/2019 Notes of Visual Basic

    31/41

  • 8/8/2019 Notes of Visual Basic

    32/41

    Console.WriteLine("Division by zero exception passed");}

    Implementing a finally Block: FinallyDemo.cs

    using System;

    using System.IO;

    class FinallyDemo

    {

    staticvoid Main(string[] args)

    {

    FileStream outStream = null;

    FileStream inStream = null;

    try

    {

    outStream = File.OpenWrite("DestinationFile.txt");

    inStream = File.OpenRead("BogusInputFile.txt");

    }

    catch(Exception ex)

    {

    Console.WriteLine(ex.ToString());}

    finally

    {

    if(outStream != null)

    {

    outStream.Close();

    Console.WriteLine("outStream closed.");

    }

    if(inStream != null){

    inStream.Close();

    Console.WriteLine("inStream closed.");

    }

    }

    }

    }

    Reflection

    Reflection is the feature in .Net, which enables us to get some

  • 8/8/2019 Notes of Visual Basic

    33/41

    information about object in runtime. That information contains dataof the class. Also it can get the names of the methods that are

    inside the class and constructors of that object.

    To write a C# .Net program which uses reflection, theprogram should use the namespace System.Reflection.To get type of the object, the typeofoperator can beused. There is one more method GetType(). This alsocan be used for retrieving the type information of aclass. The Operatortypeofallow us to get class name ofour object and GetType() method uses to get data aboutobject?s type. This C# tutorial on reflection explains thisfeature with a sample class

    10.ReflectionReflection is the feature in .Net, which enables us to get some

    information about object in runtime. That information contains dataof the class. Also it can get the names of the methods that are

    inside the class and constructors of that object.

    To write a C# .Net program which uses reflection, the programshould use the namespace System.Reflection. To get type of theobject, the typeofoperator can be used. There is one more method

    GetType(). This also can be used for retrieving the typeinformation of a class. The Operatortypeofallow us to get classname of our object and GetType() method uses to get data aboutobject?s type. This C# tutorial on reflection explains this featurewith a sample class.

    public class TestDataType{

    public TestDataType(){

    counter = 1;}

    public TestDataType(int c){

    counter = c;}

    private int counter;

  • 8/8/2019 Notes of Visual Basic

    34/41

  • 8/8/2019 Notes of Visual Basic

    35/41

    // get all the methodsConsole.WriteLine("Methods:");foreach( MethodInfo mf in methods ){

    Console.WriteLine(mf);}

    Now, the above program returns a list of methods andconstructors of TestDataType class.

    Reflection is a very powerful feature that any programminglanguage would like to provide, because it allows us to get someinformation about objects in runtime. It can be used in the

    applications normally but this is provided for doing some advancedprogramming. This might be for runtime code generation (It goesthrough creating, compilation and execution of source code inruntime).

    The Sample code can be downloaded from here. The attachedexample can be compiled using .NET command line csccommand. Type csc Reflection.cs. This will create the executableReflection.exe, which can be run as a normal executable.

    Delegates and Events

    This lesson introduces delegates and events. Our objectives are asfollows:

    Understand What aDelegate Is Understand What anEventIs ImplementDelegates FireEvents

    Delegates

    During previous lessons, you learned how to implement reference types

    using language constructs such as classes and interfaces. These reference

    types allowed you to create instances of objects and use them in special

    ways to accomplish your software development goals. Classes allow you

    to create objects that contained members with attributes or behavior.

    Interfaces allowed you to declare a set of attributes and behavior that all

    objects implementing them would publicly expose. Today, I'm going tointroduce a new reference type called a delegate.

    http://www.codersource.net/samples/Reflection.ziphttp://www.codersource.net/samples/Reflection.zip
  • 8/8/2019 Notes of Visual Basic

    36/41

    A delegate is a C# language element that allows you to reference amethod. If you were a C or C++ programmer, this would sound familiar

    because a delegate is basically a function pointer. However, developerswho have used other languages are probably wondering, "Why do I need

    a reference to a method?". The answer boils down to giving youmaximum flexibility to implement any functionality you want at runtime.

    Think about how you use methods right now. You write an algorithm that

    does its thing by manipulating the values of variables and calling methods

    directly by name. What if you wanted an algorithm that was very flexible,

    reusable, and allowed you to implement different functionality as the

    need arises? Furthermore, let's say that this was an algorithm that

    supported some type of data structure that you wanted to have sorted, but

    you also want to enable this data structure to hold different types. If you

    don't know what the types are, how could you decide an appropriate

    comparison routine? Perhaps you could implement an if/then/else or

    switch statement to handle well-known types, but this would still belimiting and require overhead to determine the type. Another alternative

    would be for all the types to implement an interface that declared a

    common method your algorithm would call, which is actually a nice

    solution. However, since this lesson is about delegates, we'll apply adelegate solution, which is quite elegant.

    You could solve this problem by passing a delegate to your algorithm andletting the contained method, which the delegate refers to, perform thecomparison operation. Such an operation is performed in Listing 14-1.

    Listing 14-1. Declaring and Implementing a Delegate:

    SimpleDelegate.cs

    using System;

    // this is the delegate declarationpublicdelegateint Comparer(object obj1, object obj2);

    publicclass Name

    {

    publicstring FirstName = null;

    publicstring LastName = null;

    public Name(string first, string last)

    {

    FirstName = first;

  • 8/8/2019 Notes of Visual Basic

    37/41

    LastName = last;

    }

    // this is the delegate method handler

    publicstaticint CompareFirstNames(object name1, object name2){

    string n1 = ((Name)name1).FirstName;

    string n2 = ((Name)name2).FirstName;

    if(String.Compare(n1, n2) > 0)

    {

    return 1;

    }

    elseif(String.Compare(n1, n2) < 0){

    return -1;

    }

    else

    {

    return 0;

    }

    }

    publicoverridestring ToString()

    {

    return FirstName + " " + LastName;

    }

    }

    class SimpleDelegate

    {

    Name[] names = new Name[5];

    public SimpleDelegate()

    {

    names[0] = new Name("Joe", "Mayo");

    names[1] = new Name("John", "Hancock");

    names[2] = new Name("Jane", "Doe");

    names[3] = new Name("John", "Doe");

    names[4] = new Name("Jack", "Smith");

    }

    staticvoid Main(string[] args)

  • 8/8/2019 Notes of Visual Basic

    38/41

    {

    SimpleDelegate sd = new SimpleDelegate();

    // this is the delegate instantiation

    Comparer cmp = new Comparer(Name.CompareFirstNames);

    Console.WriteLine("\nBefore Sort: \n");

    sd.PrintNames();

    // observe the delegate argument

    sd.Sort(cmp);

    Console.WriteLine("\nAfter Sort: \n");

    sd.PrintNames();

    }

    // observe the delegate parameter

    publicvoid Sort(Comparer compare)

    {

    object temp;

    for(int i=0; i < names.Length; i++)

    {

    for(int j=i; j < names.Length; j++)

    {

    // using delegate "compare" just like

    // a normal method

    if( compare(names[i], names[j]) > 0 )

    {

    temp = names[i];

    names[i] = names[j];names[j] = (Name)temp;

    }

    }

    }

    }

    publicvoid PrintNames()

    {

    Console.WriteLine("Names: \n");

  • 8/8/2019 Notes of Visual Basic

    39/41

    foreach (Name name in names)

    {

    Console.WriteLine(name.ToString());

    }

    }}

    13.Events

    Traditional Console applications operate by waiting for a user to press a

    key or type a command and press theEnterkey. Then they perform somepre-defined operation and either quit or return to the original prompt that

    they started from. This works, but is inflexible in that everything is hard-

    wired and follows a rigid path of execution. In stark contrast, modern

    GUI programs operate on an event-based model. That is, some event inthe system occurs and interested modules are notified so they can react

    appropriately. With Windows Forms, there is not a polling mechanism

    taking up resources and you don't have to code a loop that sits waiting for

    input. It is all built into the system with events.

    A C# eventis a class member that is activated whenever the event it wasdesigned for occurs. I like to use the term "fires" when the eventisactivated. Anyone interested in the eventcan register and be notified as

    soon as the eventfires. At the time an eventfires, registered methods willbe invoked.

    Events and delegates work hand-in-hand to provide a program's

    functionality. It starts with a class that declares an event. Any class,including the same class that the eventis declared in, may register one ofits methods for the event. This occurs through a delegate, which specifiesthe signature of the method that is registered for the event. The delegatemay be one of the pre-defined .NET delegates or one you declareyourself. Whichever is appropriate, you assign the delegate to the event,which effectively registers the method that will be called when the eventfires. Listing 14-2 shows a couple different ways to implement events.

    Listing 14-2. Declaring and Implementing Events: Eventdemo.cs

    using System;

    using System.Drawing;

    using System.Windows.Forms;

    // custom delegatepublicdelegatevoid Startdelegate();

  • 8/8/2019 Notes of Visual Basic

    40/41

    class Eventdemo : Form

    {

    // custom event

    publicevent Startdelegate StartEvent;

    public Eventdemo()

    {

    Button clickMe = new Button();

    clickMe.Parent = this;

    clickMe.Text = "Click Me";

    clickMe.Location = new Point(

    (ClientSize.Width - clickMe.Width) /2,(ClientSize.Height - clickMe.Height)/2);

    // an EventHandler delegate is assigned

    // to the button's Click event

    clickMe.Click += new EventHandler(OnClickMeClicked);

    // our custom "Startdelegate" delegate is assigned

    // to our custom "StartEvent" event.

    StartEvent += new Startdelegate(OnStartEvent);

    // fire our custom event

    StartEvent();

    }

    // this method is called when the "clickMe" button is pressed

    publicvoid OnClickMeClicked(object sender, EventArgs ea)

    {

    MessageBox.Show("You Clicked My Button!");

    }

    // this method is called when the "StartEvent" Event is fired

    publicvoid OnStartEvent()

    {

    MessageBox.Show("I Just Started!");

    }

    staticvoid Main(string[] args)

    {Application.Run(new Eventdemo());

  • 8/8/2019 Notes of Visual Basic

    41/41

    }

    }