For example:
DataTable table = new DataTable()
{
Columns = new DataColumnCollection(
{
new DataColumn("col1"),
new DataColumn("col2")
})
});
You are talking about the Collection Initialiser feature added in C# 3. It is done like this:
DataTable table = new DataTable()
{
Columns =
{
new DataColumn("col1"),
new DataColumn("col2")
}
};
This does not call a collection constructor, it uses the collection which already exists in the DataTable.
This is short-hand for Columns.Add(), so it doesn't require Columns to have a setter.
You were so close with the code in your question!
The Columns
property does not have a setter so you can only modify it.
How about this:
DataTable table = new DataTable();
table.Columns.AddRange(new[] { new DataColumn("col1"), new DataColumn("col2") });
If you want to do with one statement in a lambda:
DataTable table = (() => {
var table = new DataTable();
table.Columns.AddRange(new[] { new DataColumn("col1"),
new DataColumn("col2") });
return table;})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With