Description
[Note: This attribute can be applied to fields and parameters. For more information on storing constants in metadata, see Partition II of the CLI Specification. The types in System.Runtime.CompilerServices are intended primarily for use by compilers, not application programmers. They allow compilers to easily implement certain language features that are not directly visible to programmers.]
Example
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
/// <summary>
/// Sample demonstrating the use of the DecimalConstantAttribute class.
/// This attribute is typically used by compiler writers to translate decimal
/// constants in source code into the equivalent IL.
/// </summary>
internal class DecimalConstantAttributeSample
{
// Compiler adds DecimalConstantAttribute and initializes DecimalConstant1
// with the specified value. Note that the field will not contain
// FieldAttributes.Literal even though it looks like a constant
public const decimal DecimalConstant1 = 499.9995M;
// Manually add DecimalConstantAttribute and initialize DecimalConstant2 to
// a different value.
[DecimalConstant(4, 0, 0, 0, 4999995)]
public static readonly decimal DecimalConstant2 = 0;
// Normal constant.
public const int IntegerConstant = 500;
private static void Main()
{
FieldInfo[] fields = typeof(DecimalConstantAttributeSample).GetFields();
foreach (FieldInfo field in fields)
{
Console.WriteLine("Field name: {0}", field.Name);
Console.WriteLine("Field attributes: {0}", field.Attributes);
Console.WriteLine("Field value: {0}", field.GetValue(null));
foreach (object obj in field.GetCustomAttributes(false))
{
DecimalConstantAttribute attr = obj as DecimalConstantAttribute;
if (attr != null)
{
Console.WriteLine("Constant value: {0}", attr.Value);
}
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
}
}
The output is
Field name: DecimalConstant1
Field attributes: Public, Static, InitOnly
Field value: 499.9995
Constant value: 499.9995
Field name: DecimalConstant2
Field attributes: Public, Static, InitOnly
Field value: 0
Constant value: 499.9995
Field name: IntegerConstant
Field attributes: Public, Static, Literal, HasDefault
Field value: 500
Press Enter to continue
|