Changing Accessibility of Abstract Properties in C#

Here we have an example interface with a read-only property.

This interface is used in various classes and methods as a way of providing an interface to a data model. We do not want to enable these consumer classes to write this property, so only a getter is provided.

public interface IPropExample
{
	int someProp { get; }
}

Of course, for testing and mock purposes we need to set this property somewhere else.

The first thing we’re doing is creating an abstract base class that implements the interface. This will allow us to add functionality that can be included with all derived classes.

public abstract class PropExample
{
	public abstract int someProp { get; set; }
}

Note that I’m not actually including any additional functionality. This is just an example.

Now we can implement the getter and setter in the derived class.

public class Prop : PropExample
{
	public override int someProp { get; set; }
}

And it’s that easy!

But wait… If it was going to be that easy, why does the interface not define a setter? Nothing using the interface will be able to access it anyway. Well, it’s because most classes won’t actually define a setter. So we end up with code like this everywhere:

public class Prop : PropExample
{
	public override int someProp
	{
		get;
		set
		{
			throw new NotImplementedException();
		}
	}
}

We even up doing this more often than not. So, is there a better way? There is!

public abstract class PropExample
{
	public virtual int someProp
	{
		get;
		set
		{
			throw new NotImplementedException();
		}
	}
}

Now you only need to define your getter on your override and override the setter only if it’s needed. It will throw an exception by default.

Keep in mind that this isn’t the best solution if you require the setter to always be used, since the compiler will not alert you at compile time if you forgot to create one.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s