Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda