C# Object Initializer : Set Property from another one

纵饮孤独 提交于 2019-12-01 19:30:13
Jon Skeet

No, you can't do that. You'd have to just set it in a separate statement:

var obj = new MyObject();
obj.Test = obj.Id;

The right-hand side of the property in an object initializer is just a normal expression, with no inherent connection to the object being initialized.

If this is something you regularly want to do with one specific type, you could add a method:

public MyObject CopyIdToTest()
{
    this.Test = Id;
    return this;
}

and then use:

MyObject obj = new MyObject().CopyIdToTest();

or with other properties:

MyObject obj = new MyObject 
{
    // Set other properties here
}.CopyIdToTest();

No -- you can't access an object's properties inside an initializer. The initializer is basically some syntactic sugar for programmers.

Consider situations like:

class Program
{
    static void Main()
    {
     var Id = "hello";
    var obj = new MyObject
        {
            Test = Id // Get new GUID created in constructor
        };
    }
}

The Id you'd assign (if your idea was valid, which again, it isn't) isn't necessarily the Id you'd be getting.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!