I realise that this may be something really basic, but I'm not sure about the best practice to achieve the following.
I have the following class with a string property myString
:
public class MyClass
{
public string myString
{
get {
return myString;
}
}
public void AFunction()
{
// Set the string within a function
this.myString = "New Value"; // Error because the property is read-only
}
}
I wish the following to be true for the myString
property:
So I wish to be able to set the variable myString
within the class and make its value read-only from outside of the class.
Is there a way to achieve this without the use of a separate get and set function and making the myString
property private, like so:
public class MyClass
{
private string myString { get; set; }
public void SetString()
{
// Set string from within the class
this.myString = "New Value";
}
public string GetString()
{
// Return the string
return this.myString;
}
}
The above example allows me to set the variable internally, but not have read-only access to the actual property myString
from outside of the class.
I tried protected
but this doesn't make the value accessible from the outside.
It sounds like you just want:
public string MyString { get; private set; }
That's a property with a public getter and a private setter.
No need for extra methods at all.
(Note that the use of the word "internally" is potentially confusing here, given the specific meaning of the keyword internal
within C#.)
You can allow the setter only for the class members, usually constructor:
public class MyClass
{
public string myString { get; private set; }
}
Or you can allow setter within internal/assembly memebers:
public class MyClass
{
public string myString { get; internal set; }
}
The getter will be public.
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