CodeBlanks Logo Icon CodeBlanks

GetMethods and GetProperties

C# course · Advanced · Lesson 44/83

Learn to list methods and properties on a Type.

GetMethods and GetProperties

Type.GetMethods() lists the public methods of a type as MethodInfo[]. Type.GetProperties() lists the public properties as PropertyInfo[]. Each array holds the metadata of the member.

By default only public members are returned. With BindingFlags you can request non-public, static or instance members. These lists are the basis for dynamic method calls and property access via reflection.

BindingFlags

Calling GetMethods() without arguments returns only public members. To see non-public, static or inherited-excluded members, use BindingFlags: GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).

Common flags: Public, NonPublic, Instance, Static, DeclaredOnly. DeclaredOnly excludes inherited members. Multiple flags are joined with |.

Exercise Print the property count of a class

Get the type of the Sample class below with Type t = typeof(Sample);. Call t.GetMethods() and t.GetProperties(). Print props.Length with Console.WriteLine.

Show example solution
Type t = typeof(Sample); MethodInfo[] methods = t.GetMethods(); PropertyInfo[] props = t.GetProperties(); Console.WriteLine(props.Length);
Example solution:
using System;
using System.Reflection;

class Sample
{
    public string Name { get; set; }
    public int Age { get; set; }
    public void Hello() { }
}

class Program
{
    static void Main()
    {
        Type t = typeof(Sample);
        MethodInfo[] methods = t.GetMethods();
        PropertyInfo[] props = t.GetProperties();
        Console.WriteLine(props.Length);
    }
}

Test yourself

  1. Complete the GetMethods call

    MethodInfo[] methods = typeof(string).____();
    Show answer
    MethodInfo[] methods = typeof(string).GetMethods();
  2. Match the method to its return type

    GetMethods()
    MethodInfo[]
    GetProperties()
    PropertyInfo[]
    GetFields()
    FieldInfo[]
    GetConstructors()
    ConstructorInfo[]
  3. What does GetMethods() return by default?

    • All methods (including private)
    • Only static methods
    • Only void methods
    • Only public methods
    Show answer

    Only public methods — Correct. GetMethods() returns only public methods by default.

All lessons in Advanced