Explicit interface implementation in .NET Part 2

In the previous post we introduced the idea of explicit interface implementation in .NET. We also saw two examples from .NET with explicit implementation in action.

Let’s first see how this language structure works in C#. Suppose we have the following interface:

public interface ISummable
{
	int Calculate(int a, int b);
}

We can then implement this interface implicitly as follows:

public class Calculator : ISummable
{
	public int Calculate(int a, int b)
	{
		return a + b;
	}
}

This should be straightforward for all programmers.

Let’s have another interface:

public interface IMultipliable
{
	int Calculate(int a, int b);
}

We then want our calculator to implement the above interface as well:

public class Calculator : ISummable, IMultipliable
{
	public int Calculate(int a, int b)
	{
		return a + b;
	}
}

As Calculator already has a Calculate method with two integer parameters it also satisfies IMultipliable without changing the Calculator object implementation.

This is problematic as we have no straightforward way to provide a multiplication for our calculator:

Calculator calculator = new Calculator();
int res = calculator.Calculate(2, 5);

“res” will be 7 of course.

We assume here that we cannot change the method names of ISummable and IMultipliable. They may be part of a third party library. One way out of this situation is to implement IMultipliable explicitly. If you right-click “IMultipliable” in Calculator.cs in Visual Studio you can select “Implement Interface”, “Implement Interface Explicitly” in the context menu. You’ll get the following stub:

public class Calculator : ISummable, IMultipliable
{
	public int Calculate(int a, int b)
	{
		return a + b;
	}

	int IMultipliable.Calculate(int a, int b)
	{
		throw new NotImplementedException();
	}
}

The structure of the new Calculate method looks very much like the non-generic GetEnumerator method of the second example of the previous post.

Explicitly implemented interface methods must not have any access modifiers. They are public by default.

Let’s implement the new method:

int IMultipliable.Calculate(int a, int b)
{
	return a * b;
}

How can we call this method? We have to declare Calculator as an interface type:

public void ShowSample()
{
	IMultipliable calculator = new Calculator();
	int res = calculator.Calculate(2, 5);
}

“res” will now be 10.

We’ll investigate this further in the next post.

View all various C# language feature related posts here.

Domain Driven Design with Web API revisited Part 2: the problem domain and DDD basics refreshed

Introduction

In the previous post we went through DDD at a very high level. We discussed the cases when DDD can be a good solution and when it could rather be overkill. We saw that a complex domain model with lots of behaviour and logic could well justify the usage of DDD. On the other hand a project with more simple use cases such as CRUD could be made lighter with just plain classes filled with public getters and setters. It’s also an option to just pick certain ideas from DDD in your project. DDD is full of useful guidelines and patterns that are beneficial to software projects of all sizes.

In this post we’ll describe the problem domain of our demo application. We’ll also refresh our knowledge of some basic DDD concepts.

Read more of this post

Explicit interface implementation in .NET Part 1

The generic and well-known Dictionary object and its generic and thread-safe counterpart, i.e. the ConcurrentDictionary object both implement the generic IDictionary interface. The IDictionary interface has an Add method where you can insert a new key-value pair into a dictionary:

Dictionary<string, string> singleThreadedDictionary = new Dictionary<string, string>();
singleThreadedDictionary.Add("Key", "Value");

I can even rewrite the above code as follows:

IDictionary<string, string> singleThreadedDictionary = new Dictionary<string, string>();
singleThreadedDictionary.Add("Key", "Value");

However, what if we try to do the same with the concurrent dictionary?

Read more of this post

Domain Driven Design with Web API revisited Part 1: introduction

Introduction

Domain driven design (DDD) has been around since 2003 when Eric Evans published his groundbreaking book on the subject. It is quite a large and complex topic with a steep learning curve. Chances are that it will take years of training and hands-on experience before you can get fluent with all its parts. Also, it takes truly large projects, like SAP with all its modules, to utilise all ideas presented by DDD. I have to admit that I’ve only come to work with a subset of DDD, such as aggregate roots, value objects, entities, repositories etc., and haven’t worked with e.g. an anti-corruption layer. That’s fine, applying DDD to a software project doesn’t necessitate using every single field from DDD. You could then easily bloat your project unnecessarily.

Read more of this post

Summary of thread-safe collections in .NET

The System.Collections.Concurrent namespace has 4 thread-safe collections that you can use in multi-threaded applications. The starting point is that you have a multi-threaded app where the same collection needs to be accessed by different threads. In that case the well-know collection types, like HashSet, List, Dictionary etc. simply won’t be enough.

If many different threads have access to the same resource then there’s no guarantee on the state of that resource in the moment a thread accesses it in some way: deletion, lookup, insertion or modification. Another thread may have accessed the same resource just milliseconds before that and the other thread will access the resource under the wrong assumptions. You’ll end up with buggy code with unpredictable results and ad-hoc fixes and patches that probably won’t solve the root of the problem.

Read more of this post

Using a thread-safe dictionary in .NET C# Part 4: thread-safe insertlookups

In the previous post we looked at how the AddOrUpdate method worked. We saw that it was a very neat and thread-safe way to either insert a new key-value pair or update an existing one.

We’ve already seen a thread-safe method that helps you retrieve values by their keys in this post: TryGet. It returns true if the item could be retrieved. TryAdd on the other hand is used to insert a new key-value pair. It also returns true if the item could be inserted successfully. However, what do you do with the returned boolean values? Do you keep trying in some loop until it succeeds?

Read more of this post

Web API 2 security extensibility points part 5: OWIN

Introduction

In the previous post we discussed how to add a custom authorisation filter to your .NET web application. We saw how you could derive from the AuthorizeAttribute class and implement your own logic for the IsAuthorized and HandleUnauthorizedRequest methods. The methods in the custom authorisation filter are called after any authentication filter is applied and before the appropriate controller action is executed.

In this post we’ll look at another entry point where you can apply your custom security logic in a .NET web application: OWIN

Read more of this post

Using a thread-safe dictionary in .NET C# Part 3: thread-safe modifications

In the previous post we looked at the 4 Try methods of ConcurrentDictionary that support CRUD operations: retrieval, deletion, update and insertion. We saw some basic examples for their usage and concluded that TryUpdate was not a very good solution to actually update an item due to race conditions.

This is where another method called AddOrUpdate enters the scene.

Read more of this post

Web API 2 security extensibility points part 4: custom authorisation filters

Introduction

In the previous post we built a custom HTTP message handler for our demo Web API 2 application. We saw how a registered message handler intercepts all calls to your API before authentication filters are executed. We also wrote a couple of examples where we checked for the presence of a custom header and of an authorisation header. We finally showed how to set the principal for the current HTTP call.

In this post we’ll see another way you can intercept the calls to your API. Authorisation filters are executed after authentication filters and before your controller action methods. That is the last stage where you can add your custom auth-related logic.

Read more of this post

Using a thread-safe dictionary in .NET C# Part 2: CRUD operations

In the previous post we briefly introduced the ConcurrentDictionary object. We said that it was the thread-safe counterpart of the standard Dictionary object. The Dictionary object is not suited as a shared resource in multi-threaded scenarios as you can never be sure if another thread has added to or removed an element from the dictionary just milliseconds earlier. A ConcurrentDictionary is a good option to cure the shortcomings of the thread-sensitive Dictionary object but it is also more difficult to use.

We’ll briefly look at the 4 Try methods that enable you to insert, remove, update and lookup elements in the ConcurrentDictionary.

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.