0

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?

Stefan de Kok
  • 2,018
  • 2
  • 15
  • 19
  • Why are you casting at all? Why not make the types match? – SLaks Sep 01 '13 at 03:47
  • 1
    Why dont you change it to `private List _validTargets = new List(new List());` – Nilesh Sep 01 '13 at 06:46
  • SLaks, Nilesh, good question. Probably deserves its own thread. I am open to advice on this. The `ModelRootEntity` is used within the domain and many internal methods expect more members than `IModelRootEntity` declares (which are the ones exposed via DTO's outside the domain). So I either cast once inside the property or in every internal use. Figured, doing it once was cleaner. – Stefan de Kok Sep 01 '13 at 12:01
  • @SLaks, Nilesh, decided to open this as a new question: http://stackoverflow.com/questions/18560845/exposing-a-listdomain-objects-via-an-ilistinterface – Stefan de Kok Sep 01 '13 at 17:12

2 Answers2

0

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

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.

Community
  • 1
  • 1
Stefan de Kok
  • 2,018
  • 2
  • 15
  • 19