property marked with new keyword empty at runtime but base property is correct-Collection of common programming errors
I have quite a few problems, probably misunderstandings, about the new
keyword with properties in derived classes. Most of the documentation deals with new
on derived methods. For instance:
[DataContract]
[KnownType(typeof(PostCategory))]
public class BaseCategory : IEquatable
{
//...
///
/// Enables access to child categories (immediate ones). Filled in by data access provider. Not serializable.
///
public SortedDictionary Children { get; set; }
//...
}
[DataContract]
[KnownType(typeof(BaseCategory))]
public class PostCategory : BaseCategory
{
//...
public new SortedDictionary Children { get; set; }
//...
}
Then in my data repository implementation I have a generic implemenation for all the classes that derive from BaseCategory. I do this:
public class CachedXmlCategorizationProvider : ICategorizationRepository where T : BaseCategory, new()
{
private readonly ICacheProvider _cacheProvider = AppServices.Cache;
private readonly string _file = Path.Combine(XmlProvider.DataStorePhysicalPath, typeof (T).Name, "categorization.xml");
private SortedDictionary _dictionary;
//...
private SortedDictionary LoadFromDatastore()
{
if (!DefaultsExist())
{
return CreateDefaults();
}
var dcs = new DataContractSerializer(typeof (SortedDictionary));
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(new FileStream(_file, FileMode.Open, FileAccess.Read),
new XmlDictionaryReaderQuotas());
_dictionary = (SortedDictionary) dcs.ReadObject(reader, true);
/* HERE! Apparently this fills in the Children property of the base class */
// fill in Children
foreach (var pair in _dictionary)
{
pair.Value.Children = GetChildren(pair.Value.Id);
}
reader.Close();
return _dictionary;
}
//...
}
and when I try to access the Children
property of a specific PostCategory
instance at runtime it is null
and the base.Children
is set to the correct dictionary of Children as set by the GetChildren()
method.
The thing is, my code relies on checking the PostCategory.Children instance and because it’s null my code is failing.
What is the correct way to achieve what I want (have one base class and change the type of a property in derived class)?