Marc Howard
Marc Howard

Reputation: 425

how to set an empty iCollection c#

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

Upvotes: 16

Views: 38346

Answers (3)

Caius Jard
Caius Jard

Reputation: 74605

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

Upvotes: 9

James
James

Reputation: 2201

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

Upvotes: 9

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

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;

Upvotes: 6

Related Questions