I’m having trouble trying to set the value of a property after i cast it. I’m not sure if this is called boxing.
Anyways, the new variable is getting set, but the original is not. I thought the new variable is just a reference to the original. But when i check the intellisence/debug watcher, the original property is still null.
here’s the code.
// NOTE: data is either a Foo || FooFoo || FooBar, at this point. // only Foo impliments ITagElement. if (data is ITagElement) { var tags = ((ITagElement)data).TagList; // At this point, tags == null and data.TagList == null. if (tags.IsNullOrEmpty()) { tags = new List<Tag>(); } tags.Add(new Tag { K = xmlReader.GetAttribute('k'), V = xmlReader.GetAttribute('v') }); // At this point, Tags.Count == 1 and data.TagList == null :( :( :( }
Notice my inline comments about the values for tags and data.TagList ? Can some explain what I have done wrong? I thought the variable tags is just a reference pointer to the property data.TagList .. but it looks like it’s not.
Update / Answer 🙂
thanks for the answers guys! it’s embarassing cause i’ve been doing ths stuff for years and still forget/not notice simple things like this. (And of course, makes so much sence now that i see the light).
Marc got the points because his answer (IMO) was the simplest for my single blond brain cell.
Thanks all!
Tags and data are completely isolated variables. Just because you assign an object to
tags, this makes no difference to the variabledata.What you are getting confused is that when the two variables point to the same object, then changes to the (single) object will be seen through either variable.
Basically, if
datastarts non-null, you haveIn this scenario, adding an object to either
dataortagsis actually adding an object to the same ‘list A’However, if
datastarts null, you have:You then assign
tags, giving:You would have to manually assign the ‘list B’ to
datato make it stick.There is, however, one way to get it (assigning an interface/object) to work:
refand generics: