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

113
Visualizações
Don't allow object to be changed

I have a read-only object but somewhere it's properties getting updated. Does C# have anything to restrict that too from direct changes as well as via reflection?

Here is the POC code

class Program
{
    static void Main(string[] args)
    {
        ReadOnlyCreator tester = new ReadOnlyCreator();
        tester.ModifyTester();
        Console.ReadLine();
    }
}

class ClassUnderTest
{
    public string SomeProp { get; set; }
}

class ReadOnlyCreator
{
    private readonly ClassUnderTest _classUnderTest;
    public ReadOnlyCreator()
    {
        _classUnderTest = new ClassUnderTest { SomeProp = "Init" };
    }

    public void ModifyTester()
    {
        Console.WriteLine("Before: " + _classUnderTest.SomeProp);
        var modifier = new Modifier(_classUnderTest);
        modifier.Modify();
        Console.WriteLine("After: " + _classUnderTest.SomeProp);
    }
}
class Modifier
{
    private ClassUnderTest _classUnderTest;
    public Modifier(ClassUnderTest classUnderTest)
    {
        _classUnderTest = classUnderTest;
    }

    public void Modify()
    {
        _classUnderTest.SomeProp = "Modified";
    }
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you want a read only object you should make it read only. i.e.

class ClassUnderTest
{
    public string SomeProp { get;  }
    public ClassUnderTest(string someProp) => SomeProp = someProp;
}

You could also use init only setters if you are using c#9. This allow the property to be set only during construction of the object:

class ClassUnderTest
{
    public string SomeProp { get; init; }
}

If you are using value types you can (and should) declare the whole type as readonly. See also Choosing Between Class and Struct

public readonly struct StructUnderTest

This does not protect against reflection or unsafe code. Using these features is deliberately circumventing the rules, so it is up to the developer to ensure it is safe.

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