Get Method Names using Reflection [C#]
If you want to get method names of a given type in C#, you can use method Type.GetMethods. This method returns array of MethodInfo objects. MethodInfo contains many informations about the method and of course a method name (MethodInfo.Name).
To filter returned methods (for example if you want to get only public static methods) use BindingFlags parameter when calling GetMethods method. Required are at least two flags, one from Public/NonPublic and one of Instance/Static flags. Of course you can use all four flags and also DeclaredOnly and FlattenHierarchy. BindingFlags enumeration and MethodInfo class are declared in System.Reflection namespace.
The example will show method name and return type of the method of developersnote class
By Mohd Zulkamal
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
To filter returned methods (for example if you want to get only public static methods) use BindingFlags parameter when calling GetMethods method. Required are at least two flags, one from Public/NonPublic and one of Instance/Static flags. Of course you can use all four flags and also DeclaredOnly and FlattenHierarchy. BindingFlags enumeration and MethodInfo class are declared in System.Reflection namespace.
The example will show method name and return type of the method of developersnote class
The developersnote Class
public class developersnoteClass
{
public developersnoteClass()
{
}
public void ConvertDateTime()
{
}
public static void ConvertInteger()
{
}
public static void FormatString()
{
}
public void FormatDouble()
{
}
}
The ASPX Page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
The Code Behind
protected void Page_Load(object sender, EventArgs e)
{
// get all public static methods of MyClass type
MethodInfo[] methodInfos = typeof(developersnoteClass).GetMethods(BindingFlags.Public |
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod |
BindingFlags.Instance
);
// sort methods by name
Array.Sort(methodInfos,
delegate(MethodInfo methodInfo1, MethodInfo methodInfo2)
{ return methodInfo1.Name.CompareTo(methodInfo2.Name); });
// write method names
foreach (MethodInfo methodInfo in methodInfos)
{
Response.Write(methodInfo.ReturnType + " " + methodInfo.Name + "<br/>");
}
}
The Output
By Mohd Zulkamal
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)