-1

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.

aynber
  • 22,380
  • 8
  • 50
  • 63
Yevgeni Grinberg
  • 359
  • 5
  • 19

3 Answers3

3

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()
Andrei
  • 55,890
  • 9
  • 87
  • 108
  • Same assembly = same namespace? – Yevgeni Grinberg Jun 11 '13 at 13:43
  • 1
    @YevgeniGrinberg, not exactly. Assembly is library, either `exe` or `dll` file. Most likely in your case this is a project you are working with. Namespace however is a logical way or organization of your types. One namespace can be declared in several assemblies. Here is [a good post](http://msdn.microsoft.com/en-us/library/ms973231.aspx#assenamesp_topic5) that describes these concepts in depth. – Andrei Jun 11 '13 at 13:48
1

Because MySortedList isn't derived from TItem then you will need to make the method in question public for it to be callable from MySortedList.

You can only call protected methods from the defining class or one of its derived classes.

See the Microsoft documentation for more details.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

The class in which you have MyMethod function must be declare as public because here you want to use that method outside the class. So it should be public.

Rahul
  • 5,603
  • 6
  • 34
  • 57