c# generic method type constraint code example

Example 1: generics in c#

class MyGenericClass<T>
{
    private T genericMemberVariable;

    public MyGenericClass(T value)
    {
        genericMemberVariable = value;
    }

    public T genericMethod(T genericParameter)
    {
        Console.WriteLine("Parameter type: {0}, value: {1}", typeof(T).ToString(),genericParameter);
        Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(), genericMemberVariable);
            
        return genericMemberVariable;
    }

    public T genericProperty { get; set; }
}

Example 2: c# store generic type without arguments

public interface IModel<out T> where T : class
{
    T Value { get; }
}

public class Model<T> : IModel<T> where T : class
{
    public T Value { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        var foo = new Model<string>()
        {
            Value = "hello world",
        };

        IModel<object> boo = foo;

        Console.WriteLine(boo.Value);
    }
}