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!
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.
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.
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.
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 =)
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With