I was writing a bubblesort in C# and ran into this problem. Below are my classes and after the classes I will describe my problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BubbleSort
{
class Person
{
public String FirstName { get; set; }
public String LastName {get; set;}
public String PhoneNumber { get; set; }
public Person(String firstName, String lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
namespace BubbleSort
{
class ListProvider
{
//Class Variables
private StreamReader fileReader;
//private List<Person> test;
#region Properties
public List<Person> TheList
{
get { return TheList; }
set { TheList = value; }
}
#endregion
/// <summary>
/// I wish C# had a Scanner class :/. How different are these languages really?
/// </summary>
/// <param name="fileName"></param>
public ListProvider(string fileName)
{
// test = new List<Person>();
using (fileReader = new StreamReader(fileName))
{
String line = "";
while (fileReader.Peek() != -1)
{
line = fileReader.ReadLine();
String[] nameArray = line.Split(' ');
TheList.Add(new Person(nameArray[0], nameArray[1]));
//test.Add(new Person(nameArray[0], nameArray[1]));
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
ListProvider listProvider = new ListProvider("C:\\Users\\JC Boss\\Desktop\\Career\\Programming Practice\\BubbleSort\\BubbleSort\\names.txt");
foreach (Person person in listProvider.TheList)
{
Console.WriteLine(person.FirstName + " " + person.LastName);
}
}
Okay. So when I try and add a new Person to this list, I get a stack overflow exception. Now, if I were to uncomment the List variable test, and add to that. It would work fine, and would throw no error. Why is this happening? I looked around but could not see why this would happen to a property? } }
public List<Person> TheList
{
get { return TheList; }
set { TheList = value; }
}
This setter refers to itself. Any attempt to read or write to it will cause an infinite recursion.