0

I am learning C# and was trying a simple Reflection Example. I am trying to get the names of methods from a class. Here's The code:

using System;
using System.Reflection;

namespace Practice
{
    class ReflectionExamples
    {
        private int Sum(int a, int b)
        {
            return a + b;
        }

        public int GetSum(int a, int b)
        {
            int c = Sum(a, b);

            return c;

        }
    }

    class ReflectionDemo
    {
        public static void Execute() // Main calls this
        {
            var a = typeof(ReflectionExamples);

            MethodInfo[] mi = a.GetMethods(); //Using BindingFlags.NonPublic does not show any results
            foreach (MethodInfo m in mi)
            {
                Console.WriteLine(m.Name);
            }
        }
    }
}

The output from this is(Sum is missing):

GetNum
ToString
Equals
GetHashCode
GetType
Ravi
  • 727
  • 6
  • 19

1 Answers1

1

The documentation states (scroll about halfway down the page):

Note

You must specify Instance or Static along with Public or NonPublic or no members will be returned.

The following is also mentioned for Type.GetMethods(BindingFlags):

  • You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

  • Specify BindingFlags.NonPublic to include non-public methods (that is, private, internal, and protected methods) in the search. Only protected and internal methods on base classes are returned; private methods on base classes are not returned.

Therefore you need to specify both BindingFlags.NonPublic and BindingFlags.Instance:

MethodInfo[] mi = a.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
Community
  • 1
  • 1
lc.
  • 113,939
  • 20
  • 158
  • 187