Skip to content

Commit ec153b6

Browse files
committed
fix(datatable): handle Nullable<T> and existing columns in AddColumn<T>
1 parent 91151c5 commit ec153b6

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

SharpHelpers/SharpHelpers/DataTableHelper.cs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ string Escape(string s)
7878
foreach (DataRow row in table.Rows)
7979
lines.Add(string.Join(delimiter, row.ItemArray.Select(v => Escape(v?.ToString()))));
8080
return string.Join(Environment.NewLine, lines);
81-
}
81+
}
8282

8383
/// <summary>
8484
/// Adds a new column to the DataTable with the specified default value.
@@ -87,17 +87,24 @@ string Escape(string s)
8787
/// <param name="columnName"></param>
8888
/// <param name="defaultValue"></param>
8989
/// <typeparam name="T"></typeparam>
90-
public static void AddColumn<T>(this DataTable table, string columnName, T defaultValue = default)
90+
public static void AddColumn<T>(this DataTable table, string columnName, T defaultValue = default!)
9191
{
9292
if (table == null) throw new ArgumentNullException(nameof(table));
93-
94-
var column = new DataColumn(columnName, typeof(T)) { DefaultValue = defaultValue };
95-
table.Columns.Add(column);
93+
if (string.IsNullOrWhiteSpace(columnName)) throw new ArgumentException("Empty", nameof(columnName));
94+
if (table.Columns.Contains(columnName))
95+
return;
96+
97+
var t = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
98+
var col = new DataColumn(columnName, t)
99+
{
100+
DefaultValue = defaultValue!
101+
};
102+
table.Columns.Add(col);
96103
foreach (DataRow row in table.Rows)
97104
{
98-
row[columnName] = defaultValue;
105+
row[columnName] = defaultValue!;
99106
}
100-
}
107+
}
101108

102109
/// <summary>
103110
/// Merges multiple DataTables with the same schema into one.

0 commit comments

Comments
 (0)