Profile Picture

Sirwan Afifi

Stories from a web developer.

© 2017. Sirwan Afifi All rights reserved.

Explicit Interface Implementation

Let’s imagine that you have a class with two methods:

public class VendingMachine
{
    public bool InsertCoin(float amount)
    {
        if (amount < 500)
        {
            return false;
        }
        return true;
    }

    public string Buy()
    {
        return "Buy";
    }
}

Now when we want to create an instance of this class and call one of those methods, it executes as expected:

VendingMachine machine = new VendingMachine();
machine.InsertCoin(5); // false
machine.Buy();         // "Buy"

Now suppose that we have an interface called IVendingMachine that has two methods:

public interface IVendingMachine 
{
    bool InsertCoin(float amount);
    string Buy();
}

We want our class to implements this interface:

public class VendingMachine : IVendingMachine
{
    public bool InsertCoin(float amount)
    {
        if (amount < 500)
        {
            return false;
        }
        return true;
    }

    public string Buy()
    {
        return "Buy";
    }
}

Our class satisfied the interface because it has the methods with the same names. So Visual Studio doesn’t give you a compiler error. Now let’s imagine that we also want to add interface’s methods to this class, So, in this case, we must explicitly prefix the methods with IVendingMachine.:

public class VendingMachine : IVendingMachine
{
    public bool InsertCoin(float amount)
    {
        if (amount < 500)
        {
            return false;
        }
        return true;
    }

    bool IVendingMachine.InsertCoin(float amount)
    {
        if (amount < 300)
        {
            return true;
        }
        return false;
    }

    public string Buy()
    {
        return "Buy";
    }

    string IVendingMachine.Buy()
    {
        return "IVendingMachine Buy";
    }
}

Note that Visual Studio can help you to implement interface explicitly by pressing Ctrl + . on the name of the interface and select Implement interface explicitly:

Now, what happens when we call the InsertCoin and Buy methods? In this case, we should consider two different situations when we create the object:

  • Concrete Type
  • Interface Variable

If we want the methods of VendingMachine we should create the object with concrete type:

VendingMachine machine = new VendingMachine();
machine.InsertCoin(5); // false
machine.Buy();         // "Buy"

If we want the methods of IVendingMachine we should create the object with interface variable:

IVendingMachine machine = new VendingMachine();
machine.InsertCoin(5); // true
machine.Buy();         // "IVendingMachine Buy"

Delegates in C#

Lately I have been studying some topics in C# in order to improve myself. I think Delegate is one of those topics which is kinda difficult for beginners to initiate with. So, in order to make it clear how it works, I’m going to make some explanations in this post.

What are Delegates?

Delegate was introduced in C# 1. Think of it as a simply being a placeholder for functions that’ll be called at some point in time. Assume you want to declare a variable that is a reference to a specific method. In this case, the variable encapsulates some executable code and you can invoke the variable just like an actual method. In doing so, we need to create a delegate

Defining a Delegate

Delegates are created using delegate keyword along with the function signature:

delegate int Sum(int a, int b);

As you can see we are defining a delegate called Sum that is compatible with any method with an int return type with two parameters. Actually we defined a type that we can use to create variables and point those variables to methods that have the same signature and same return type. The type defenition for a delegate describes the method that we want to call:

int Add(int a, int b) => a + b;

Now we can assign a method to the delegate variable. This assignment creates a delegate instance:

Sum s = Add;

Now we can invoke the delegate instance in the same way as a method:

int result = s(5, 6);

Advantages of Delegate

  • Delegates are type safe, It means that the C# compiler checks the function signatures of a Delegate when you use them at runtime.
  • Can be used to define callback functions.
  • Can be dynamically switched at runtime.

Real World example

Suppose that you want to implement something like a Repeater control in your ASP.NET MVC application, As you probably know a Repeater is(was) server side databound control in ASP.NET WebForm for displaying information, It had a lot of flexability becuase you had complete control over the your markup.

public static class Helpers
{
	public delegate HelperResult ItemTemplate<T>(T input);

	public static HelperResult Repeater<T>(this HtmlHelper html,
	  IEnumerable<T> items,
	  ItemTemplate<T> itemTemplate,
	  ItemTemplate<T> alternatingitemTemplate = null)
	{
		return new HelperResult(writer =>
		{
			int i = 0;
			foreach (var item in items)
			{
				var func = i % 2 == 0 ? itemTemplate : alternatingitemTemplate;
				func(item).WriteTo(writer);
				i++;
			}
		});
	}
}

As you can see we emulated the ItemTemplate and AlternatingItemTemplate using a delegate. In this case user can pass the data and the data will be rendered inside the view. In this case the delegates act like callback.
The ItemTemplate delegate in our example can be replaced with Func delegate:

Func<T, HelperResult> itemTemplate,
Func<T, HelperResult> alternatingitemTemplate = null

Now we can use our helper inside any view:

<table>
    <tr>
        <td>Id</td>
        <td>Name</td>
    </tr>
    @Html.Repeater(Model, @<tr>
	    <td>@item.Title</td>
	    <td>@item.Price</td>
	</tr>, 
	@<tr class="alert-info">
	    <td>@item.Title</td>
	    <td>@item.Price</td>
    </tr>)
</table>

If you run the application you can see the result:

You can check out the GitHub repository for this post.

Thinking out of the box to become a better programmer

Image courtesy of http://goo.gl/iu68gq

Today I was talking with a friend of mine about thinking, The topic is interesting and I wanted to share it with you because as a programmer we are always thinking and trying to find solutions. Actually it’s a good habit when you want to learn something new, instead of taking action and delve into the details, you should think about that and break it down into several pieces then construct it as a big picture. Once you get familiar to it you can start trying to figure out each individual piece, By doing so you will become great in your field.

Image courtesy of http://goo.gl/Xi2Cn4

On the other hand, thinking isn’t the only thing for being an expert in programming. Suppose that you are given a challenging feature to implement in a team you’re working with, you might spend days and days trying to implement this feature and each time you fail and stuck in it then you try to find a solution on the net or asking questions on Stackoverflow. I’m not saying you shouldn’t google about your problem, What I’m saying is that you should understand the problem, This is where a Thinking out of the box’s metaphor comes into play.

This is very helpful because when you ran into a problem you should first think about it in a new or a different prespective, For example you can put yourself in end user’s place and try to figure it out. Once you understand it, you can start coding the feature. By doing so you can help yourself and believe me it works like a charm and you don’t need to post off-topic questions every single day on Stackoverflow anymore, Instead when you run into a serious problem, you can post your question and get extra votes :)

So thinking out of the box helps us to think like a programmer, It also helps you to approach problems in new ways.