How to create a generic method in C#

2 Answers

0 votes
using System;

class Program
{
  static void Display<T>(T s) {
    Console.WriteLine(s);
  }

  static void Main(string[] args)
  {
    Display("C# Programming");
    Display(12);
    Display(3.14);
  }
}



/*
run:

C# Programming
12
3.14

*/

 



answered Dec 19, 2020 by avibootz
0 votes
using System;

class Program
{
    // Generic method that swaps two values
    public static void Swap<T>(ref T a, ref T b) {
        T temp = a;
        a = b;
        b = temp;
    }

    static void Main()
    {
        // Swap integers
        int x = 10;
        int y = 20;
        Console.WriteLine($"Before swap: x = {x}, y = {y}");
        Swap(ref x, ref y);
        Console.WriteLine($"After swap:  x = {x}, y = {y}");

        Console.WriteLine();

        // Swap strings
        string s1 = "Hello";
        string s2 = "World";
        Console.WriteLine($"Before swap: s1 = {s1}, s2 = {s2}");
        Swap(ref s1, ref s2);
        Console.WriteLine($"After swap:  s1 = {s1}, s2 = {s2}");

        Console.WriteLine();

        // Swap doubles
        double d1 = 1.5;
        double d2 = 3.7;
        Console.WriteLine($"Before swap: d1 = {d1}, d2 = {d2}");
        Swap(ref d1, ref d2);
        Console.WriteLine($"After swap:  d1 = {d1}, d2 = {d2}");
    }
}



/*
run:

Operation complete
3

Cannot divide by zero
Operation complete
0

Operation complete
0

Cannot divide by zero
Operation complete
0

*/

 



answered 9 hours ago by avibootz
...