Search code examples
c#outobject-initializers

out parameters in object initializer during anonymous instantiation


If I have an object containing a public int property (public accessors), how can I parse a string to int when initializing this property at instantiation ?

// Given initialized DataTable table;
// Given public int IntProperty {get; set;} in public class MyObject    
table.Rows.Select(row => new MyObject 
{
   int.TryParse(row["stringValue"], IntProperty), // MyObject.IntProperty is unknown here
   IntProperty = int.TryParse(row["stringValue"], ... ) // IntProperty is known but what about the out int result argument of Int32.TryParse ?
});

EDIT : I could do this but want to know if there is a way to do it directly inside object initializer :

table.Rows.Select(row => {
    int.TryParse(row["stringValue"], out int intProperty);
    return new MyObject 
    {
       IntProperty = intProperty;
    }
});

Solution

  • I strongly agree Jeroen Mostert. Instead of "squeezing everything into an object-initializer", make your code readable and easy to unserstand. Than it´ll probably compile without problems:

    var result = new List<MyObject>();
    foreach(var row in table.Rows)
    {
        var instance = new MyObject();
        int value;
        if(int.TryParse(row["stringValue"], out value)
            instance.IntProperty = value;
        result.Add(instance);
    }
    

    In C#7 you can also simplify this a bit to the following:

    var instance = new MyObject();
    if(int.TryParse(row["stringValue"], out int value)
        instance.IntProperty = value;
    result.Add(instance);