I have an application which is made up of many different control types, each of which can, optionally, be linked with a parameter object.
These are then saved in an XML file for reloading later. To link the control to the parameter, where specified, the control stores the parameters ID. This is then searched for during loading and re-linked.
However as this is optional, if the parameter is not specified I get a NullReferenceException when trying to access the ID which is understandable. I could resolve this by putting a check around the line in question. However i would have to do this for many different control types and more than just one reference as show in this basic example.
So my question is, is there an elegant way to somehow allow this call to just return an empty string instead of this exception?
public class Parameter
{
public string ID;
}
public class LabelCtrl
{
public string Name;
public Parameter LinkedParameter;
}
public class XMLManager
{
public void SaveControl(ControlInstance_LabelCtrl ci)
{
xmlWriter.WriteStartElement("ControlInstance_LabelCtrl");
{
xmlWriter.WriteElementString("Name", ci.Name);
// Elegant way to insert empty string instead of causing NullReferenceException error
xmlWriter.WriteElementString("LinkedParameter", ci.LinkedParameter.ID);
}
xmlWriter.WriteEndElement();
}
}