ReadOnly vs Property within Assembly Question/Conundrum
-
22-08-2019 - |
Question
How can I make a Property "ReadOnly" outside the Assembly (DLL) for people using the DLL but still be able to populate that property from within the assembly for them to read?
For example, if I have a Transaction object that needs to populate a property in a Document object (which is a child class of the Transaction class) when something happens in the Transaction object, but I just want to developer using my DLL to only be able to read that property and not change it (it should only be changed from within the DLL itself).
Solution
C#
public object MyProp {
get { return val; }
internal set { val = value; }
}
VB
Public Property MyProp As Object
Get
Return StoredVal
End Get
Friend Set(ByVal value As Object)
StoredVal = value
End Set
End Property
OTHER TIPS
If you're using C# you can have different access modifiers on the get
and set
, e.g. the following should achieve what you want:
public int MyProp { get; internal set; }
VB.NET also has this capability: http://weblogs.asp.net/pwilson/archive/2003/10/28/34333.aspx
C#
public bool MyProp {get; internal set;} //Uses "Automatic Property" sytax
VB
private _MyProp as Boolean
Public Property MyProp as Boolean
Get
Return True
End Get
Friend Set(ByVal value as Boolean)
_MyProp = value
End Set
End Property
What language? In VB you mark the setter as Friend, in C# you use internal.