4

I have the following object where in my constructor I add a new Guid as the Id.

public class MyObject
{
  public MyObject()
  {
    Id = Guid.NewGuid().ToString();
  }

  public String Id { get; set; }
  public String Test { get; set; }

}

I want to do something like that in an object initializer :

var obj = new MyObject
{
  Test = Id; // Get new GUID created in constructor
}

Is it possible?

2 Answers 2

8

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Note that the constructor has completed before the "property setting" part of the initializer executes.
Yes -- I was conflating the initialization with construction. I'll edit for clarity, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.