Question

I am having trouble using an IList property which always seems to return null, even though the member is is getting is instantiated:

    private List<ModelRootEntity> _validTargets = new List<ModelRootEntity>();

    public IList<IModelRootEntity> ValidTargets
    {
        get
        {
            return _validTargets as IList<IModelRootEntity>;
        }
        protected internal set
        {
            if (value == null)
                _validTargets.Clear();
            else
                _validTargets = value as List<ModelRootEntity>;
        }
    }

ModelRootEntity implements IModelRootEntity. I watched both values during debugging, whilst the member shows a positive count, the property stays null.

I also tried raising an exception within the property getter to throw if the counts of _validTargets and _validTargets as List<ModelRootEntity> are different, but it never threw.

Found question [Dictionary properties are always null despite dictionaries being instantiated, which seems similar, however in my case this seems to happen regardless of serialization.

Any ideas?

Was it helpful?

Solution 2

I found the answer, thanks to @Nilesh comment above.

Replacing:

private List<ModelRootEntity> _validTargets = new List<ModelRootEntity>();

with:

private List<IModelRootEntity> _validTargets = new List<ModelRootEntity>();

exposed the real issue. The second line will not compile. The following post explained why: C# newbie List<Interface> question

The only odd thing was the exception I tried to force which never threw, and "threw" me off.

OTHER TIPS

If you set your property to any value that isn't a List<ModelRootEntity>, the as expression will return null and the property will become null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top