For example:
DataTable table = new DataTable()
{
Columns = new DataColumnCollection(
{
new DataColumn("col1"),
new DataColumn("col2")
})
});
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;})();
You probably need to remove the paretheses around that collection initializer for DataColumnCollection
, and remove the unmatched, final )
Those are syntactical issues, though. The underlying problems are that the Columns
property has no setter, and the DataColumnCollection
has no public constructor.
Basically, you have to instantiate and then call .Columns.Add()
.
If this is something you have to do a lot in your code, you could create helper classes that would give you friendlier syntax:
DataTable table = DataTableFactory.CreateTableWithColumns("col1", "col2");
There are 2 reasons why this won't work:
1) the Columns
property is read-only
2) the DataColumnCollection
class does not have a constructor that accepts a collection of columns to initialize it.
Best you can do is create the table in one line and add the columns in another:
DataTable table = new DataTable();
table.Columns.AddRange( new []
{
new DataColumn("col1"),
new DataColumn("col2")
});
To answer your other question, IF Columns
had a setter and IF DataColumnCollection
accepted columns in its constructor the syntax would be:
DataTable table = new DataTable()
{
Columns = new DataColumnCollection( new DataColumn[]
{
new DataColumn("col1"),
new DataColumn("col2")
})
});
The class DataColumnCollection
has no constructor so you can't manually create an instance. The compiler's error message should be pretty self-explanatory, saying something along the lines of:
The type 'System.Data.DataColumnCollection' has no constructors defined
You can add columns to the DataTable.Columns
collection by using the Add()
method:
DataTable table = new DataTable();
table.Columns.Add(new DataColumn("col1"));
table.Columns.Add(new DataColumn("col2"));
You can't use that syntax as the Columns property is readonly. I'd use the technique suggested by Gabe.