Check if a method is static in CSharp

Description

The following code shows how to check if a method is static.

Example


using System;/*  w  w w.  ja v  a  2 s  .c  o m*/
using System.IO;
using System.Reflection;
using System.Text;

public class Sample
{
    public static void Main()
    {
        Type aType = "".GetType();
        MethodInfo[] mInfo = aType.GetMethods();
        if (mInfo.Length != 0)
        {
            for (int i = 0; i < mInfo.Length; i++)
            {
                if (mInfo[i].DeclaringType == aType && !mInfo[i].IsSpecialName)
                {
                    StringBuilder modifiers = new StringBuilder();
                    if (mInfo[i].IsStatic) { modifiers.Append("static "); }
                    if (mInfo[i].IsPublic) { modifiers.Append("public "); }
                    if (mInfo[i].IsFamily) { modifiers.Append("protected "); }
                    if (mInfo[i].IsAssembly) { modifiers.Append("internal "); }
                    if (mInfo[i].IsPrivate) { modifiers.Append("private "); }
                    Console.WriteLine(modifiers);
                }
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Reflection »




Array
Constructor
Event
Field
Interface
Method
Properties
Type