ForteBass

Member
  • Content count

    1
  • Joined

  • Last visited

Community Reputation

106 Neutral

About ForteBass

  • Rank
    Newbie
  1. C# List<t> problem when adding Classes to it

    In line with Rid and Darookie, why are you creating an List and an array? ListMarkets is already a dynamically-sized array with all the same functionality of the static-sized MarketArray. That is you can give it a ListMarkets[integer] just like you can do a MarketArray[integer]. If by unique names you meant unique variable names, then you might misunderstand reference types. Take a look at this code: [source lang="csharp"]class MarketPlace{ List<Market> listMarkets = new List<Markets>(); void MakeMarket(){ Market aMarket = new Market(); listMarkets.Add(aMarket); } // This is, of course, bad because listMarkets could be empty, but it's just an example. void ChangeMarket(){ listMarkets[0].value = 200; } }[/source] So, if you call MakeMarkets twice, then ChangeMarket, listMarkets[1]. value is still the default of 0 (or whatever is in the Market constructor). You don't need an array to keep unique variable names. This is because the variable name aMarket is local to the MakeMarket call, so after the call finishes, that variable is deleted. But since the "new" operator creates instances in the heap, the "new Market" is saved by the listMarkets as long as it's not deleted from that list. aMarket and listMarkets keep a "reference" to the Market made in MakeMarkets. But the Market instance itself is stored elsewhere in memory. [quote name='darookie' timestamp='1344786721' post='4968736'] [source lang="csharp"] // 2) Unique name using list index (example only works for single list per class type) class Market2 { // here the constructor not only assign the name but also adds the instance to the list public Market2(IList&lt;Market2&gt; list) { Name = list.Count; list.Add(this); } int Name { get; private set; } }[/source] [/quote] Don't use this if you ever plan on deleting Markets. If you make two markets, then delete the first one, the next one added will have the same name as the one remaining. In this case, it's better to use a Dictionary<int, Market>, it should look more like this: [source lang="csharp"] // 2) Unique name using list index (example works for multiple lists per class type) class Market2 { static int marketCount = 0; // here the constructor not only assign the name but also adds the instance to the list public Market2(IDictionary&lt;int, Market2&gt; list) { Name = marketCount++; list.Add(Name, this); } int Name { get; private set; } }[/source]