Description
[Note: This exception is typically thrown when the access level of a field in a class library is changed, and one or more assemblies referencing the library have not been recompiled.]
Example
using System;
using System.Reflection;
/// <summary>
/// Shows a FieldAccessException being thrown
/// because we try to SetValue on an enum field, which
/// is read-only.
/// </summary>
///
enum Color
{
Brown = 0,
Red = 1,
Blue = 2,
Green = 3,
}
class FieldAccessExceptionSample
{
static void Main()
{
try
{
typeof(Color).GetField("Red").SetValue(null, (Color)42);
}
catch (FieldAccessException fae)
{
Console.WriteLine("Caught exception: {0} - '{1}'",
fae.GetType().Name, fae.Message);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
}
}
The output is
Caught exception: FieldAccessException - 'Cannot set a final field.'
Press Enter to continue
|