1

I need to make container class for different structs(which inherit after same interface) but the thing is container needs to have GetStructAt(int index) method which returns non-nullable type.

Example:

public interface IExampleInterface
{}

public struct A : IExampleInterface
{
    //some code
}

public struct B : IExampleInterface
{
    //some code
}

public class Containter
{
    List<IExampleInterface> list = new List<IExampleInterface>();

    public /*SOMETHING*/ GetStructAt(int index)
    {
        return list[index];
    }

    public void AddStruct<T>(T toAdd) where T : struct, IExampleInterface
    {
        list.Add(toAdd);
    }
}

What should I put in place of "/SOMETHING/ to get non-nullable type or is there any other way, maybe even without interfaces(which are not a must)?

My usecase is holding some components(which must be struct) of specific objects in this container to then add them to objects when needed. Adding to objects needs non-nullable type(I can't change it)

  • 1
    It's very unclear what the requirements are at the moment. What does the *caller* want? Do they know which type of struct they're interested in? What would you expect to happen if the actual type is different? Where does this "get non-nullable type" requirement come from, and isn't it enough just to say it definitely *won't* be null? – Jon Skeet Dec 22 '19 at 13:22
  • @JonSkeet caller accepts T where T: struct,IExampleInterface(that's where this non-nullable requirement comes from). Type will always be struct because I set it kind of by hand –  Dec 22 '19 at 13:49
  • So you want to make it a generic method, like `AddStruct` is? What if the caller calls `GetStructAt(0)` and the element at index 0 isn't an `A`? What do you want to happen? – Jon Skeet Dec 22 '19 at 16:16
  • I'd like GetStruct not to be generic and depend only on index in the list so that I can iterate throught whole list and add each struct to my object –  Dec 22 '19 at 19:37
  • 1
    I don't see how you can expect `GetStruct` *not* to be generic, but to have different return types based on something at execution time. I strongly advise you to think about what you'd want the calling code to look like, and what it would expect to be returned, and you'll see why your requirements don't really work. – Jon Skeet Dec 23 '19 at 09:05

1 Answers1

1

You need IExampleInterface, as:

public IExampleInterface GetStructAt(int index)
{
    return list[index];
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175