Search code examples
c#visual-studio-2017stack-overflow

StackOverflow Exception when setting object variable


I am trying to extract data from a sql table, write it to an object and in turn put that in a list. I'm using VS2017, C# and MS-SQL 2008.

When I run the code it extracts the data from the SQL table; dumps it into some variables (I know this isn't the fastest, I just wanted to confirm I was getting them), I instantiate the object and try to set the first value, I then get the stack overflow on the set operation.

Why is it fine setting a variable and printing to screen, but not putting it into a variable?

Error;

System.StackOverflowException HResult=0x800703E9 Message=Exception of type 'System.StackOverflowException' was thrown.

Class;

class Company
{
    public String MDWRowNumber { get => MDWRowNumber; set => MDWRowNumber = value; } //errors here on set => MDWRowNumber = value
    public String MDWIdNumber { get => MDWIdNumber; set => MDWIdNumber = value; }
    public String MDWCompanyName { get => MDWCompanyName; set => MDWCompanyName = value; }
}

Main;

sql = "SELECT RowNo, Id, Name FROM Company;";
command = new SqlCommand(sql, connection);
reader = command.ExecuteReader();

while (reader.Read())
{
    Console.WriteLine(reader.GetValue(0).ToString());
    Console.WriteLine(reader.GetValue(1).ToString());
    Console.WriteLine(reader.GetValue(2).ToString());

    a = reader.GetValue(0).ToString();
    b = reader.GetValue(1).ToString();
    c = reader.GetValue(2).ToString();

    Console.WriteLine(a + " | " + b + " | " + c); // writes correct values as expected

    Company company = new Company();
    company.MDWRowNumber = a; /////Errors here/////
    company.MDWIdNumber = b;
    company.MDWCompanyName = c;
    //Company company = new Company()
    //    {
    //        MDWRowNumber = reader.GetValue(0).ToString(), ///// without all junk above errors here /////
    //        MDWIdNumber = reader.GetValue(1).ToString(),
    //        MDWCompanyName = reader.GetValue(2).ToString()
    //    };

    CompanyList.Add(company);
}

Console.WriteLine(CompanyList.First().MDWCompanyName);

reader.Close();
command.Dispose();

Solution

  • Here's the problem:

    public String MDWRowNumber { get => MDWRowNumber;
    

    The property calls itself - hence the stack overflow.

    Either use a private variable,

    private string _MDWRowNumber;
    public String MDWRowNumber { get => _MDWRowNumber; set => _MDWRowNumber = value; }
    

    or an auto property

    public String MDWRowNumber { get; set; }