0
0
C Sharp (C#)programming~5 mins

Inspecting methods and properties in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Sometimes, you want to see what actions (methods) and details (properties) an object has. This helps you understand or use it better.

When you get an object and want to know what you can do with it.
When debugging to check what properties an object holds.
When learning a new class or library and want to explore its features.
When writing code that works with different objects dynamically.
When you want to list all methods or properties for documentation or display.
Syntax
C Sharp (C#)
Type type = typeof(ClassName);
// or
Type type = objectInstance.GetType();

// To get methods
MethodInfo[] methods = type.GetMethods();

// To get properties
PropertyInfo[] properties = type.GetProperties();

typeof(ClassName) gets the type info from a class name.

GetType() gets the type info from an object instance.

Examples
This lists all method names of the string class.
C Sharp (C#)
Type type = typeof(string);
MethodInfo[] methods = type.GetMethods();
foreach (var method in methods)
{
    Console.WriteLine(method.Name);
}
This lists all property names of the int object.
C Sharp (C#)
var number = 123;
Type type = number.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (var prop in properties)
{
    Console.WriteLine(prop.Name);
}
Sample Program

This program creates a Person object and prints its public properties and methods. It shows how to inspect an object's details.

C Sharp (C#)
using System;
using System.Reflection;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void SayHello()
    {
        Console.WriteLine($"Hello, my name is {Name}.");
    }

    private void SecretMethod() { }
}

class Program
{
    static void Main()
    {
        Person p = new Person { Name = "Alice", Age = 30 };
        Type type = p.GetType();

        Console.WriteLine("Properties:");
        foreach (var prop in type.GetProperties())
        {
            Console.WriteLine(prop.Name);
        }

        Console.WriteLine("Methods:");
        foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
        {
            Console.WriteLine(method.Name);
        }
    }
}
OutputSuccess
Important Notes

By default, GetMethods() returns public methods including inherited ones.

Use BindingFlags to control which methods or properties you want (public, private, static, instance).

Properties have getter and setter methods behind the scenes, which also appear in methods list.

Summary

Use typeof() or GetType() to get type info.

Use GetMethods() and GetProperties() to list methods and properties.

Inspecting helps understand and use objects better.