简体   繁体   中英

Set inner property Doesn't update on Outer Object

Below is my code:

void Main()
{
    Test test = new Test();
    test.inner.OperatorId = 5;
    Console.Out.WriteLine(test.inner.OperatorId); //returns 0; Why not 5?
}

public class InnerClass
{
   public string Text { get; set; }
   public long OperatorId { get; set; }
}
// Define other methods and classes here

public class Test{
    long operatorId;
    string text;
    public InnerClass inner
   {
       get
       {
           return new InnerClass
           {
               Text = text,
               OperatorId = operatorId
           };
       }
       set
       {
           text = value.Text;
           operatorId = value.OperatorId;
       }
   }
}

Why doesn't console.out return 5? classes in c# are by reference so affecting the inner object should also affect the reference to it in the outer class? How can I fix this?

Note: There is a reason why test is written this way. It's a simpler way of referring to asp.net controls.

There are two issues with your code. The second issue relates more to why you don't see the correct value. However, they're both involved in what's going on, so it's worth mentioning both of them.

Issue #1:

This line:

Console.Out.WriteLine(test.inner.OperatorId);

Calls the getter on inner property, which initializes a new instance of it (this happens every single time the getter is called):

get
{
    return new InnerClass
    {
        Text = text,
        OperatorId = operatorId
    };
}  

Are you trying to go for a singleton pattern? If that's the case, you could check if it's null and if it is, then initialize a new instance. Just be careful with singletons and thread safety. While if you make a fix suggested in the coverage of the second issue, a new instance will be initialized with the correct value... you would be creating a new instance every single time the getter gets called if you don't fix this issue.

Issue #2:

The second issue is something you've brought up in the comments after I posted the first part. Why isn't the new instance built with the set values? Well, let's take a look at how you're setting the value of 5 :

test.inner.OperatorId = 5;

Are you setting the inner property to a new value for the setter to trigger? No. You're setting the OperatorId property of the InnerClass . So, the operatorId field never gets that value.

Aside form the issues from the first part, if you wanted to keep the same code and get it to work, that line would have to be:

test.inner = new InnerClass { OperatorId = 5 };

This sets inner property to a new instance of the InnerClass with the desired OperatorId value, which sets the operatorId field to the appropriate value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM