Search code examples
c#system.reflection

Reflection not return value


I am trying to access field value using reflection, but cant make it work

public class Menssagens
{
    public string Teste2;

    public void Falar(string key, string id)
    {
        string json = File.ReadAllText(@"bin/" + id + ".json");
        Menssagens dotNet = JsonConvert.DeserializeObject<Menssagens>(json);
        Console.WriteLine(dotNet.Teste2); //Works fine
        Console.WriteLine(typeof(Menssagens).GetField(key).GetValue(this)); 
        //Dont works, returns nothing
    }

Solution

  • You're accessing the property value on this. You never set it on this, so it returns null.
    You probably want to access the value on the instance you created.

    In fact, your method should be static.