Private 'set' in C# - having trouble wrapping my brain around it

前端 未结 9 2414
傲寒
傲寒 2021-02-12 10:34

I\'ve seen a lot of example code written using something like (please forgive how horribly canned this is):

public class Test
{
   public object Thingy { get; pr         


        
相关标签:
9条回答
  • 2021-02-12 11:10

    The private makes it into a readonly property. A common example is if you have multiple classes passing around a single object, you don't want another class to be able to modify the instance.

    0 讨论(0)
  • 2021-02-12 11:12

    As a simple example; it is a cheap way of making an "immutable enough" object (for use in threading, state, etc). But also anywhere where the client simply shouldn't need to assign it, or can't be trusted to assign it (correctly).

    Another example might be a list:

    public List<Foo> Items {get;private set;}
    

    since we might call obj.Items.Add() etc, but we would rarely assign obj.Items = .... However, this example is marred by needing explicit initialization in the constructor, and XmlSerializer hates it - to be honest for lists I mainly use:

    private readonly List<Foo> items = new List<Foo>();
    public List<Foo> Items {get { return items;}}
    

    which solves both of these.

    As another example, contrasting:

    private readonly int foo;
    public int Foo {get{return foo;}}
    

    vs

    private readonly int foo;
    public int Foo {get{return foo;} private set {foo=value;}}
    

    this pattern may be useful in serialization, for example with DataContractSerializer (with the addition of some attributes), since many serializers will still look for private accessors. This avoids us having to decorate our internal state (foo), but gives the veneer of privacy to the set.

    Ultimately anything can be bypasses and assigned via reflection, so private set is only intended to avoid accidental damage to data.

    0 讨论(0)
  • 2021-02-12 11:13

    I've seen this used with the design:

    public class whatever
    {
        public string WhateverId { get; private set; }
    
        public static whatever Create(string whateverId)
        {
            return new whatever() { WhateverId = whateverId };
        }
    }
    

    So you create whatever class, but after it's created the id can't be changed because it might break things that are connected to it.

    the private set just gives the simple initializer syntax, I kind of like it for some scenarios.

    Also can be used if it's changeable, but you need to manage it when changes are made

    public void SetWhateverId(string whateverId)
    {
        DisconnectAllCurrentWhateverIdReferences();
        WhateverId = whateverId;
        ReconnectAllPreviousWhateverIdReferences();
    }
    
    0 讨论(0)
提交回复
热议问题