Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid creating unneeded object in an elegant way?

Tags:

c#

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);
like image 388
SeaDrive Avatar asked Apr 07 '10 21:04

SeaDrive


3 Answers

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
like image 112
itowlson Avatar answered Nov 15 '22 01:11

itowlson


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);
like image 44
Reed Copsey Avatar answered Nov 15 '22 00:11

Reed Copsey


            ...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.

like image 39
gingerbreadboy Avatar answered Nov 14 '22 23:11

gingerbreadboy