1

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?

Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120

1 Answers1

2

You cannot refer to properties of the object you're constructing on the right-hand side of a =, i.e., 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,
};
dtb
  • 213,145
  • 36
  • 401
  • 431
  • Ok. But i was doing this in normal object construction before. Like MyClass obj=new MyClass(); obj.select=true; obj.edit=obj.select; I dont know why it is not there in Object Initializer :( – Murali Murugesan Jan 23 '13 at 12:49
  • Object initializer syntax does not support this. If you want to do this, don't use object initializer syntax. – dtb Jan 23 '13 at 12:49
  • The another important fact is i was calling another collection.Contains(key) to get bool value for it. In this case it calls 2 more times :( – Murali Murugesan Jan 23 '13 at 12:51
  • @Murali Just out of curiosity, why do you change from "normal object construction" to object initializer? One possibility is to use normal property assignment on a temp. variable, and then copy the reference from the temp. variable to the "permanent" variable once every propety assignment has succeeded. That's more or less what object initializers do. – Jeppe Stig Nielsen Jan 23 '13 at 12:55
  • @JeppeStigNielsen, i started using object initializer with lambda expression, something like collection.select(x=> new MyClass{...}). Now only getting new changes and more properties. – Murali Murugesan Jan 23 '13 at 13:12