0

How force to use class that implement generic interface in class? Is something like this possible?

public interface IGeneric<T>
{
    T Value {get;}
}

//public class MyList<IGeneric<T>> {}//not allowed
5
  • I assume you want something like class MyList<T> : IGeneric<T> Commented Jun 16, 2022 at 11:31
  • 1
    learn.microsoft.com/en-us/dotnet/csharp/language-reference/… Commented Jun 16, 2022 at 11:38
  • No i dont want to implement interface, but use on my custom list as items. Commented Jun 16, 2022 at 11:40
  • 1
    Then the first option from Enigmativities answer is your solution Commented Jun 16, 2022 at 11:43
  • It is possible to create such a class, but I cannot create instances of this class. Example Commented Jun 16, 2022 at 14:11

1 Answer 1

1

Something like this:

void Main()
{
    MyList<string> myList = new MyList<string>(new Generic());
}

public interface IGeneric<T>
{
    T Value { get; }
}

public class MyList<T>
{
    private IGeneric<T> _generic;
    public MyList(IGeneric<T> generic)
    {
        _generic = generic;
    }
}

public class Generic : IGeneric<string>
{
    public string Value => throw new NotImplementedException();
}

Or like this:

void Main()
{
    MyList<Generic, string> myList = new MyList<Generic, string>();
    //Or MyList<IGeneric<string>, string> myList = new MyList<IGeneric<string>, string>();
}

public interface IGeneric<T>
{
    T Value { get; }
}

public class MyList<G, T> where G : IGeneric<T>
{
}

public class Generic : IGeneric<string>
{
    public string Value => throw new NotImplementedException();
}
Sign up to request clarification or add additional context in comments.

4 Comments

I can't create class instance, compiler Error CS0311. code MyList<IGeneric<string>> myList = new MyList<IGeneric<string>>();
Probably myList needs to have type MyList<string>, but if you can edit your current interface + class + myList declaration into the question we can answer more specifically.
MyList<string> don't work. I don't understand "edit your ... declaration to the question". Example
@JarosławPietras - I've fleshed it out more. And tested that the code runs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.