Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.1K
Visualizações
Set Property of Instance without Setter

Suppose I have a class and an interface that looks like this:

[Serializable]
public class MyClass : IClass
{
   public int Prop => 42;
}

public interface IClass
{
   int Prop { get; }
}

As you can see there's no Setter. But I was hoping to use reflection to change the Prop property but I can't seem to do it. Here's what I have so far:

var property = typeof(MyClass).GetProperty("Prop", BindingFlags.Instance | BindingFlags.Public);
property.SetValue(instaneOfClass, 31);

I keep getting this error: System.ArgumentException: Property set method not found.

Shouldn't this work? How can I set the property without using a setter?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Auto implemented properties have backing fields named <PropName>k__BackingField.

In your case you would access this backing field like this:

var property = typeof(MyClass).GetField("<Prop>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
property.SetValue(instanceOfClass, 31);

Note that I'm calling GetField() instead of GetProperty(), and using BindingFlags.NonPublic instead of BindingFlags.Public, since the backing field is private.

However, since this is an expression bodied member (lambda syntax), no backing field is generated. Instead of relying on another member, the getter simply returns the result of the given expression, and the compiler doesn't need to generate a backing field.

Implementing your property with an explicit getter will generate a backing field, and the above code will work.

public class MyClass : IClass
{
   public int Prop { get; } = 42;
}
over 4 years ago · Santiago Trujillo Relatório

0

If you specify a getter you'll have a compiler generated field that contains the property name. You can then modify the value of this field using reflection (GetFields, SetValue):

public class Foo        {
        public Foo() => Bar = 42;
        public int Bar { get; }        

        static void Main()  {
           var f = new Foo();
           Console.WriteLine(f.Bar); // ==> 42;
           f.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic).First(x => x.Name.Contains("Bar")).SetValue(f, 43);
           Console.WriteLine(f.Bar); // ==> 43;
  }
}

It does not work for a computed property as in your example.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda