C # object initializer: setting a property from another

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

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 this in an object initializer:

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

Is it possible?

+4
source share
2 answers

No, you cannot do this. You just need to install it in a separate statement:

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

The right side of the property in the initializer of the object is just a normal expression that does not have a built-in connection with the initialized object.

If this is what you usually want to do with one particular type, you can add a method:

 public MyObject CopyIdToTest() { 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(); 
+8
source

No - you cannot access the properties of the object inside the initializer. The initializer is basically syntactic sugar for programmers.

Consider situations such as:

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

Id that you would assign (if your idea was valid, but that is not the case) will not necessarily be the Id that you get.

+1
source

All Articles