Class property Retrieved and configured internally, but only retrieved externally

I understand that this may be something really basic, but I'm not sure of 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 want the property myStringto do the following:

  • Installed internally
  • Gettable internal interface
  • NOT installed outside
  • The resulting look

Therefore, I want to be able to set the variable myStringinside the class and make its value read-only from outside the class.

Is there a way to achieve this without using a separate get and set function and make the property myStringprivate, for example:

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;
    }
}

, myString .

protected, .

+5
4

, :

public class MyClass
{
    public string myString { get; private set; }
}

setter / memebers:

public class MyClass
{
    public string myString { get; internal set; }
}

.

+7

, :

public string MyString { get; private set; }

.

.

( , "" , internal #.)

+10
source

You can specify access modifiers for get and set, for example:

public string MyString
{
    get;
    private set;
}
+2
source
public string myString { get; private set; }
+2
source

All Articles