How to create a generic method with generic constructor in C#

1 Answer

0 votes
using System;

class Generic<T>
{
    private T gVariable;

    public Generic(T gValue) {
        this.gVariable = gValue;
    }

    public void Print() {
        Console.WriteLine(this.gVariable);
    }
}

class Program
{
    // Generic method that creates a Generic<T> object
    public static Generic<T> CreateGeneric<T>(T value) {
        return new Generic<T>(value);
    }

    // Generic method that creates any T with a parameterless constructor
    public static T CreateInstance<T>() where T : new() {
        return new T();
    }

    static void Main()
    {
        var g1 = CreateGeneric(12);
        var g2 = CreateGeneric("C# Programming");
        var g3 = CreateGeneric(3.14f);
        var g4 = CreateGeneric(345.8916);

        g1.Print();
        g2.Print();
        g3.Print();
        g4.Print();
    }
}



/*
run:

12
C# Programming
3.14
345.8916

*/

 



answered Dec 19, 2020 by avibootz
edited 19 hours ago by avibootz
...