Generic method with generic parameter in constraint - CSharp Custom Type

CSharp examples for Custom Type:Generics

Description

Generic method with generic parameter in constraint

Demo Code

using static System.Console;
using System;//from   ww w.  j a va2  s  .  c om
using System.Collections.Generic;
using System.Threading;
class Program
{
   static void Main(string[] args)
   {
      string number1 = "42";
      WriteLine($"{number1} squared is {Squarer.Square<string>(number1)}");
      byte number2 = 13;
      WriteLine($"{number2} squared is {Squarer.Square<byte>(number2)}");
   }
}
public static class Squarer
{
   public static double Square<T>(T input) where T : IConvertible
   {
      double d = input.ToDouble(Thread.CurrentThread.CurrentCulture);
      return d * d;
   }
}

Result


Related Tutorials