user2969489
user2969489

Reputation: 179

Columns.Add() vs new DataColumn()

I feel confused on how to insert a new column on a table, and what's the difference between Columns.Add() and new DataColumn()?

DataTable student = new DataTable("Students");
student.Columns.Add("ID", typeof(int));


DataColumn id = new DataColumn("ID");
id.DataType = typeof(int);
student.Columns.Add(id);

Upvotes: 1

Views: 4477

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

DataColumnCollection.Add is just short-cut for creating column and adding it. As MSDN says:

Creates and adds a DataColumn object that has the specified name and type to the DataColumnCollection.

And this is how it implemented:

public DataColumn Add(string columnName, Type type)
{
    DataColumn column = new DataColumn(columnName, type);
    this.Add(column);
    return column;
}

As you can see, internally it creates new instance of DataColumn and adds it to itself.

NOTE: You can use DataColumn constructor which accepts column data type as second parameter. Thus your second sample could look like:

student.Columns.Add(new DataColumn("ID", typeof(int)));

But anyway, I think first 'short-cut' option is more readable and compact. You might want to use latter approach if you already have some columns, or if you have columns of custom type inherited from DataColumn.

Upvotes: 2

Related Questions