C # Object Initialiser - link to a new instance

Is there any way to get a link to the instance that I create using the object initializer

var x = new TestClass
           {
                 Id = 1,
                 SomeProperty = SomeMethod(this)
           }

"this" should point to the new instance of TestClass that I am creating. But this obviously applies to the instance of the class in which this code resides.

I do not ask if this is suitable for this. I know I can do it like this:

var x = new TestClass {Id= x};
x.SomeProperty = SomeMethod(this);

I have a complicated scenario in which a reference to a new instance in the object initializer will make life easier.

Is this possible anyway?

+3
source share
4 answers

, # , ", ."

, , , . ,

var temp = new TestClass();
temp.Id = 1;
temp.SomeProperty = SomeMethod(temp);
x = temp;

, temp , . this, - . SomeProperty = this.SomeMethod(this) temp.SomeProperty = this.SomeMethod(temp) temp.SomeProperty = temp.SomeMethod(temp)? , , ?

x, , . x , temp.SomeProperty = SomeMethod(x).

value . , value , getter set_SomeProperty(value). . , value , temp.SomeProperty = SomeMethod(value).

, , , newthis. , , newthis, . Microsoft, , , .

+5

, , - , - . x , . , .

var x = new TestClass {
    Id = 1
};
x.SomeProperty = SomeMethod(x);
+1
var x = new TestClass
           {
                 Id = 1,
                 SomeProperty = SomeMethod(this)
           }

, . , - .

0
source

Revealing or using an object that has not been completely constructed is usually a very bad idea. Consider the following:

class Connection
{
    internal string connectionString;
    public Connection(ConnectionPool pool, string connectionString) {
        this.pool = pool;
        //this.connectionString = connectionString; // I moved it because I could.
        this.pool.Register(this);
        this.connectionString = connectionString;
        this.Init();        
    }

    private void Init() { //blah }
}

class ConnectionPool
{
     public void Register(Connection c)
     {
         if ( this.connStrings.Contains( c.connectionString ) ) // BOOM
     }
}

This is a very contrived example. Things can get a lot worse. Below was a rather interesting link on this subject: Partially constructed objects

0
source

Source: https://habr.com/ru/post/1761483/


All Articles