Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Property, Gettable and settable internally, but only gettable externally

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:

  • Settable internally
  • Gettable internally
  • NOT settable externally
  • Gettable externally

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.

like image 578
Luke Avatar asked Apr 10 '13 11:04

Luke


2 Answers

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#.)

like image 149
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet


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.

like image 44
beardeddev Avatar answered Oct 12 '22 23:10

beardeddev