7

How do the System.Reflection.BindingFlags Public, NonPublic, and Instance correspond to the C# access modifiers?

Is the following correspondence table correct?

+-------------+--------+---------+-----------+----------+--------------------+
| BindingFlag | Public | Private | Protected | Internal | Protected Internal |
+-------------+--------+---------+-----------+----------+--------------------+
| Instance    | No     | No      | No        | Yes      | Yes                |
| NonPublic   | No     | Yes     | Yes       | No       | No                 |
| Public      | Yes    | No      | No        | No       | No                 |
| *           | Yes    | Yes     | Yes       | Yes      | Yes                |
+-------------+--------+---------+-----------+----------+--------------------+

* Instance | NonPublic | Public

Is there a way to make sense of this? For example, if Instance corresponds to Internal, why isn't it just called Internal?

JDiMatteo
  • 12,022
  • 5
  • 54
  • 65

1 Answers1

16

Your table is not 100% correct.

Instance means that this is an "instance method" which means non-static. If you want to get non-static methods, then you use the Instance filter. If you want to get static methods then you cannot put this filter.

NonPublic means anything except for public methods. So if you use the NonPublic filter, then you will get private, protected, internal and protected internal methods.

Public means just public methods, and no other methods.

Your table should look like that:

+-------------+--------+---------+-----------+----------+--------------------+
| BindingFlag | Public | Private | Protected | Internal | Protected Internal |
+-------------+--------+---------+-----------+----------+--------------------+
| NonPublic   | No     | Yes     | Yes       | Yes      | Yes                |
| Public      | Yes    | No      | No        | No       | No                 |
+-------------+--------+---------+-----------+----------+--------------------+

Putting "Instance" filter in this table doesn't make sense, as Instance does not deal with method's access level.

msporek
  • 1,187
  • 8
  • 21
  • 2
    What does instance do? It seems to be suggested all over the place in the context of calling internal constructors, e.g. http://stackoverflow.com/a/4077327/1007353 – JDiMatteo Dec 19 '14 at 17:51
  • 2
    You didn't read my answer, the answer is there! Instance means you will get "non static" members, so if you use this filter, then you should not expect a static method to be returned. I cannot be more clear. Here you have info from MSDN: http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags(v=vs.110).aspx – msporek Dec 19 '14 at 17:56
  • OK, thanks, sorry my question was sort of grounded in confusion. – JDiMatteo Dec 19 '14 at 18:01