13

I have three collections:

private ICollection<FPTAssetClassAsset> wrassets;
private ICollection<FPTFundAsset> wrfunds;
private ICollection<FPTManagedStrategyAsset> wrstrats;

If a foreach loop returns 0 objects, the collections don't get set and are therefore null. When i add this icollection (Union) to another icollection it fails with: "Value cannot be null" because the icollection is null, rather than being Empty. How can i set this collection as empty instead?

Loop:

    public void GetWrapperAssets(FPT fpt)
    {
        foreach (var w in fpt.CouttsPositionSection.Wrappers
        .Union(fpt.StandAloneSection.Wrappers)
        .Union(fpt.BespokePropositionSection.Wrappers)
        .Union(fpt.NonCouttsPositionSection.Wrappers)
        )
        {
            foreach (var a in w.UnderlyingAssets.OfType<FPTManagedStrategyAsset>())
            {
                wrstrats.Add(a);
            }
            foreach (var a in w.UnderlyingAssets.OfType<FPTAssetClassAsset>())
            {
                wrassets.Add(a);
            }
            foreach (var a in w.UnderlyingAssets.OfType<FPTFundAsset>())
            {
                wrfunds.Add(a);
            }
        }
    }
Marc Howard
  • 395
  • 2
  • 6
  • 25

3 Answers3

8

Initialise your collections before the foreach loop, this way they will always have a value:

private ICollection<FPTAssetClassAsset> wrassets = new Collection<FPTAssetClassAsset>();
private ICollection<FPTFundAsset> wrfunds = new Collection<FPTFundAsset>();
private ICollection<FPTManagedStrategyAsset> wrstrats = new Collection<FPTManagedStrategyAsset>();
James
  • 2,195
  • 1
  • 19
  • 22
  • 1
    Thanks, i couldn't initialise a new Collection because of an abstract class, so used List instead and worked a charm. – Marc Howard Jan 30 '14 at 16:59
5

Well, you can always check for null before adding. Or you can turn it into a property:

private ICollection<FPTAssetClassAsset> wrassets
{ 
    get { return _wrassets == null ? new List<FPTAssetClassAsset>() : _wrassets; }
}
private ICollection<FPTAssetClassAsset> _wrassets;
Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
  • 1
    Where are you setting the value of _wrassets? Wouldnt the above code always return a new List() since _wrassets is never set? – O.MeeKoh Dec 30 '19 at 23:14
4

You can use Array.Empty<T> if you're just looking for something that won't crash upon a read until you can get around to replacing it with something you use in earnest:

private ICollection<FPTAssetClassAsset> wrassets      = Array.Empty<FPTAssetClassAsset>();
private ICollection<FPTFundAsset> wrfunds             = Array.Empty<FPTFundAsset>();
private ICollection<FPTManagedStrategyAsset> wrstrats = Array.Empty<FPTManagedStrategyAsset>();
Caius Jard
  • 72,509
  • 5
  • 49
  • 80