The root of my question is that the C# compiler is too smart. It detects a path via which an object could be undefined, so demands that I fill it. In the code, I look at the tables in a DataSet to see if there is one that I want. If not, I create a new one. I know that dtOut will always be assigned a value, but the the compiler is not happy unless it's assigned a value when declared. This is inelegant.
How do I rewrite this in a more elegant way?
System.Data.DataTable dtOut = new System.Data.DataTable();
.
.
// find table with tablename = grp
// if none, create new table
bool bTableFound = false;
foreach (System.Data.DataTable d1 in dsOut.Tables)
{
string d1_name = d1.TableName;
if (d1_name.Equals(grp))
{
dtOut = d1;
bTableFound = true;
break;
}
}
if (!bTableFound) dtOut = RptTable(grp);
That initial value can be null
. The compiler doesn't require you to create an instance; it just requires you to assign a value.
System.Data.DataTable dtOut = null; // compiler is now happy
// rest of code as before
You can rewrite your method like so:
System.Data.DataTable dtOut = dsOut
.Tables
.Cast<System.Data.DataTable>()
.FirstOrDefault(t => t.TableName.Equals(grp))
?? RptTable(grp);
...program...
{
System.Data.DataTable dtOut = GetDataTableByName(grp, dsOut);
}
public DataTable GetDataTableByName(string grp, object dsOut)
{
foreach (System.Data.DataTable d1 in dsOut.Tables)
{
if (d1.TableName.Equals(grp))
return RptTable(grp)
}
return null;
}
If I've interperated your naming correctly.
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