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?

1
  • is noting to worry about, is noting at all. Commented Jan 23, 2013 at 12:45

1 Answer 1

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

5 Comments

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 :(
Object initializer syntax does not support this. If you want to do this, don't use object initializer syntax.
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 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.
@JeppeStigNielsen, i started using object initializer with lambda expression, something like collection.select(x=> new MyClass{...}). Now only getting new changes and more properties.

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.