简体   繁体   中英

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>;
}

There are no generic properties in C# so far. You can find details here and here :

We must reserve space for the backing store for the generic property [...]. But we don't know how much to reserve. Even if the compiler had read and understood every possible use of the generic.

MSDN states here :

Properties are a natural extension of fields. Both are named members with associated types.

They must have an associated type at compile-time.

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.

if you want to make it generic the generic type should be passed to the class as following

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

Calling it

var defaultValue = new test<TheType>.Default;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM