C# Null Coalescing Operator

Few new operators have been introduced in C#2.0. Null Coalescing operator, which is one of them, is discussed in this post. While coding, we frequently need to perform null checks as follows–

Contact contact = provider.GetContact(contactId);
if (contact == null)
   contact = new Contact();

Instead of using if block we could just write it –

Contact contact = provider.GetContact(contactId);
contact = contact ?? new Contact();

It is pretty useful in the context of nullable types. It can also be handy while converting nullable type to value type, as shown below–

int? nullableInt = null;
int valueInt = nullableInt ?? default(int);

The valueInt become value type after executing this statement. But if we write something like this–

int? nullableIntAgain = nullableInt ?? 5;

the int literal 5 is automatically converted to a nullable type by CLR and afterwards, being assigned to nullableIntAgain. Subsequently, we can assign it to null now–

nullableIntAgain = null;

Isn’t pretty slick and handy? However, when using this operator we need to keep in mind that–

glyphicons Null coalescing operator can only be used in nullable or reference type. Otherwise it will raise an InvalidOperationException.

glyphicons We need to consider thread-safety also. Otherwise it could end up in race condition.

Hope it helps. Thanks!


[R-1: 29-03-2013] Updated formatting to make this post more consistent with current CSS.

Making [Web Method] Asynchronous using “OneWay “

By default Web methods called are synchronous like HTTP request and response architecture and rely on immediate response. But sometimes asynchronous operation might be the best suited for a particular operation. .Net Framework has good support for asynchronous operation. Simplest and easiest way to make a web method asynchronous is by using OneWay property, which we discuss in this post.

OneWay property is a part of SoapRpcMethod attribute. If we set its value to true – then client does not need to wait for the web service to finish the operation of the web method and returns immediately with Http Status code 202, which indicates that service started its operation and client does not need to come back to get the status. Example of an asynchronous web method using OneWay

[SoapRpcMethod(OneWay = true)]
public void StartLongRunningAsynchronousProcess() {
// start asynchronous process + client need not to wait for the response
view raw gistfile1.cs hosted with ❤ by GitHub

Return type of this type of web method should be nothing other than void. If we set the return type something else – then though it will compile – it will generate exception while it will be accessed.If we look at the WSDL for this service – we will find that there is no <output> element either in <portType> or <binding> elements of StartLongRunningAsyncronousProcess method.

We could see by looking at the <portType> element of the service:

<portType name="ServiceNameSoap">
<operation name= "StartLongRunningAsynchronousProcess">
<input message="s0: StartLongRunningAsynchronousProcessSoapIn"/>
view raw gistfile1.xml hosted with ❤ by GitHub

Execution status of a Workflow Instance

We can determine the Execution status of an workflow instance using the workflow definition.. Workflow definition of an workflow instance provice the current execution status. Base class Activity contain one field named – ExecutionStatus which is a member of ActivityExecutionStatus Enum. ActivityExecutionEnum contain following values –

  • Initialized
  • Cancelling
  • Closed
  • Executing
  • Faulting
  • Compensating

Example –

Console.WriteLine( "Workflow Execution status :{0} ", instance.GetWorkflowDefinition().ExecutionStatus.ToString());

Dehydration & Rehydration in WF

If we have a long running workflow tasks or have a  large number of workflow tasks executing , we can unload and store it in a temporary storage using Persistence services ships with Workflow Foundation.

Dehydration : Removing a workflow instance from execution status and storing it away for later recall is called Dehydration. Typically persistence services that comes with WF is used for this purpose, but you can write your own service to perform the same task.

Rehydration: When needed – the workflow instance is brought back from persistence service. The process of bringing it back into an execution status is known as Rehydration.

The main goal is to unload the long running tasks from memory and store then in temporary storage and retrieve it when its needed. And by this way – it’s possible to provide efficient memory utilization.

Interface 101: Explicit Interface Implementation using C#

The primary motivation of introducing inerface is to enforce OO-style of thinking while revoking the drawbacks of multiple inheritance. In fact, the support for explicit interface implementation is an important tool in OO-developers’ toolbox. Utilizing this concept, we can implement multiple interfaces in a class, and still no ambiguity gets introduced.

In fact, explicit interface implementation ensures private accessibility via interface reference. That is, in order to access any member of a class that implements an interface explicitly, an interface reference is required, which supports the concept called “Run-time Bindings“, and introduces a higher level of abstraction.

In the rest of the post we focus on following–

glyphicons Defining interfaces,
glyphicons Implementation of the interfaces explicitly,
glyphicons Advantages of explicit interface implementation.

To do so, we start by defining interfaces and shows how to apply explicit interface implementation using an example. Please note that, this is a simple and contrived example, intended only to be illustrative.

public interface ISimpleCalculator{
int Add(int num1, int num2);
public interface ICalculator{
double Add(double num1, double num2);

The following class Calculator implements both interfaces using explicit interface implementation.

public class Calculator:ISimpleCalculator,ICalculator{
int ISimpleCalculator.Add (int num1, int num2)
return num1 + num2;
double ICalculator.Add (double num1, double num2)
return num1 + num2;
view raw gistfile1.cs hosted with ❤ by GitHub

Now that we have implemented these interfaces, next we see outlines several examples to show how to use this implementation. The first example below tries to use the Add method without interface reference.

Calculator calc = new Calculator();
calc.Add(); // Uncomment it to get the Compile time Error
view raw gistfile1.txt hosted with ❤ by GitHub

Therefore, it gets a compile time error as the implementation is private and can only be accessed via interface reference as follows.

ISimpleCalculator simpleCalc = calc;
int result = simpleCalc.Add(5, 10); // returns 15
view raw gistfile1.txt hosted with ❤ by GitHub

As we have notice that the both interfaces have Add as a member. In fact, Calculator class also implements both Add method via polymorphic references. Next example shows how to invoke ICalculator.Add by using an instance of Calculator.

ICalculator floatingNumberCalculator = calc;
floatingNumberCalculator.Add(3.2 ,5.8);
view raw gistfile1.cs hosted with ❤ by GitHub

To sum up, the key take-aways from this discussion regarding explicit interface implementation are as follows.

glyphicons It make the whole implementation Abstract/Private . That is , you need the interface reference to access that implementation.

glyphicons It allow you to implement multiple Interface and at the same time, does not introduce any ambiguity. So, the polymorphic reference or runtime binding can be implement very efficiently.

We highly appreciate any comment or query regarding this post. Thanks!

See More


[R-1: 02-04-2013] Updated formatting to make this post more consistent with current CSS.