Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the value of a read-only property with generic getters and setters?

Tags:

c#

properties

Not sure if I worded this correctly ... but I have the following code:

    public Guid ItemId
    {
        get;
    }

    public TransactionItem()
    {
        this.ItemId = Guid.Empty;
    }

Naturally I am getting a read-only issue ... which I do understand. Is there anyway to set this property value without having to do something like the below:

    Guid _itemId = Guid.Empty;
    public Guid ItemId
    {
        get
        {
            return _itemId;
        }
        set
        {
            _itemId = value;
        }
    }

or

    public Guid ItemId
    {
        get;
        internal set;
    }

Thanks in advance!

like image 608
mattruma Avatar asked Feb 19 '09 12:02

mattruma


People also ask

Can we change the value of readonly in C#?

Use the readonly keyword in C# This means that the variable or object can be assigned a value at the class scope or in a constructor only. You cannot change the value or reassign a value to a readonly variable or object in any other method except the constructor.

What is read only property in C sharp?

In C#, a readonly keyword is a modifier which is used in the following ways: 1. Readonly Fields: In C#, you are allowed to declare a field using readonly modifier. It indicates that the assignment to the fields is only the part of the declaration or in a constructor to the same class.

What is readonly property?

The readOnly property sets or returns whether a text field is read-only, or not. A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it.


2 Answers

I would go for this:

public Guid ItemId
{
    get;
    private set; // can omit as of C# 6 
}

public TransactionItem()
{
    this.ItemId = Guid.Empty;
}

Of course, it would be open for setting within this class, but since you are writing it I hope you have the sense to not break your own intentions...

In my opinion, things like readonly properties, are mostly important when seen from the outside. From the inside, it doesn't really matter what it is, cause there, you are the King =)

like image 78
Svish Avatar answered Oct 24 '22 13:10

Svish


If you just need the ItemId property to be read-only for external users of your class, then Svish's answer is the way to go.

If you need ItemId to be read-only within the class itself then you'll need to do something like this:

private readonly Guid _ItemId
public Guid ItemId
{
    get { return _ItemId; }
}

public TransactionItem()
{
    _ItemId = Guid.Empty;
}
like image 33
LukeH Avatar answered Oct 24 '22 15:10

LukeH