Elegant code question: How to avoid creating unneeded object

Posted by SeaDrive on Stack Overflow See other posts from Stack Overflow or by SeaDrive
Published on 2010-04-07T21:04:54Z Indexed on 2010/04/07 21:13 UTC
Read the original article Hit count: 205

Filed under:
|

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);

© Stack Overflow or respective owner

Related posts about c#

Related posts about code-elegance