how to set an empty iCollection c#

Marc Howard picture Marc Howard · Jan 30, 2014 · Viewed 22.9k times · Source

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);
            }
        }
    }

Answer

James picture James · Jan 30, 2014

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>();