Building a class whose property can only be set in the constructor, but anywhere?

I am trying to create a class that takes a value aas a parameter in its constructor. It has a private member variable that stores this value. After that, the value should not be changed.

Here is what I have, it works, but I don't think this is the best solution out there:

internal class Foo
{
    private int a;
    public int A
    {
        get
        {
            return this.a;
        }
    }

    public Foo(int a)
    {
        this.a = a;
    }
}

This way you cannot access afrom outside the class, and a-property only has a get method. However, you can still change ainside the class and use a property that returns only one variable, and nothing else looks silly.

Am I doing it right, or is there a way to improve my code / a more correct way to do this?

+5
3

, readonly !

public class Foo
{
    public Foo(int bar)
    {
        this.bar = bar;
    }

    public int Bar
    {
        get
        {
            return bar;
        }
    }
    private readonly int bar;
}
+6

" # 6 ". , readonly , get-only . , :

public class Class1
{
    public int A { get; }
    public Class1(int a)
    {
        A = a;
    }
}

..., :

public class Class1
{
    public int A { get; }
    public Class1(int a)
    {
        A = a;
    }
    public void Mutate()
    {
        // Class1.cs(11,9,11,10): error CS0200: Property or indexer 'Class1.A' cannot be assigned to -- it is read only
        A++;
    }
}

- /- .

+5
internal class Foo
{
    private readonly int _a;
    public int A 
    { 
        get
        {
            return _a;
        }
    }

    public Foo(int a)
    {
        _a = a;
    }
}

That should do it.

0
source

All Articles