Type.GetFields Method
public FieldInfo[] GetFields();
Retrieves all public fields of the current Type.
Parameters
This method does not take any parameters.
Return Value
An array of FieldInfo
objects representing all public fields defined on the current Type. Returns an empty array if the Type has no public fields.
Remarks
The GetFields()
method returns public fields only. To retrieve all fields (public, protected, internal, private), including inherited fields, use the GetFields(BindingFlags)
overload with appropriate BindingFlags
.
- Use
BindingFlags.Public | BindingFlags.Instance
to get public instance fields. - Use
BindingFlags.Public | BindingFlags.Static
to get public static fields. - Use
BindingFlags.DeclaredOnly
to get only fields declared on the current type, not inherited fields.
Requirements
Interface | Supported in |
---|---|
.NET Framework | 4.0, 3.5, 3.0, 2.0, 1.1, 1.0 |
.NET Standard | 2.0, 1.0 |
.NET Core | 2.0, 1.0 |
.NET | 5, 6, 7, 8 |
See Also
- Type Class
- FieldInfo Class
- Type.GetField Method
- Type.GetFields(BindingFlags) Method
- System.Reflection Namespace
Example
Getting Public Fields of a Type
using System;
using System.Reflection;
public class ExampleClass
{
public int PublicIntField = 10;
private string _privateStringField = "Hello";
public static double PublicStaticDoubleField = 3.14;
}
public class Program
{
public static void Main(string[] args)
{
Type exampleType = typeof(ExampleClass);
Console.WriteLine($"Public fields of {exampleType.Name}:");
FieldInfo[] publicFields = exampleType.GetFields();
if (publicFields.Length == 0)
{
Console.WriteLine(" No public fields found.");
}
else
{
foreach (FieldInfo field in publicFields)
{
Console.WriteLine($" - {field.FieldType.Name} {field.Name}");
}
}
Console.WriteLine("\nGetting all fields (including private and static):");
FieldInfo[] allFields = exampleType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (FieldInfo field in allFields)
{
Console.WriteLine($" - {field.FieldType.Name} {field.Name} (IsPublic: {field.IsPublic}, IsPrivate: {field.IsPrivate}, IsStatic: {field.IsStatic})");
}
}
}