This is my code, it gives me CA2000 on "new DataTable()..." and "new DataColumn()..."s
usersDS.Tables.Add(new DataTable()
{
TableName = "Users",
Columns = { new DataColumn() { ColumnName = "Handle", DataType = typeof(string) }, new DataColumn() { ColumnName = "Nickname" ,DataType = typeof(string) } }
});
Is it possible to fix without declaring variables?
This is nearly a duplicate of How to fix a CA2000 IDisposable C# compiler warning, when using a global cache. Maybe it should be considered a duplicate of that one. I'm not sure.
Code Analysis is legitimately complaining that it is theoretically possible for the method to complete without the
IDisposable
object being disposed and without it being safely stored somewhere else. The latter can happen if an exception occurs during the initialization of theDataTable
object or adding theDataTable
object to theusersDS.Table
object (whatever that is).If you can guarantee that no exception will be thrown here, then IMHO it is perfectly fine to suppress the CA warning. In that case, you know more than CA can, and you're promising you know what you're doing.
If you can't make the guarantee, then no…it's not possible to fix the warning without introducing local variables so that you're able to dispose the object in the event of an exception. For example: