Use of unassigned local variable error

I am getting a "Use of unassigned local variable 'statementrec'" error on line 22 of one of my case statement that is in a while loop.  My other case statements use "statementrec"  and there are no swiggle errors except on my case statement "B".   I have attached code for viewing.  Any ideas???

thanks
nick
while ((line = file.ReadLine()) != null)
            {
  
                Console.WriteLine(line);
                counter++;
                col16 = line.Substring(15, 1);
                linelen = line.Length; //used to get the end of line integer value
                switch (col16)
                {
                    #region cases
                    case "A":
                        StatementRecs statementrec = new StatementRecs();   // initialize
                        statementrec.StatementNo = Convert.ToInt32(line.Substring(1, 6));
                        statementrec.Regarding = line.Substring(95);  //don't put 2nd parm if you want end of line 
                        break;

                    case "B":
                        string x = "";
                        string y = "";
                        x = line.Substring(95, 7);
                        y = line.Substring(109, 5);
                        statementrec.FileNo = x + " " + y; <<<<====== this is where I get the error
                        break;

                    case "C":
                        {
                            c_counter++;

                            // Description 
                            statementrec.Descriptions.Add(line.Substring(34, 21));   <<<=== Statementrec is okay here
                              ...
                              ...
                              ..
                        }
                        break;
                        
                       case "D":                     
                       case "E"
                              ...

                }   
            }     


...
...
  public class StatementRecs
    {
        #region variables definitions
        // Auto Property
        public string name { get; set; }
        public string StreetAddress { get; set; }
        public string CityStateZip { get; set; }
        public DateTime InvDate { get; set; }
        public int StatementNo { get; set; }
        public string Regarding { get; set; }
        public string FileNo { get; set; }
        public List<string> Descriptions { get; set; }
        public List<decimal?> PriorBals { get; set; }
        public List<DateTime?> BillThruDts { get; set; }
        public List<decimal?> NewChgs { get; set; }
        public List<DateTime?> PaymentDts { get; set; }
        public List<decimal?> PaymentAmts { get; set; }
        public List<decimal?> NewBals { get; set; }
        public decimal? TotalPriorBal { get; set; }
        public decimal? TotalNewChg { get; set; }
        public decimal? TotalPayment { get; set; }
        public decimal? TotalBalDue { get; set; }
        public string Footer1 { get; set; }
        public string Footer2 { get; set; }
        public string InCareOf { get; set; }
        public string AddressError { get; set; }
        #endregion

        public StatementRecs() //constructor
        {
            this.Descriptions = new List<string>();
            this.PriorBals = new List<decimal?>();
            this.BillThruDts = new List<DateTime?>();
            this.NewChgs = new List<decimal?>();
            this.PaymentDts = new List<DateTime?>();
            this.PaymentAmts = new List<decimal?>();
            this.NewBals = new List<decimal?>();
        }

Open in new window

LVL 1
countyprobSystem AnalystAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

DanMerkCommented:
The problem occurs because this line is inside the case statement A:
StatementRecs statementrec = new StatementRecs();   // initialize

If the code enters the switch and col16 met the condition to go to case B, then the system would be attempting to access the Descriptions properties of an object that has not been assigned. If you move the above statement above the switch, this error should go away.

PS- Visual Studios, in my experience, will tend not to show multiple unassignment errors if they relate to the same variable.
0
countyprobSystem AnalystAuthor Commented:
The reason I put it in case "A" was because I need to run through the while loop with all my case statements (A-E) before I recreate the a new "statementrec".   In case statement "E" I write the contents from "statementrec" into a dataset.  Then I want to initalize the "statementrec" for a new set of data to run though for case statements A-E again.  I even tried a "if" statement but I guess the problem will still exist the line is inside the "if" statement.  Unfortunately I'm think like a Foxpro programmer and don't have the nuances down.  Any suggestions on to how handle the decribed logic??

nick


            bool init_rec_sw = true;

            while ((line = file.ReadLine()) != null)
            {
                if (init_rec_sw == true)
                {
                //    //instanitate the variable we are going to use to hold readfile data
                    StatementRecs statementrec = new StatementRecs();
                    init_rec_sw = false;  // set false until entire account is populated
                }
                ...
                ...
                ////StatementRecs statementrec = new StatementRecs();
                switch (col16)
                {
                    #region cases
                    case "A":
                        
                        statementrec.StatementNo = Convert.ToInt32(line.Substring(1, 6));
                        statementrec.Regarding = line.Substring(95);  //don't put 2nd parm if you want end of line 
                        break;

                    case "B":
                        ...
                        statementrec.FileNo = x + " " + y;
                        break;
                        
                   case ....
                   case "E":
                        write the record to dataset
                        init_rec_sw = true;
                }
            }

Open in new window

0
DanMerkCommented:
With any C language (be it C, C++, or C#) a variable's scope (or existance) is restricted by the curly brackets: {}. By instanitating it in the if statement, you are restricting its scope to the if statement; therefore, once that code is executed, the program losses all knowledge of statementrec.  

Let me think about your code. I will get back.
0
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

DanMerkCommented:
Can you provide a psuedo code version of what the switch does? I think the problem is that you need to use a different construct, like another while loop,  if...else, etc.
0
countyprobSystem AnalystAuthor Commented:
I have attached a with sample data and code.  In addition I have also attached code snippet outlining how I writing the code.  Thank you again for assisting.

nick
StreamReader file = new StreamReader(filepath);   //prepare correct file to read
           StatementRecs statementrec = new StatementRecs(); // this is where I was orginally instantiating
           while ((line = file.ReadLine()) != null)  //read file line by line
            {
                counter++;
                col16 = line.Substring(15, 1);   //look for a specific character in position 15 in the file
                switch (col16)      // check character that was found a execute appropriate case statement
                      case "A":     // when the character is "A" pick out specific info and populate the instance
                        
                        statementrec.StatementNo = Convert.ToInt32(line.Substring(1, 6));
                        statementrec.Regarding = line.Substring(95);  //don't put 2nd parm if you want end of line 
                        break;

                    case "B":
                        ...
                        statementrec.FileNo = x + " " + y;    //same thing here for character "B"
                        break;
                        
                   case ....
                   case "E":
                        write the record to dataset           // when you find chaacter "E" then write the data
                        // need to reinitialize the "statementrec" for the next read

                }
            }

Open in new window

Here-is-what-the-data-looks-like.txt
0
DanMerkCommented:
The way I see it, you have two while statements happening here. The first one is going thru each line of an individual record, and the other is going thru a list of records. Therefore, I’m thinking you should do two while loops with the inner loop containing a modified switch. I would recommend doing something like this. By using End_of_Record as a referee value for the inner while loop, we can decide when a record is done. This code does make one huge assumption: The will be no incomplete records (ie. if a record exists, then it WILL END with an E and not an end of file or EOF).

StreamReader file = new StreamReader(filepath);   //prepare correct file to read
bool End_of_Record = false;
int counter = 0;

while ((line = file.ReadLine()) != null)  //read file line by line
{
            StatementRecs statementrec = new StatementRecs();
            counter++;
            End_of_Record = false;
           
            while (!End_of_Record)
            {
                        col16 = line.Substring(15, 1);   //look for a specific character in position 15 in the file
                        switch (col16)    
                                    case "A":    
                                                statementrec.StatementNo = Convert.ToInt32(line.Substring(1, 6));
                                                statementrec.Regarding = line.Substrin(95);
                                                break;
                                    case "B":
                                               ...
                                               statementrec.FileNo = x + " " + y;    //same thing here for character "B"
                                               break;
                                    case ....
                                    case "E":
                                                write the record to dataset        
                                                End_of_Record = true;
                        line = file.ReadLine();
            }
}
0
DanMerkCommented:
I'm sorry, I have some messed up logic. Hopefully this is all set (more importantly is the idea behind this). Here is the correction:

StreamReader file = new StreamReader(filepath);   //prepare correct file to read
bool End_of_Record = false;
int counter = 0;
line = file.ReadLine()

while (line  != null)  //Check to see if we are out of records
{
            StatementRecs statementrec = new StatementRecs();
            counter++;
            End_of_Record = false;
           
            while (!End_of_Record)
            {
                        col16 = line.Substring(15, 1);   //look for a specific character in position 15 in the file
                        switch (col16)    
                                    case "A":    
                                                statementrec.StatementNo = Convert.ToInt32(line.Substring(1, 6));
                                                statementrec.Regarding = line.Substrin(95);
                                                break;
                                    case "B":
                                               ...
                                               statementrec.FileNo = x + " " + y;    //same thing here for character "B"
                                               break;
                                    case ....
                                    case "E":
                                                write the record to dataset        
                                                End_of_Record = true;
                        line = file.ReadLine();
            }
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
countyprobSystem AnalystAuthor Commented:
Aha, brilliant.  Why didn't think of 2 loops.  Thanks, I'm back on track again after a week of headache.  

Nick
0
countyprobSystem AnalystAuthor Commented:
Excellent tip.  
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.