dotnet / docs

This repository contains .NET Documentation.
https://learn.microsoft.com/dotnet
Creative Commons Attribution 4.0 International
4.23k stars 5.87k forks source link

How to create an instance of the class described in "where (generic type constraint) (C# Reference)" #14582

Closed sam-wheat closed 5 years ago

sam-wheat commented 5 years ago

In this document

This class is defined:

public class AGenericClass<T> where T : IComparable<T> { }

And this statement is made:

For example, you can declare a generic class, MyGenericClass, such that the type parameter T implements the IComparable interface:

In the code below I am naming my example class Selector instead of AGenericClass and using interfacte ISelectable instead of IComparable { } That is the only difference.

Can you please show me how to create an instance of Selector class using the same definition as AGenericClass shown in the c# documentation?

Again AGenericClass and Selector differ in name only:

public class AGenericClass<T> where T : IComparable<T> { }

 

public class Selector<T> where T:ISelectable<T>    { }

 

public class Program2
{

    public Program2()
    {
        Selector<Selectable<string>> stringSelector = new Selector<Selectable<string>>(); // does not build
    }
}

public interface ISelectable<T>
{
    bool IsSelected { get; set; }
    T Item { get; set; }
}

public class Selectable<T> : ISelectable<T> 
{
    public bool IsSelected { get; set; }
    public T Item { get; set; }
}

public class Selector<T> where T:ISelectable<T>    {    }

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

BillWagner commented 5 years ago

@sam-wheat

I made a few changes and this compiles for me:

public class Program2
{

    public Program2()
    {
        Selector<Selectable> stringSelector = new Selector<Selectable>(); // does not build
    }
}

public interface ISelectable<T>
{
    bool IsSelected { get; set; }
    T Item { get; set; }
}

// This is the class that needs to change:
public class Selectable : ISelectable<Selectable> 
{
    public bool IsSelected { get; set; }
    public Selectable Item { get; set; }
}

public class Selector<T> where T:ISelectable<T>    {    }

I'll close this as answered.