appdev

Upload: bookwormmd

Post on 04-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 appdev

    1/45

    Colegio de San Juan de Letran

    College of Engineering

    And Institute of Information Technology

    A Research work in C# Programming

    Submitted by:

    Martin Gerome Camacho

    ACT2B

    Submitted to:

    Engr. Ethel T. Manansala

    _____________

    Grade

    January 29, 2013

  • 7/29/2019 appdev

    2/45

    Objects

    A class or struct definition is like a blueprint that specifies what the type can do. An object is basically a

    block of memory that has been allocated and configured according to the blueprint. A program may create

    many objects of the same class. Objects are also called instances, and they can be stored in either a

    named variable or in an array or collection. Client code is the code that uses these variables to call the

    methods and access the public properties of the object. In an object-oriented language such as C#, a

    typical program consists of multiple objects interacting dynamically.

    EXAMPLE:

    1)

    publicclass Person{

    publicstring Name { get; set; }publicint Age { get; set; }

    public Person(string name, int age){

    Name = name;

    Age = age;

    }}

    class Program

    {

    staticvoid Main(){

    Person person1 = new Person("Jasper", 6);

    Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);

    Person person2 = person1;

    person2.Name = "Patrick";

    person2.Age = 16;

    Console.WriteLine("person2 Name = {0} Age = {1}", person2.Name, person2.Age);

    Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);

    Console.ReadLine();

    }}

  • 7/29/2019 appdev

    3/45

    2)

    using System;

    class Hello{

    public class BankAccount {

    public string accountName;

    public int accountFee;

    private int accountBalance;

    private int accountNumber;

    }

    static void Main(){

    BankAccount custAccount = new BankAccount();

    custAccount.accountName = "John Smith";

    custAccount.accountFee = 5;

    Console.WriteLine ("Customer Name is " + custAccount.accountName);

    Console.WriteLine ("Account Fee = $" + custAccount.accountFee);

    }}

  • 7/29/2019 appdev

    4/45

    Classes

    A class is a construct that enables you to create your own custom types by grouping together variables of

    other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the

    class is not declared as static, client code can use it by creating objects or instances which are assigned to

    a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR

    marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in

    memory and client code can only access it through the class itself, not an instance variable

    EXAMPLE:

    1)

    publicclass Person{publicstring name;

    public Person(){

    name = "unknown";

    }

    public Person(string nm){

    name = nm;

    }

    publicvoid SetName(string newName){

    name = newName;

    }}

    class TestPerson{

    staticvoid Main(){

    Person person1 = new Person();

    Console.WriteLine(person1.name);

    person1.SetName("Doe a Deer");

    Console.WriteLine(person1.name);

    Console.ReadLine();

    }}

  • 7/29/2019 appdev

    5/45

    2)

    string _name;

    public Perl(){

    this._name = "Perl";

    _name = "Sam";

    Console.WriteLine(this._name);

    Console.WriteLine(_name);

    }}

    class Program{

    static void Main(){

    Perl perl = new Perl();

    }}

  • 7/29/2019 appdev

    6/45

    Structs

    Objects live on the managed heap. Structs often reside on the evaluation stack. Every program uses simple

    structs. All value typessuch as int, bool and charare structs. And custom structs, often not advisable,

    are also used.

    EXAMPLE:

    1)

    using System;

    struct SimpleStruct{

    private int xval;

    public int X{

    get {return xval;

    }

    set{

    if (value < 100)

    xval = value;

    }}

    public void DisplayX(){

    Console.WriteLine("The stored value is: {0}", xval);

    }}

    class TestClass

    {

    public static void Main(){

    SimpleStruct ss = new SimpleStruct();

    ss.X = 5;

    ss.DisplayX();

    }}

  • 7/29/2019 appdev

    7/45

    2)

    public struct Foo{

    private string fooString;

    private int fooNumber;

    public string FooString{

    get

    {

    return fooString;

    }

    set{

    fooString = value;

    }}

    public int GetFooNumber(){

    return fooNumber;

    }}

  • 7/29/2019 appdev

    8/45

    Inheritance

    Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics of

    object-oriented programming. Inheritance enables you to create new classes that reuse, extend, and

    modify the behavior that is defined in other classes. The class whose members are inherited is called the

    base class, and the class that inherits those members is called the derived class. A derived class can have

    only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB

    is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.

    EXAMPLE:

    1)

    publicclass WorkItem{

    privatestaticint currentID;protectedint ID { get; set; }

    protectedstring Title { get; set; }

    protectedstring Description { get; set; }

    protected TimeSpan jobLength { get; set; }

    public WorkItem(){

    ID = 0;

    Title = "Default title";

    Description = "Default description.";

    jobLength = new TimeSpan();

    }

    public WorkItem(string title, string desc, TimeSpan joblen){

    this.ID = GetNextID();

    this.Title = title;

    this.Description = desc;

    this.jobLength = joblen;

    }

    static WorkItem(){

    currentID = 0;

    }

  • 7/29/2019 appdev

    9/45

    protectedint GetNextID(){

    return ++currentID;

    }

    publicvoid Update(string title, TimeSpan joblen){

    this.Title = title;

    this.jobLength = joblen;

    }

    publicoverridestring ToString(){

    return String.Format("{0} - {1}", this.ID, this.Title);

    }}

    publicclass ChangeRequest : WorkItem{

    protectedint originalItemID { get; set; }

    public ChangeRequest() { }

    public ChangeRequest(string title, string desc, TimeSpan jobLen,

    int originalID){

    this.ID = GetNextID();

    this.Title = title;

    this.Description = desc;

    this.jobLength = jobLen;

    this.originalItemID = originalID;

    }}

    class Program{

    staticvoid Main(){

    WorkItem item = new WorkItem("Fix Bugs",

    "Fix all bugs in my code branch",

    new TimeSpan(3, 4, 0, 0));

    ChangeRequest change = new ChangeRequest("Change Base Class Design",

    "Add members to the class",

  • 7/29/2019 appdev

    10/45

    new TimeSpan(4, 0, 0),

    1);

    Console.WriteLine(item.ToString());

    change.Update("Change the Design of the Base Class",

    new TimeSpan(4, 0, 0));

    Console.WriteLine(change.ToString());

    Console.ReadLine();

    }}

    2)

    using System;

    public class ParentClass{

    public ParentClass(){

    Console.WriteLine("Parent Constructor.");

    }

    public void print(){

    Console.WriteLine("I'm a Parent Class.");

    }}

    public class ChildClass : ParentClass{

    public ChildClass(){

    Console.WriteLine("Child Constructor.");

    }

    public static void Main(){

    ChildClass child = new ChildClass();

    child.print();

    }}

  • 7/29/2019 appdev

    11/45

    Abstract Class

    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 may define

    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.

    EXAMPLE:

    1)

    publicclass D{

    publicvirtualvoid DoWork(int i){

    }}publicabstractclass E : D{

    publicabstractoverridevoid DoWork(int i);

    }

    publicclass F : E{

    publicoverridevoid DoWork(int i)

    {

    }}

  • 7/29/2019 appdev

    12/45

    2)

    using System;

    namespace abstractSample

    {

    abstract class absClass

    {

    public int AddTwoNumbers(int Num1, int Num2)

    {

    return Num1 + Num2;

    }

    public abstract int MultiplyTwoNumbers(int Num1, int Num2);

    }

    class absDerived:absClass

    {

    [STAThread]

    static void Main(string[] args)

    {

    absDerived calculate = new absDerived();

    int added = calculate.AddTwoNumbers(10,20);

    int multiplied = calculate.MultiplyTwoNumbers(10,20);

    Console.WriteLine("Added : {0},

    Multiplied : {1}", added, multiplied);

    }

    public override int MultiplyTwoNumbers(int Num1, int Num2)

    {

    return Num1 * Num2;

    }

  • 7/29/2019 appdev

    13/45

    Class Members

    A class's members include all the members declared in the class, along with all members (except

    constructors and destructors) declared in all classes in its inheritance hierarchy. Private members in base

    classes are inherited but are not accessible from derived classes. A class member, method, field, property,

    or event, on a derived class that is overriding a virtual member of the base class can declare that member

    as sealed. This negates the virtual aspect of the member for any further derived class. This is

    accomplished by putting the sealed keyword before the override keyword in the class member declaration

    Polymorphism

    Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and

    inheritance. Polymorphism is a Greek word that means "many-shaped" and it has two distinct aspects:1. At run time, objects of a derived class may be treated as objects of a base class in places such as

    method parameters and collections or arrays. When this occurs, the object's declared type is no

    longer identical to its run-time type.

    2. Base classes may define and implement virtual methods, and derived classes can override them,which means they provide their own definition and implementation. At run-time, when client code

    calls the method, the CLR looks up the run-time type of the object, and invokes that override of the

    virtual method. Thus in your source code you can call a method on a base class, and cause a

    derived class's version of the method to be executed.

    EXAMPLE:

    1)

    publicclass Shape{

    publicint X { get; privateset; }

    publicint Y { get; privateset; }

    publicint Height { get; set; }

    publicint Width { get; set; }publicvirtualvoid Draw(){

    Console.WriteLine("Performing base class drawing tasks");

    }}

    class Circle : Shape{

    publicoverridevoid Draw(){

  • 7/29/2019 appdev

    14/45

    Console.WriteLine("Drawing a circle");

    base.Draw();

    }}

    class Rectangle : Shape{

    publicoverridevoid Draw(){

    Console.WriteLine("Drawing a rectangle");

    base.Draw();

    }}

    class Triangle : Shape{

    publicoverridevoid Draw(){

    Console.WriteLine("Drawing a triangle");

    base.Draw();

    }}

    class Program{

    staticvoid Main(string[] args){

    System.Collections.Generic.List shapes = new System.Collections.Generic.List();

    shapes.Add(new Rectangle());

    shapes.Add(new Triangle());

    shapes.Add(new Circle());

    foreach (Shape s in shapes){

    s.Draw();

    }

    Console.ReadLine();

    }}

    2)

    using System;

    namespace method_overloading{

    classProgram{

    publicclassPrint{

    publicvoid display(string name){

  • 7/29/2019 appdev

    15/45

    Console.WriteLine("Your name is : " + name);

    }

    publicvoid display(int age, float marks){

    Console.WriteLine("Your age is : " + age);

    Console.WriteLine("Your marks are :" + marks);

    }}

    staticvoid Main(string[] args){

    Print obj = newPrint();

    obj.display("George");

    obj.display(34, 76.50f);

    Console.ReadLine();

    }

  • 7/29/2019 appdev

    16/45

    Interfaces

    An interface contains definitions for a group of related functionalities that a class or a struct can implement.

    By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability

    is important in C# because the language doesn't support multiple inheritance of classes. In addition, you

    must use an interface if you want to simulate inheritance for structs, because they can't actually inherit from

    another struct or class.

    EXAMPLE:

    1)

    publicclass Car : IEquatable{

    publicstring Make {get; set;}

    publicstring Model { get; set; }publicstring Year { get; set; }

    publicbool Equals(Car car){

    if(this.Make == car.Make &&

    this.Model == car.Model &&

    this.Year == car.Year){

    returntrue;

    }

    else

    returnfalse;

    }}

  • 7/29/2019 appdev

    17/45

    2)

    class Demo : def{

    public static void Main(){

    System.Console.WriteLine("Hello Interfaces");

    Demo refDemo = new Demo();

    def refdef = refDemo;

    refdef.xyz();

    refdef.pqr();

    }

    void abc.xyz(){

    System.Console.WriteLine("In xyz");

    }

    void def.pqr(){

    System.Console.WriteLine("In pqr");

    }}

    interface abc{

    void xyz();

    }

    interface def : abc{

    void pqr();

    }

  • 7/29/2019 appdev

    18/45

    Methods

    A method is a code block that contains a series of statements. A program causes the statements to be

    executed by calling the method and specifying any required method arguments. In C#, every executed

    instruction is performed in the context of a method. The Main method is the entry point for every C#

    application and it is called by the common language runtime (CLR) when the program is started.

    EXAMPLE:

    1)

    static int one(int num1){

    if (num1%2==0){

    Console.WriteLine("The number is even");

    }else{

    Console.WriteLine("The number is odd");

    }

    return 0;

    }

    static int two(int a, int b,int c){

    if (a>b && a>c){

    Console.WriteLine("First number is the highest");

    }

    else if (a< b && b>c){

    Console.WriteLine("Second number is the highest");

    }

    else{

    Console.WriteLine("Third number is the highest");

    }

    return 0;

    }

    }

    static void Main(string[] args){

  • 7/29/2019 appdev

    19/45

  • 7/29/2019 appdev

    20/45

    }

    return 0;

    }

    static int two(int a, int b,int c){

    if (a>b && a>c){

    Console.WriteLine("First number is the highest");

    }

    else if (a< b && b>c){

    Console.WriteLine("Second number is the highest");

    }

    else{

    Console.WriteLine("Third number is the highest");

    }

    return 0;

    }

    static int three(string a, string b, string c, string d){

    string[] three = new string[4]{a,b,c,d};

    Array.Sort(three);

    for (int i=0; iWrite(three[i]+ " ");

    }

    return 0;

    }

    static void Main(string[] args){

    String name, name2, name3, name4;

    int num1, num2, num3;

    char op;

    Console.Write("Choose an operation(A/B/C): ");

    op=char.Parse(Console.ReadLine());

    if (op == 'a' || op=='A'){

    Console.Write("Please enter a number: ");

  • 7/29/2019 appdev

    21/45

    num1=int.Parse(Console.ReadLine());

    one(num1);

    Console.ReadLine();

    }

    if (op=='b' || op==='B'){

    Console.Write("Please enter anumber: ");

    num1=int.Parse(Console.ReadLine());

    Console.Write("Please enter anumber: ");

    num2=int.Parse(Console.ReadLine());

    Console.Write("Please enter anumber: ");

    num3=int.Parse(Console.ReadLine());

    two(num1, num2, num3);

    Console.ReadLine();

    }

    if (op=='c' || op=='C'){

    Console.Write("Please enter name: ");

    name=Console.ReadLine();

    Console.Write("Please enter name: ");

    name2=Console.ReadLine();

    Console.Write("Please enter name: ");

    name3=Console.ReadLine();

    Console.Write("Please enter name: ");

    name4=Console.ReadLine();

    three(name, name2, name3, name4);

    Console.ReadLine();

    }

    else{

    Console.WriteLine("The letter you entered is invalid.");

    }

  • 7/29/2019 appdev

    22/45

    Parameters/Arguments

    Named arguments free you from the need to remember or to look up the order of parameters in the

    parameter lists of called methods. The parameter for each argument can be specified by parameter name.

    EXAMPLE:

    1)

    class NamedExample{

    staticvoid Main(string[] args){

    Console.WriteLine(CalculateBMI(123, 64));

    Console.WriteLine(CalculateBMI(weight: 123, height: 64));

    Console.WriteLine(CalculateBMI(height: 64, weight: 123));Console.WriteLine(CalculateBMI(123, height: 64));

    }

    staticint CalculateBMI(int weight, int height)

    {

    return (weight * 703) / (height * height);

    }}

    2)

    using System;

    class Program{

    static void Main(){

    Test(name: "Mark", size: 5);

    Test(name: "Ian", size: -1);

    Test(6, "Men");

    Test(7, name: "Jerome");

    }

    static void Test(int size, string name){

    Console.WriteLine("Size = {0}, Name = {1}", size, name);

    }}

  • 7/29/2019 appdev

    23/45

    Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller

    provides an argument for any one of a succession of optional parameters, it must provide arguments for all

    preceding optional parameters. Comma-separated gaps in the argument list are not supported.

    EXAMPLE:

    1)

    namespace OptionalNamespace{

    class OptionalExample{

    staticvoid Main(string[] args){

    ExampleClass anExample = new ExampleClass();

    anExample.ExampleMethod(1, "One", 1);

    anExample.ExampleMethod(2, "Two");

    anExample.ExampleMethod(3);

    ExampleClass anotherExample = new ExampleClass("Provided name");

    anotherExample.ExampleMethod(1, "One", 1);

    anotherExample.ExampleMethod(2, "Two");

    anotherExample.ExampleMethod(3);

    anExample.ExampleMethod(3, optionalint: 4);

    }}

    class ExampleClass{

    privatestring _name;

    public ExampleClass(string name = "Default name"){

    _name = name;

    }

    publicvoid ExampleMethod(int required, string optionalstr = "default string",

    int optionalint = 10){

    Console.WriteLine("{0}: {1}, {2}, and {3}.", _name, required, optionalstr,

    optionalint);

    }}}

  • 7/29/2019 appdev

    24/45

    2)

    using System;

    class Program{

    static void Main(){

    Method();

    Method(4);

    // Method("Dot");

    Method(4, "Dot");

    Method(name: "Sam");

    Method(value: 5, name: "Allen");

    }

    static void Method(int value = 1, string name = "Perl"){

    Console.WriteLine("value = {0}, name = {1}", value, name);

    }}

  • 7/29/2019 appdev

    25/45

    Constructors

    Whenever a class orstruct is created, its constructor is called. A class or struct may have multiple

    constructors that take different arguments. Constructors enable the programmer to set default values, limit

    instantiation, and write code that is flexible and easy to read.

    EXAMPLE:

    1)

    publicclass Taxi{

    publicbool isInitialized;

    public Car(){

    isInitialized = true;

    }}class TestCar{

    staticvoid Main(){

    Car t = new Car();

    Console.WriteLine(t.isInitialized);

    }}

    2)

    class Widget{

    int _size;

    public Widget(int size){

    this._size = size;

    }}

    class Program{

    static void Main(){

    Widget widget1 = new Widget(10);

    Widget widget2 = new Widget(20);

    }}

    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/0b0thckt.aspx
  • 7/29/2019 appdev

    26/45

    Instance Constructor

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

    new expression 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.

    EXAMPLE:

    1)

    class CoOrds{

    publicint x, y;

    public CoOrds(){

    x = 0;

    y = 0;}

    public CoOrds(int x, int y){

    this.x = x;

    this.y = y;

    }

    publicoverridestring ToString(){

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

    }}

    class MainClass{

    staticvoid Main(){

    CoOrds p1 = new CoOrds();

    CoOrds p2 = new CoOrds(5, 3);

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

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

    Console.ReadKey();

    }}

    http://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/98f28cdx.aspxhttp://msdn.microsoft.com/en-us/library/0b0thckt.aspxhttp://msdn.microsoft.com/en-us/library/51y09td4.aspx
  • 7/29/2019 appdev

    27/45

    2)

    using System;

    public class Person{

    public int age;

    public string name;

    }

    public class MainClass {

    static void Main() {

    Person p = new Person();

    Console.Write("Name: {0}, Age: {1}",p.name, p.age);

    }}

  • 7/29/2019 appdev

    28/45

    Static Constructor

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

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

    referenced.

    EXAMPLE:

    1)

    publicclass Bus{

    protectedstaticreadonly DateTime globalStartTime;

    protectedint RouteNumber { get; set; }

    static Bus(){globalStartTime = DateTime.Now;

    Console.WriteLine("Static constructor sets global start time to {0}",

    globalStartTime.ToLongTimeString());

    }

    public Bus(int routeNum){

    RouteNumber = routeNum;

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

    }

    publicvoid Drive(){

    TimeSpan elapsedTime = DateTime.Now - globalStartTime;

    Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",

    this.RouteNumber,

    elapsedTime.TotalMilliseconds,

    globalStartTime.ToShortTimeString());

    }}

    class TestBus{

    staticvoid Main(){

    Bus bus1 = new Bus(71);

    Bus bus2 = new Bus(72);

    http://msdn.microsoft.com/en-us/library/98f28cdx.aspxhttp://msdn.microsoft.com/en-us/library/98f28cdx.aspx
  • 7/29/2019 appdev

    29/45

  • 7/29/2019 appdev

    30/45

    Private Constructor

    It cannot be called externally. It is used to ensure higher-quality code bases on complex projects. These

    constructors eliminate the ability of external code in the project to instantiate the class directly. This forces

    the class to provide a controlled and unified access pattern.

    EXAMPLE:

    1)

    using System;

    public sealed class Test{

    public static readonly Test Instance = new Test();

    public int A;

    private Test(){this.A = 5;

    }}

    class Program{

    static void Main(){

    Test test = Test.Instance;

    Console.WriteLine(test.A);

    test.A++;

    Console.WriteLine(test.A);

    }}

    2)

    public class Class1{

    private Class1(){}

    public static Class1 clobj(){

    Class1 h = new Class1();

    return h;

    }

    public void abc(){

    MessageBox.Show("hello");

    }}}

  • 7/29/2019 appdev

    31/45

    Static Constructor

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

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

    referenced.

    EXAMPLE:

    1)

    static class HasStaticConstructor{

    public static int _test;

    static HasStaticConstructor(){

    _test = 1;}}

    static class NoStaticConstructor{

    public static int _test = 1;

    }

    class Program{

    static void Main()

    {

    System.Console.WriteLine(HasStaticConstructor._test);

    System.Console.WriteLine(NoStaticConstructor._test);

    }}

  • 7/29/2019 appdev

    32/45

    2)

    public class Bus{

    static Bus(){

    System.Console.WriteLine("The static constructor invoked.");

    }

    public static void Drive(){

    System.Console.WriteLine("The Drive method invoked.");

    }}

    class TestBus{

    static void Main()

    {

    Bus.Drive();

    }}

  • 7/29/2019 appdev

    33/45

    Destructors

    Destructors are used to destruct instances of classes, cannot be inherited or overloaded, cannot be called

    and they are invoked automatically.

    EXAMPLE:

    1)

    using System;

    class A{

    public A(){

    Console.WriteLine("Creating A");

    }~A(){

    Console.WriteLine("Destroying A");

    }}

    class B:A{

    public B(){

    Console.WriteLine("Creating B");

    }

    ~B(){

    Console.WriteLine("Destroying B");

    }}

    class C:B{

    public C(){

    Console.WriteLine("Creating C");

    }

    ~C(){

    Console.WriteLine("Destroying C");

    }}

    class App{

    public static void Main(){

  • 7/29/2019 appdev

    34/45

    C c=new C();

    Console.WriteLine("Object Created ");

    Console.WriteLine("Press enter to Destroy it");

    Console.ReadLine();

    c=null;

    Console.Read();

    }}

    2)

    class First{

    ~First(){

    System.Console.WriteLine("First's destructor is called");

    }}

    class Second: First{

    ~Second(){

    System.Console.WriteLine("Second's destructor is called");

    }}

    class Third: Second{

    ~Third(){

    System.Console.WriteLine("Third's destructor is called");

    }}

    class TestDestructors{

    static void Main() {

    Third t = new Third();

    }}

  • 7/29/2019 appdev

    35/45

    Properties

    Properties get and set values. The C# language provides them as a convenient way to simplify syntax.

    They are implemented as methods in the intermediate language. They are standard access points to a

    class from external code. Unlike fields, properties do not denote storage locations. Instead, properties have

    accessors that specify the statements to be executed when their values are read or written.

    EXAMPLE:

    1)

    using System;

    class Example{

    int _number;

    public int Number{get{

    return this._number;

    }

    set{

    this._number = value;

    }}}

    class Program{

    static void Main(){

    Example example = new Example();

    example.Number = 5; // set { }

    Console.WriteLine(example.Number);{}

    }}

  • 7/29/2019 appdev

    36/45

    2)

    using System;

    class Example{

    public Example(){

    this.IsFound = true;

    }

    bool _found;

    public bool IsFound{

    get{

    return this._found;

    }

    private set{

    this._found = value;

    }}}

    class Program{

    static void Main(){

    Example example = new Example();

    Console.WriteLine(example.IsFound);

    }}

  • 7/29/2019 appdev

    37/45

    Accesors

    The accessor of a property contains the executable statements associated with getting (reading or

    computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set

    accessor, or both.

    EXAMPLE:

    1)

    using System;

    abstract class Shape {

    public abstract double Area {

    get;

    set;}}

    class Square: Shape {

    public double side;

    public Square(double s) {

    side = s;

    }

    public override double Area {

    get {

    return side*side ;

    }

    set {

    side = Math.Sqrt(value);

    }}}

    class Cube: Shape {

    public double side;

    public Cube(double s) {

    side = s;

    }

    public override double Area {

  • 7/29/2019 appdev

    38/45

    get {

    return 6*side*side;

    }

    set {

    side = Math.Sqrt(value/6);

    }}}

    public class MainClass {

    public static void Main() {

    Console.Write("Enter the side: ");

    string sideString = Console.ReadLine();

    double side = double.Parse(sideString);

    Square s = new Square(side);

    Cube c = new Cube(side);

    Console.WriteLine("Area of a square = {0:F2}",s.Area);

    Console.WriteLine("Area of a cube = {0:F2}", c.Area);

    Console.Write("Enter the area: ");

    string areaString = Console.ReadLine();

    double area = double.Parse(areaString);

    s.Area = area;

    c.Area = area;

    Console.WriteLine("Side of a square = {0:F2}", s.side);

    Console.WriteLine("Side of a cube = {0:F2}", c.side);

    }}

  • 7/29/2019 appdev

    39/45

    2)

    using System;

    public class BaseClass {

    private string name;

    public string Name{

    get {

    return name;

    }

    set {

    name = value;

    }}}

    public class DerivedClass : BaseClass {

    private string name;

    public new string Name{

    get{

    return name;

    }

    set {

    name = value;

    }}}

    public class MainClass{

    public static void Main(){

    DerivedClass d1 = new DerivedClass();

    d1.Name = "John";

    Console.WriteLine("Name in the derived class is: {0}",d1.Name);

    ((BaseClass)d1).Name = "Mary";

    Console.WriteLine("Name in the base class is: {0}",

    ((BaseClass)d1).Name);

    }}

  • 7/29/2019 appdev

    40/45

    Delegates

    A delegate is a special kind of object that holds a reference to a method. The delegate can be called as if it

    were any other method. However, when called, the underlying referenced method is executed. This simple

    layer of abstraction is useful because unlike a direct call, the method being used does not need to be

    known when writing the code. The reference is created at run-time and may be changed repeatedly

    throughout the life of the executing program.

    EXAMPLE:

    1)

    public delegate double Delegate_Prod(int a,int b);

    class Class1{static double fn_Prodvalues(int val1,int val2){

    return val1*val2;

    }

    static void Main(string[] args){

    Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);

    Console.Write("Please Enter Values");

    int v1 = Int32.Parse(Console.ReadLine());

    int v2 = Int32.Parse(Console.ReadLine());

    double res = delObj(v1,v2);

    Console.WriteLine ("Result :"+res);

    Console.ReadLine();

    }}

  • 7/29/2019 appdev

    41/45

    2)

    public class MarketingDepartment{

    public bool ExecuteNewCampaign(decimal budget){

    bool success = false;

    AddressProvider MyAddressProvider = new AddressProvider();

    List ListOfAddresses =

    MyAddressProvider.GetAddressesNewProspects();

    if (budget < 10000){

    BallpenCompany MyBallpenCompany = new BallpenCompany();

    success = MyBallpenCompany.SendBallPens(ListOfAddresses);

    }

    else{

    CoffeeCupCompany MyCoffeeCupCompany = new CoffeeCupCompany();

    success = MyCoffeeCupCompany.SendCoffeeCups(ListOfAddresses);

    }

    return success;

    }}

  • 7/29/2019 appdev

    42/45

    Events

    An event in C# is a way for a class to provide notif ications to clients of that class when some interesting

    thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the

    classes that represent controls in the interface have events that are notified when the user does something

    to the control (for example, click a button).

    Events, however, need not be used only for graphical interfaces. Events provide a generally useful way for

    objects to signal state changes that may be useful to clients of that object. Events are an important building

    block for creating classes that can be reused in a large number of different programs.

    Events are declared using delegates. If you have not yet studied the Delegates Tutorial, you should do so

    before continuing. Recall that a delegate object encapsulates a method so that it can be called

    anonymously. An event is a way for a class to allow clients to give it delegates to methods that should becalled when the event occurs. When the event occurs, the delegate(s) given to it by its clients are invoked.

    EXAMPLE:

    1)

    using System;

    namespace wildert{

    public class TimeOfTick : EventArgs{

    private DateTime TimeNow;

    public DateTime Time{

    set{

    TimeNow = value;

    }

    get{

    return this.TimeNow;

    }}}

    public class Metronome{

    public event TickHandler Tick;

    public delegate void TickHandler(Metronome m, TimeOfTick e);

    public void Start(){

    while (true){

  • 7/29/2019 appdev

    43/45

    System.Threading.Thread.Sleep(3000);

    if (Tick != null){

    TimeOfTick TOT = new TimeOfTick();

    TOT.Time = DateTime.Now;

    Tick(this, TOT);

    }}}}

    public class Listener{

    public void Subscribe(Metronome m){

    m.Tick += new Metronome.TickHandler(HeardIt);

    }

    private void HeardIt(Metronome m, TimeOfTick e){

    System.Console.WriteLine("HEARD IT AT {0}",e.Time);

    }}

    class Test{

    static void Main(){

    Metronome m = new Metronome();

    Listener l = new Listener();

    l.Subscribe(m);

    m.Start();

    }}}

    2)

    using System;

    namespace wildert{

    public class Metronome{

    public event TickHandler Tick;

    public EventArgs e = null;

    public delegate void TickHandler(Metronome m, EventArgs e);

    public void Start(){

    while (true){

    System.Threading.Thread.Sleep(3000);

  • 7/29/2019 appdev

    44/45

    if (Tick != null){

    Tick(this, e);

    }}}}

    public class Listener{

    public void Subscribe(Metronome m){

    m.Tick += new Metronome.TickHandler(HeardIt);

    }

    private void HeardIt(Metronome m, EventArgs e){

    System.Console.WriteLine("HEARD IT");

    }}

    class Test{

    static void Main(){

    Metronome m = new Metronome();

    Listener l = new Listener();

    l.Subscribe(m);

    m.Start();

    }}}

  • 7/29/2019 appdev

    45/45

    Access Modifiers

    All types and type members have an accessibility level, which controls whether they can be used from

    other code in your assembly or other assemblies. You can use the following access modifiers to specify the

    accessibility of a type or member when you declare it:

    public

    The type or member can be accessed by any other code in the same assembly or another assembly that

    references it.

    private

    The type or member can be accessed only by code in the same class or struct.

    protected

    The type or member can be accessed only by code in the same class or struct, or in a class that is derivedfrom that class.

    internal

    The type or member can be accessed by any code in the same assembly, but not from another assembly.