Posts Tagged ‘csharp’

Quick Tip – C# property with abstract getter, concrete setter

The Problem

On a recent .NET project I was defining an abstract class in C# when I came upon a unusual case: I needed a property that had an abstract getter, but a concrete setter. In other words, the getter needed to be implemented by all derived classes and the setter does not, in fact its defined in the abstract class. Nothing I like more than a good object oriented programming quandry.

Here’s some code to help make sense of it:

public abstract class BaseClass 
{
    private string _baseValue;
    public abstract string Value 
    {
        get;
        // the "set" will cause a compile error.  You can't define the get or set inside
        // of an abstract property.
        set 
        {
            _baseValue = value;        
        }
    }
}


The Solution

While the above syntax will generate a compile time error, there is a fairly simple way to work around the issue. Check out this code:

public abstract class BaseClass 
{
    private string _baseValue;
    protected abstract string ValueGet();
    protected void ValueSet(string baseValue) 
    {
        _baseValue = baseValue;
    }
 
    public abstract string Value 
    {
        get 
        {
            // as implemented by the derived class
            return this.ValueGet();
        }
        set 
        {
            // as implemented by BaseClass, or derived class override
            this.ValueSet(value);        
        }
    }
}

Here we delegated the setting and getting of the property to separate protected methods within BaseClass. Now that 2 methods are used we can assign whether or not they are abstract separately. The getter must be implemented by the derived classes, the setter may or may not be.

And that’s it. Obviously this code also works vice versa, with the setter being abstract and the getter being concrete. It’s nice because from the perspective of someone using your code, nothing changes with regards to the public Value property. The use of protected methods to defer overriding and abstraction help you avoid writing any unnecessarily redundant code in your derived classes. It’s a nice little trick to have in your pocket.

Happy C# OOP’ing!

Quick Tip: Deserializing XML to objects in C#

The Overview

Here’s a quick example of how you can deserialize XML into C# objects. This will be brief, so feel free to ask questions in the comments for more details.

We are going to write a small class and program to deserialize objects.xml into a MyObject object that can then be used in the main program, Program. Its not rocket science, but it beats the hell out of manually parsing XML to get the information we need.

The Code


objects.xml

>
  >
    >ObjectName>
    >123>
    >2010-12-15T08:54:11>
    >ridiculously long name>
  >
  >
    >AnotherObject>
    >235435>
    >2010-12-15T08:59:51>
    >seriously, its way too long>
  >
  >
    >TheLastObject>
    >>
    >2010-12-15T09:04:43>
    >no way this is gonna be the property name>
  >
>


MyObject.cs

using System;
using System.Xml.Serialization;
 
namespace MyNamespace
{
    public class MyObject
    {
        public string name;
        public int intValue;
        public DateTime timestamp;
 
        [XmlElement("elementNameDifferentThanObjectPropertyName")]
        public string extraValue;
 
        public MixOrder() 
        {
            name = "";
            intValue= 0;
            timestamp = new DateTime();
            extraValue = "";
        }
    }
}

Notice I used the XmlElement attribute for the XML field with the obscenely long name. XmlElement specifically represents System.Xml.Serialization.XmlElementAttribute. This allows us to assign an element or attribute of the XML to a public property of the deserialized object even if their names don’t match. This is useful in the case of undesirable XML element names that are hard to work with or break coding conventions. Also, and more importantly, as the XML you deserialize changes over time, you can just adjust the name of the XmlElement attribute if necessary without changing the functionality of the object.


Program.cs

using System;
using System.Xml;
using System.Xml.Serialization;
using MyNamespace;
 
namespace TestConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List<MyObject> myObjects = new List<MyObject>();
            XmlSerializer serializer = new XmlSerializer(typeof(List<MyObject>));
            XmlReader reader = XmlReader.Create("objects.xml");
            myObjects = (List<MyObject>)serializer.Deserialize(reader);
 
            // now you can perform operations on your list of MyObject objects,
            // no manual XML parsing necessary.
 
            Console.WriteLine("Press  key to exit.");
            Console.ReadLine();
        }
    }
}

I leave the processing of the object up to you, but the process is clear. We create a XmlSerializer that corresponds to the type of our object, create a XmlReader for the XML, then use the serializer to deserialize the XML from the reader. From there you have a successfully populated List list. Do with it what you will.

In the words of the Beastie Boys, “That’s it, that’s all, that’s all there is.” See ya at the next quick tip.