user8882898
user8882898

Reputation:

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

Upvotes: 2

Views: 837

Answers (2)

eocron
eocron

Reputation: 7546

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.

Upvotes: 1

Corentin Pane
Corentin Pane

Reputation: 4943

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.

Upvotes: 2

Related Questions