Search code examples
c#accessor

What is the purpose of set { return; }?


I've seen the following code in various places:

 namespace My.name.space
    {
        class myClass
        {       
            public CustomObject Name
            {
                get { return new CustomObject (this.Dog); }
                set { return; }
            }

        }
    }

What is the purpose of set { return; }?

I don't understand what purpose set return would serve.

I would think you could just remove the set accessor completely.


Solution

  • None. It's somebody who doesn't quite know that a read-only property can be expressed much more simply by not including the set

    public Derp MuhDerp { get { return _derp; } }
    

    Interesting point brought up by CSharpie in a comment...

    If you have to have a set because it is defined in an interface, you can add the set but omit the return:

    public Derp MuhDerp { get { return _derp; } set { } }
    

    Of course, if the interface defines a setter, you should probably make sure it works as expected :)