Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Object Initializer : Set Property from another one

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?

like image 713
danbord Avatar asked Feb 17 '23 07:02

danbord


1 Answers

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();
like image 78
Jon Skeet Avatar answered Mar 05 '23 03:03

Jon Skeet