Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
});
like image 645
FooBar Avatar asked Oct 29 '25 17:10

FooBar


2 Answers

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);
like image 166
MakePeaceGreatAgain Avatar answered Oct 31 '25 07:10

MakePeaceGreatAgain


If you are sure, your stringvalue will always be parseable to int you can use int.Parse()

Otherwise, you will also have to handle a failed parsing. You can do like this:

  • define the out parameter in the outer scope
  • use it in an assignment in case of successful parsing

WARNING This will fail, if you traverse your list in parallel!

    List<string> list = new List<string>{"1", "2", "3"}; 
    int i = 0;
    var ilist = list.Select(x => new MyObject {
        IntProperty = int.TryParse(x, out i) ? i : 0
    });

EDIT With inline declarations from VS2107 you can even do it without the variable from the outer scope

    List<string> list = new List<string>{"1", "2", "3"}; 
    var ilist = list.Select(x => new MyObject {
        IntProperty = int.TryParse(x, out int i) ? i : 0
    });
like image 21
derpirscher Avatar answered Oct 31 '25 06:10

derpirscher