Reputation: 7301
I create a dictionary as you can see :
public Dictionary<string, string> TipList
{
get { return TipList; }
set { TipList = value; }
}
I fetch some data from a service and I want to put these data into my dictionary as you can see here :
Dictionary<string, string> dict = new Dictionary<string, string>();
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
var list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(objText).ToDictionary(x => x.Keys, x => x.Values);
object o;
object o1;
foreach (var item in list)
{
o = item.Value.ElementAt(0);
o1 = item.Value.ElementAt(1);
dict.Add(o.ToString(), o1.ToString());
}
GlobalVariable.TipListCache.Add(NewCarReceiption.CSystem.Value, dict);
NewCarReceiption.TipList = dict.Where(i=>i.Key!=null & i.Value!=null).ToDictionary(x => x.Key, x => x.Value);
}
}
}
But after running my code when the above function is trying to put their data into my dictionary .my application returns this error :
Upvotes: 1
Views: 379
Reputation: 37299
Your setter is calling the TipList
property's setter (itself) which is calling its setter and so on - resulting in the exception.
Initialize it like this:
private Dictionary<string, string> _tipList;
public Dictionary<string, string> TipList
{
get { return _tipList; }
set { _tipList = value; }
}
Or best, if you do not need any behavior other than the default, with the auto-implemented property:
public Dictionary<string, string> TipList { get; set; }
and since C# 6.0 you can also initialize it like this ( with Auto-property initializers):
public Dictionary<string, string> TipList { get; set; } = new Dictionary<string, string>();
Upvotes: 3
Reputation: 156978
You are setting the same property over and over again, going into an infinite loop.
If you don't need any additional logic in your getter and setter, you might just leave it auto-implemented:
public Dictionary<string, string> TipList
{
get;
set;
}
If you do need more logic in your getter and setter, you have to add a backing field yourself:
private Dictionary<string, string> tipList;
public Dictionary<string, string> TipList
{
get
{
DoSomethingBeforeGet();
return this.tipList;
}
set
{
DoSomethingBeforeSet();
this.tipList = value;
DoSomethingAfterSet();
}
}
Upvotes: 1