简体   繁体   中英

How to assign a same value to different properties using Object Initializer

I try to assign a value to two different properties in object initializer and failed.

In below code i try to assign Expand and Select properies to true. But i got the error ' The name Select doesnt exist in the current context '

Here is my code

public class MyClass{
public String Title{get;set;}
public String Key{get;set;}
public bool Expand{get;set;}
public bool Select{get;set;}
public bool Editable{get;set;}
}

new MyClass()
  {
   Title = "Murali",
   Key = "MM",                       
   Expand = Select = true
  }

Also i need to assign another property Editable based on this two properties

Something like

new MyClass()
  {
   Ediatable=(Select && Expand)
  }

How can i do the above logic? Does Object Initializer has a support of it?

You cannot refer to properties of the object you're constructing on the right-hand side of a = , ie, you can only assign to the properties, but not read from them.

Possible solution:

var expandAndSelect = true;

var result = new MyClass
{
    Title = "Murali",
    Key = "MM",                       
    Expand = expandAndSelect,
    Select = expandAndSelect,
};

and

var select = true;
var expand = false;

var result = new MyClass
{
    Expand = expand,
    Select = select,
    Editable = select & expand,
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM