Property readonly .NET

8

I received this question in a test and could not answer:

"How can I declare a readonly property in .NET / C #?"     
asked by anonymous 31.01.2014 / 15:36

5 answers

9

Mads Torgersen (C # design team) has announced that this is a feature that is being considered for the next release (C # 6.0?).

Currently:

private readonly int x;
public int X { get { return x; } }

With C # 6.0:

public int X { get; } = x;  

Source: Probable C # 6.0 features illustrated

    
31.01.2014 / 15:46
9

Just use the readonly modifier in a field:

public readonly int Numero;

For example. Thus, Numero can only be assigned a value in the class constructor.

Note that readonly is not used on a property; To make a property read-only, set its setter to private :

public int Numero { get; private set; }
    
31.01.2014 / 15:38
2

One way is to create a property without Set

public int PropriedadeReadOnly
{
    get { return propriedadeReadOnly; }
}

And a second form, which allows the property to be written only once, usually in the constructor of a class. It is using readonly

public readonly PropriedadeRead;
    
31.01.2014 / 17:04
2

To set a read-only priority, we have two options, either to place the get in the declaration of the property or to declare the set as private.

    
03.02.2014 / 15:33
0

In the case of VB net, you can write like this:

Public ReadOnly valor_pi as Single = 3.1415
    
31.01.2014 / 15:40