Check if a field is static in CSharp
Description
The following code shows how to check if a field is static.
Example
using System;// w w w . j a va2 s . c o m
using System.Reflection;
public class Myfielda
{
private string field = "A private field";
public string Field
{
get{return field;}
set{if(field!=value){field=value;}}
}
}
public class Myfieldb
{
static string field = "B private static field";
public string Field
{
get{return field;}
set{if(field!=value){field=value;}}
}
}
public class Myfieldinfo
{
public static int Main()
{
Myfielda Myfielda = new Myfielda();
Myfieldb Myfieldb = new Myfieldb();
Type MyTypea = typeof(Myfielda);
FieldInfo Myfieldinfoa = MyTypea.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance);
Type MyTypeb = typeof(Myfieldb);
FieldInfo Myfieldinfob = MyTypeb.GetField("field", BindingFlags.NonPublic|BindingFlags.Static);
Console.Write("\n{0} - ", MyTypea.FullName);
Console.Write("IsStatic - {0}", Myfieldinfoa.IsStatic);
Console.Write("\n{0} - ", MyTypeb.FullName);
Console.Write("IsStatic - {0}", Myfieldinfob.IsStatic);
return 0;
}
}
The code above generates the following result.