Friday, December 11, 2015

C# Interface

This sample code is my favorite way to demonstrate how interface work, I can see students in "20483 Programming in C#" are all understand why we have to implement interface and what is the meaning of contract to the implemented classes. 
 
 
using System;

namespace ConsoleApplication1
{
   interface IDataAccess
   {     
      void SelectTop10();
   }
   class OracleDataAccess : IDataAccess
   {
      public void SelectTop10(){
        Console.WriteLine("SELECT * FROM TABLE1 WHERE ROWNUM <= 10;");
      }

   }
   class SQLDataAccess : IDataAccess
   {
      public void SelectTop10(){
        Console.WriteLine("SELECT TOP 10 * FROM TABLE1;");
      }
   }
   class Program
   {
      static void Main(string[] args)
      {
         OracleDataAccess oracle = new OracleDataAccess();
         oracle.SelectTop10();
         IDataAccess sql = new SQLDataAccess();
         sql.SelectTop10();
      }
   }
}
 
Here is the output:-
 

C# Delegate with return value

I have written another simple Delegate code to share with students in "20483 Programming in C#", this code showing the delegate with parameters and return value and how we supply the parameters and receive the return value.
 
 
using System;

namespace EventDelegatePOC
{
   delegate int MyDelegate(string s);

   class Program
   {
      static int SayHello(string HelloMessage)
      {
          Console.WriteLine("Hello {0}", HelloMessage);
          return 100;
      }
      static int SayGoodBye(string GoodbyeMessage)
      {
          Console.WriteLine("Good Bye {0}", GoodbyeMessage);
          return -999;
      }
      static void Main(string[] args)
      {
          MyDelegate x = new MyDelegate(SayHello);
          MyDelegate y = new MyDelegate(SayGoodBye);

          int a = x("President");
          int b = y("Sayonara");

          Console.WriteLine("a = {0}", a);
          Console.WriteLine("b = {0}", b);
      }
   }
}
Here is the ouput:-

C# Event Delegate Tutorial

 
Here is the simple tutorial for understanding C# Event and Delegate, I believe the code explain by itself:
 
using System;

namespace EventDelegate2
{
   delegate void MyDelegate();

   class Program
   {
      static event MyDelegate myEvent;

      static void Main(string[] args)
      {
          myEvent += new MyDelegate(Sing);
          myEvent += new MyDelegate(Dance);

          myEvent.Invoke();

      }
       
      static void Sing()
      {
          Console.WriteLine("Sing");
      }


      static void Dance()
      {
          Console.WriteLine("Dance");
      }

    }
}
 
Here is the output: