Casting Objects

   
  

using System;

public class MotorVehicle {

    public string model;

    public MotorVehicle(string model) {
        this.model = model;
    }

    public void Start() {
        Console.WriteLine(model + " started");
    }

}

public class Product : MotorVehicle {

    public bool convertible;

    public Product(string model, bool convertible) :
        base(model) {
        this.convertible = convertible;
    }

}


public class Motorcycle : MotorVehicle {

    public bool sidecar;

    public Motorcycle(string model, bool sidecar) :
        base(model) {
        this.sidecar = sidecar;
    }

    public void PullWheelie() {
        Console.WriteLine(model + " pulling a wheelie!");
    }

}
class MainClass {

    public static void Main() {
        Product myProduct = new Product("MR2", true);

        MotorVehicle myMotorVehicle = (MotorVehicle)myProduct;

        Console.WriteLine("myMotorVehicle.model = " + myMotorVehicle.model);
        myMotorVehicle.Start();
        Motorcycle myMotorcycle = new Motorcycle("V-Rod", true);

        MotorVehicle myMotorVehicle2 = (MotorVehicle)myMotorcycle;

        Console.WriteLine("myMotorVehicle2.model =" + myMotorVehicle2.model);
        myMotorVehicle2.Start();
        Motorcycle myMotorcycle2 = (Motorcycle)myMotorVehicle2;

        Console.WriteLine("myMotorcycle2.model = " + myMotorcycle2.model);
        Console.WriteLine("myMotorcycle2.sidecar = " + myMotorcycle2.sidecar);
        myMotorcycle2.Start();
        myMotorcycle2.PullWheelie();
    }
}

   
     


Custom Serialization using ISerializable

   
 

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Text;
using System.IO;

using System.Runtime.Serialization.Formatters.Soap;


[Serializable]
class MyStringData : ISerializable {
    public string dataItemOne, dataItemTwo;

    public MyStringData() { }

    private MyStringData(SerializationInfo si, StreamingContext ctx) {
        dataItemOne = si.GetString("First_Item").ToLower();
        dataItemTwo = si.GetString("dataItemTwo").ToLower();
    }

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext ctx) {
        // Fill up the SerializationInfo object with the formatted data.
        info.AddValue("First_Item", dataItemOne.ToUpper());
        info.AddValue("dataItemTwo", dataItemTwo.ToUpper());
    }
}

[Serializable]
class MoreData {
    public string dataItemOne, dataItemTwo;

    [OnSerializing]
    internal void OnSerializing(StreamingContext context) {
        dataItemOne = dataItemOne.ToUpper();
        dataItemTwo = dataItemTwo.ToUpper();
    }

    [OnDeserialized]
    internal void OnDeserialized(StreamingContext context) {
        dataItemOne = dataItemOne.ToLower();
        dataItemTwo = dataItemTwo.ToLower();
    }
}
class Program {
    static void Main(string[] args) {
        MyStringData sd = new MyStringData();
        sd.dataItemOne = "some data.";
        sd.dataItemTwo = "some more data";

        Stream s = new FileStream("MyData.soap",
        FileMode.Create, FileAccess.Write, FileShare.None);

        SoapFormatter sf = new SoapFormatter();
        sf.Serialize(s, sd);
        s.Close();

        s = File.OpenRead("MyData.soap");
        sd = (MyStringData)sf.Deserialize(s);
        Console.WriteLine("Item 1: {0}", sd.dataItemOne);
        Console.WriteLine("Item 2: {0}", sd.dataItemTwo);

        MoreData md = new MoreData();
        md.dataItemOne = "1, 2, 3.";
        md.dataItemTwo = "One more test...";

        s = new FileStream("MoreData.soap",FileMode.Create, FileAccess.Write, FileShare.None);

        sf = new SoapFormatter();
        sf.Serialize(s, md);
        s.Close();

        s = File.OpenRead("MoreData.soap");
        md = (MoreData)sf.Deserialize(s);
        Console.WriteLine("Item 1: {0}", md.dataItemOne);
        Console.WriteLine("Item 2: {0}", md.dataItemTwo);
    }
}

    


Interface with event

   
 

using System;

public delegate void AlarmEvent(IAlarm sender);

public interface IAlarm {
    event AlarmEvent IssueAlarm;
}

abstract class MyStuff : ICloneable {
    public object Clone() {
        return null;
    }
    public void DoStuff() {
    }

}
interface IFoo {
    void DoStuff();
}

interface IBar {
    void DoStuff();
}

interface ITest {
    void DoSomething();
    int DoSomethingElse();
}
class MyClass : IFoo, IBar {
    void IFoo.DoStuff() {
    }
    void IBar.DoStuff() {
    }
}

class MainClass : IComparable {
    public int CompareTo(object other) {
        return -1;
    }
    static int Main(string[] args) {
        MainClass c = new MainClass();
        MainClass c2 = new MainClass();
        if (c.CompareTo(c2) == 0)
            return 0;
        MyClass c3 = new MyClass();
        return 1;
    }
}

    


Interfaces:Working with Interfaces


   


/*
A Programmer's Introduction to C# (Second Edition)
by Eric Gunnerson

Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/

// 10 - InterfacesWorking with Interfaces
// copyright 2000 Eric Gunnerson
using System;

public class WorkingwithInterfaces
{
    public static void Main()
    {
        DiagramObject[] dArray = new DiagramObject[100];
        
        dArray[0] = new DiagramObject();
        dArray[1] = new TextObject("Text Dude");
        dArray[2] = new TextObject("Text Backup");
        
        // array gets initialized here, with classes that
        // derive from DiagramObject. Some of them implement
        // IScalable.
        
        foreach (DiagramObject d in dArray)
        {
            if (d is IScalable)
            {
                IScalable scalable = (IScalable) d;
                scalable.ScaleX(0.1F);
                scalable.ScaleY(10.0F);
            }
        }
    }
}

interface IScalable
{
    void ScaleX(float factor);
    void ScaleY(float factor);
}
public class DiagramObject
{
    public DiagramObject() {}
}
public class TextObject: DiagramObject, IScalable
{
    public TextObject(string text)
    {
        this.text = text;
    }
    // implementing IScalable.ScaleX()
    public void ScaleX(float factor)
    {
        Console.WriteLine("ScaleX: {0} {1}", text, factor);
        // scale the object here.
    }
    
    // implementing IScalable.ScaleY()
    public void ScaleY(float factor)
    {
        Console.WriteLine("ScaleY: {0} {1}", text, factor);
        // scale the object here.
    }
    
    private string text;
}

           
          


A safe method of determining whether a class implements a particular interface


   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
//  ISample.cs - Demonstrates a safe method of determining whether a class
//               implements a particular interface
//               Compile this program with the following command line:
//                   C:>csc isample.cs
//
namespace nsInterfaceSample
{
    using System;
    public class InterfaceSample
    {
        static public void Main ()
        {
// Declare an instance of the clsSample class
            clsSample samp = new clsSample();
//  Test whether clsSample supports the IDisposable interface
            if (samp is IDisposable)
            {
//  If true, it is safe to call the Dispose() method
                IDisposable obj = (IDisposable) samp;
                obj.Dispose ();
            }
        }
    }
    class clsSample : IDisposable
    {
//  Implement the IDispose() function
        public void Dispose ()
        {
            Console.WriteLine ("Called Dispose() in clsSample");
        }
    }
}


           
          


Overriding Interfaces: Tester Overriding InterfacesAs


   

/*
Learning C# 
by Jesse Liberty

Publisher: O'Reilly 
ISBN: 0596003765
*/
 using System;

 namespace OverridingInterfaces
 {
     interface IStorable
     {
         void Read();
         void Write();
     }

     interface ITalk
     {
         void Talk();
         void Read();
     }


     // Modify Document to also implement ITalk
     class Document : IStorable, ITalk
     {
         // the document constructor
         public Document(string s)
         {
             Console.WriteLine(
                 "Creating document with: {0}", s);
         }

         // Implicit implementation
         public virtual void Read()
         {
             Console.WriteLine(
                 "Document Read Method for IStorable");
         }

         public void Write()
         {
             Console.WriteLine(
                 "Document Write Method for IStorable");
         }

         // Explicit implementation
         void ITalk.Read()
         {
             Console.WriteLine("Implementing ITalk.Read");
         }

         public void Talk()
         {
             Console.WriteLine("Implementing ITalk.Talk");
         }
     }

    public class TesterOverridingInterfacesAs
    {
       [STAThread]
       static void Main()
       {
           // Create a Document object
           Document theDoc = new Document("Test Document");
           IStorable isDoc = theDoc as IStorable;
           if (isDoc != null)
           {
               isDoc.Read();
           }

           // Cast to an ITalk interface
           ITalk itDoc = theDoc as ITalk;
           if (itDoc != null)
           {
               itDoc.Read();
           }

           theDoc.Read();
           theDoc.Talk();
       }
    }
 }