2

Suppose I have this code:

List<MyObj> resultList = new List<MyObj>();
foreach (var item in collection)
{
    resultList.Add(new MyObj
    {
       X = item.foo,
       Y = item.bar,
       Z = [I want it to be X + Y]
    });
 }

I can't use the 'this' keyword. Is there another way of accomplishing this? Thanks!

Alonzzo2
  • 959
  • 10
  • 24

2 Answers2

3

You can't do it inside the object initializer, you'll have to do it externally after creating an instance of MyObj:

var resultList = collection.Select(myObj => 
{
    var newObj = new MyObj
    {
        X = item.foo,
        Y = item.bar,
    };
    newObj.Z = newObj.X + newObj.Y;
    return newObj;
}).ToList();
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
2

Allowing it in the object initialiser would be dangerous, you'd be able to access properties of the object before its constructor has finished execution. If you know your properties don't do anything weird though, if you know that calling the getter right after you set the value simply produces the value that you set, you can move the logic out of the initialiser.

var resultList = (
    from item in collection
    let X = item.foo
    let Y = item.bar
    let Z = X + Y
    select new MyObj {
        X = X,
        Y = Y,
        Z = Z
    }).ToList();