Create generic class and add constraint to generic parameter - CSharp Custom Type

CSharp examples for Custom Type:Generics

Description

Create generic class and add constraint to generic parameter

Demo Code

using static System.Console;
using System;//from  w  ww . j av a  2  s . c om
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
   static void Main(string[] args)
   {
      var gt = new GenericThing<int>();
      gt.Data = 42;
      WriteLine($"GenericThing: {gt.Process("42")}");
   }
}
public class GenericThing<T> where T : IComparable, IFormattable
{
   public T Data;
   public string Process(string input)
   {
      if (Data.ToString().CompareTo(input) == 0)
      {
         return Data.ToString() + Data.ToString();
      }
      else
      {
         return Data.ToString();
      }
   }
}

Result


Related Tutorials