Use interface as class member - CSharp Custom Type

CSharp examples for Custom Type:interface

Description

Use interface as class member

Demo Code

using System;//from w w  w  . j av a2  s.co  m
using System.Collections.Generic;
using System.Text;
public class Dog
{
   public string Name { get; set; }
   private Runnable _runner;
   public Dog(string name, Runnable runner)
   {
      Name = name;
      _runner = runner;
   }
   public void Run(int distance)
   {
      _runner.Run(distance);
   }
}
public class FastRunner : Runnable
{
   public void Run(int distance)
   {
      Console.WriteLine("I run fast for {0} kms", distance);
   }
}
public interface Runnable
{
   void Run(int distance);
}
public class Person
{
   private readonly string _firstName;
   private readonly string _lastName;
   private Runnable _runner;
   public string FirstName
   {
      get
      {
         return _firstName;
      }
   }
   public string LastName
   {
      get
      {
         return _lastName;
      }
   }
   public int Age { get; set; }
   public Person(string firstName, string lastName, int age, Runnable runner)
   {
      _firstName = firstName;
      _lastName = lastName;
      Age = age;
      _runner = runner;
   }
   public virtual void SayHello()
   {
      Console.WriteLine("Hello I'm a Person");
   }
   public override string ToString()
   {
      return FirstName + " " + LastName + " - age: " + Age;
   }
   public void Run(int distance)
   {
      _runner.Run(distance);
   }
}
class Program
{
   static void Main(string[] args)
   {
      Person slow = new Person("A", "B", 32, new SlowRunner());
      Person fast = new Person("C", "D", 27, new FastRunner());
      Dog d = new Dog("X", new FastRunner());
      slow.Run(5);
      fast.Run(5);
      d.Run(3);
   }
}
public class SlowRunner : Runnable
{
   public void Run(int distance)
   {
      Console.WriteLine("I run slowly for {0} kms", distance);
   }
}

Result


Related Tutorials