C# Type DeclaringMethod

Description

Type DeclaringMethod gets a MethodBase that represents the declaring method, if the current Type represents a type parameter of a generic method.

Syntax

Type.DeclaringMethod has the following syntax.


public virtual MethodBase DeclaringMethod { get; }

Example

The following code example defines a class that has a generic method, assigns a type argument to the method, and invokes the resulting constructed generic method.


using System;// w w w .  j ava2  s.co m
using System.Reflection;

public class Example
{
    public static void Generic<T>(T toDisplay)
    {
        Console.WriteLine("\r\nHere it is: {0}", toDisplay);
    }
}

public class Test
{
    public static void Main()
    {
        Type ex = typeof(Example);
        MethodInfo mi = ex.GetMethod("Generic");

        DisplayGenericMethodInfo(mi);

    }

    private static void DisplayGenericMethodInfo(MethodInfo mi)
    {
        if (mi.IsGenericMethod)
        {
            Type[] typeArguments = mi.GetGenericArguments();
            foreach (Type tParam in typeArguments)
            {
                if (tParam.IsGenericParameter)
                {
                    Console.WriteLine("\t\t{0}  parameter position {1}" +
                        "\n\t\t   declaring method: {2}",
                        tParam,
                        tParam.GenericParameterPosition,
                        tParam.DeclaringMethod);
                }
                else
                {
                    Console.WriteLine("\t\t{0}", tParam);
                }
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version