Search code examples
c#templatespropertiesget

c# how to use a template in a get property?


I have some problem to use a template in a get property in c#. The following class has no problem:

public class test
{
    public T GetDefault<T>()
    {
        return default(T);
    }
}

But i would like to use get property and then there is a error

unexpected use of generic name

the code is following:

public class test
{
    public T Default<T> => default<T>;
}

Solution

  • I don't think current C# version support such syntax sugar. But you can get similar behavior like this:

    public static class test<T>
    {
        public static T Default => default(T);
    }
    

    And then use it:

    var value = test<int>.Default;
    

    Actually, if you strugling between two, I would reccomend to stay at methods:

    public static class test
    {
        public static T GetDefault<T>() => default(T);
    }
    

    Benefit is that you can put different extensions in same test class, on different types.