Nice Generic Example that implements an interface.
- by mbcrump
I created this quick generic example after noticing that several people were asking questions about it. If you have any questions then let me know.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace ConsoleApplication4
{
//New class where Type implements IConvertible interface (interface = contract)
class Calculate<T> where T : IConvertible
{
//Setup fields
public T X;
NumberFormatInfo fmt = NumberFormatInfo.CurrentInfo;
//Constructor 1
public Calculate()
{
X = default(T);
}
//Constructor 2
public Calculate (T x)
{
X = x;
}
//Method that we know will return a double
public double DistanceTo (Calculate<T> cal)
{
//Remove the.ToDouble if you want to see the methods available for IConvertible
return (X.ToDouble(fmt) - cal.X.ToDouble(fmt));
}
}
class Program
{
static void Main(string[] args)
{
//Pass value type and call DistanceTo with an Int.
Calculate<int> cal = new Calculate<int>();
Calculate<int> cal2 = new Calculate<int>(10);
Console.WriteLine("Int : " + cal.DistanceTo(cal2));
//Pass value type and call DistanceTo with an Double.
Calculate<double> cal3 = new Calculate<double>();
Calculate<double> cal4 = new Calculate<double>(10.6);
Console.WriteLine("Double : " + cal3.DistanceTo(cal4));
//Pass reference type and call DistanceTo with an String.
Calculate<string> cal5 = new Calculate<string>("0");
Calculate<string> cal6 = new Calculate<string>("345");
Console.WriteLine("String : " + cal5.DistanceTo(cal6));
}
}
}