C# Type GenericParameterAttributes

Description

Type GenericParameterAttributes gets a combination of GenericParameterAttributes flags that describe the covariance and special constraints of the current generic type parameter.

Syntax

Type.GenericParameterAttributes has the following syntax.


public virtual GenericParameterAttributes GenericParameterAttributes { get; }

Example

The following code example defines a generic type Test with two type parameters that have different constraints.


//  ww  w  .j  a  va2  s .c om
using System;
using System.Reflection;

public interface ITest {}
public class Base {}
public class Test<T,U> 
    where T : Base, ITest 
    where U : class, new() {}

public class Derived : Base, ITest {}

public class Example
{
    public static void Main()
    {
        Type def = typeof(Test<,>);
        Console.WriteLine("\r\nExamining generic type {0}", def);

        Type[] defparams = def.GetGenericArguments();
        foreach (Type tp in defparams)
        {
            Console.WriteLine(ListGenericParameterAttributes(tp));
        }
    }
    private static string ListGenericParameterAttributes(Type t)
    {
        string retval;
        GenericParameterAttributes gpa = t.GenericParameterAttributes;
        GenericParameterAttributes variance = gpa & GenericParameterAttributes.VarianceMask;

        // Select the variance flags. 
        if (variance == GenericParameterAttributes.None)
            retval = "No variance flag;";
        else
        {
            if ((variance & GenericParameterAttributes.Covariant) != 0)
                retval = "Covariant;";
            else
                retval = "Contravariant;";
        }
        return retval;
    }
}

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