i need to access reflection a private static string[] from a class in csharp

To access a private static string array using reflection in C#, you can follow these steps:

  1. Get the type of the class that contains the private static string array using the typeof operator.
  2. Use the GetField method to retrieve the FieldInfo object representing the private static string array.
  3. Set the BindingFlags parameter to include NonPublic and Static to access private and static members respectively.
  4. Use the GetValue method of the FieldInfo object to get the value of the private static string array.

Here's an example code that demonstrates this:

main.cs
using System;
using System.Reflection;

public class MyClass
{
    private static string[] myArray = { "item1", "item2", "item3" };
}

public class Program
{
    public static void Main()
    {
        Type type = typeof(MyClass);
        FieldInfo field = type.GetField("myArray", BindingFlags.NonPublic | BindingFlags.Static);
        
        string[] value = (string[])field.GetValue(null);
        
        foreach (string item in value)
        {
            Console.WriteLine(item);
        }
    }
}
508 chars
24 lines

In the Main method of the Program class, we use typeof(MyClass) to get the Type object representing MyClass. Then, we use GetField method with the field name "myArray" and the appropriate BindingFlags to retrieve the FieldInfo object. Finally, we use GetValue method on the FieldInfo object, passing null since the field is static, to get the value of the private static string array.

related categories

gistlibby LogSnag