Search code examples
c#genericsprotected

Protection level of method to use with generics


My generic class is defined as follows:

public class MySortedList<TKey, TItem> where TItem : MyClass<TKey>

In one of class' methods I create an instance of TItem and call one of its protected methods:

TItemInstance.MyMethod();

Here I get the error that

MyMethod is inaccessible due to its protection level

What level of protection should MyMethod have?
Thank You.


Solution

  • Methods declared as protected can only be used in the classes and their subclasses.

    If you want to use method outside of the class, you should declare it as public:

    public void MyMethod()
    

    or, if the caller is defined in the same assembly, internal:

    internal void MyMethod()