Evil Code #007: Overloads

Time to do a bit of Evil Code again. Let’s look into following set of classes first.

public class BaseParameter { }
public class DerievedParameter :BaseParameter { }

public class BaseClass
{
   public void Foo(DerievedParameter param) => Console.WriteLine($"Inside {nameof(BaseClass)}");
}

public class DerievedClass : BaseClass
{
   public void Foo(BaseParameter param) => Console.WriteLine($"Inside {nameof(DerievedClass)}");
}

The client code looks like following.

var instance = new DerievedClass();
instance.Foo(new DerievedParameter());
instance.Foo(new BaseParameter());

What could be output of the above ? There might be tendency that the one might be inclined to think about an output that resembles following.

Inside BaseClass
Inside DerievedClass

But interestingly that is not quite right. The overload rules ensures that when there is a probable method in the most derieved compile type, the derieved method is chosen, even if there is a better choice in base class. The output of the code would be as following.

Inside DerievedClass
Inside DerievedClass

This is one of the reasons why overloading of base class methods are not recommended.

Let’s take a step further and introduce IEnumerable as method parameters. That’s when things get even more interesting.


public class BaseClass
{
  public void Foo(DerievedParameter param) => Console.WriteLine($"Inside {nameof(BaseClass)}");
  public void Bar(IEnumerable<DerievedParameter> paramList) => Console.WriteLine($"Inside {nameof(BaseClass)}");
}

public class DerievedClass : BaseClass
{
  public void Foo(BaseParameter param) => Console.WriteLine($"Inside {nameof(DerievedClass)}");
  public void Bar(IEnumerable<BaseParameter> paramList) => Console.WriteLine($"Inside {nameof(DerievedClass)}");
}
 instance.Bar(new List<DerievedParameter> { new DerievedParameter(), new DerievedParameter() });
instance.Bar(new List<BaseParameter> { new BaseParameter(), new BaseParameter() });

What could be the output of above ? As per our earlier knowledge, the output would be

Inside DerievedClass
Inside DerievedClass

Well, the actual answer is slightly more complicated. If you are running the code in a framework above 4.0, then you are bang on target. But, if the target framework is lesser, you are in for a surprise.

Inside BaseClass
Inside DerievedClass

The reason for the above scenario is that post 4.0, C# generic interfaces support covariance and contravariance, which wasn’t the case for frameworks prior to that. This results in above scenario.

Happy Coding

Lazy Cache

Recently came across this small but highly effective caching library called LazyCache. While I have been familiar with the in-memory caching functionalities of .Net such as ObjectCache and MemoryCache, LazyCache provides a neat threadsafe wrapper around the conventional options. It also make sure you don’t need to implement the Cache Aside pattern yourself as the library takes care of it themselves.
Let’s write an example code to demonstrate the usage.

_cache = new CachingService(new MemoryCacheProvider(new MemoryCache(new MemoryCacheOptions())));
_cache.GetOrAdd("Test", () => GetFromWebService());


As you can see, the usage is pretty simple and straightforward. The highly effective design of GetOrAdd method allows you to fetch the cached data from memory, or if not, it is unavailable, evaluate the Func delegate to fetch the required data from the original source.

The ability to inject the caching service means, you could also take advantage of other services like the Redis ObjectCache.

APM/EAP to TAP

Asynchronous Programming has evolved over the years, right from the APM to the extremely powerful TAP Model. One (or probably the only one) of the problem which developers find themselves in is to use legacy code which were written somewhere in between the evolution. Quite often, developers might be inclined to wrap the existing code to the latest TAP model. How do one do that ? Let’s examine each model and its conversion one by one.

Asynchronous Programming ModelĀ 

APM was the very first model introduced by the .Net designers, however it is no longer a recommended pattern. We will begin by writing an example code in APM, before figuring out how to convert it to TAP.

 

string filePath = @"yourfilepath";
byte[]  buffer = new byte[20000];
using(FileStream  fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous))
{
       Console.WriteLine(ReadFile(fs,buffer,0,buffer.Length));
}

private int ReadFile(Stream fs, byte[] buffer,int offset,int count)
{
  IAsyncResult result =  fs.BeginRead(buffer, 0, count, null, null);
  int numBytes = fs.EndRead(result);
  return numBytes;
}

The Task.Factory provides us an easy way to convert APM patterns to TAP. Let’s rewrite the above code in TAP now.

 

private Task<int> ReadAsync(Stream stream, byte[] buffer, int offset, int count) => Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, offset, count, null);

Event based Asynchronous Pattern

The second approach that Microsoft adopted was known as EAP. Let’s first examine a sample code for EAP.

Process p = new Process();
p.Exited += (e,args)=>
{
  Console.WriteLine("Executing Exited Event");
  Console.WriteLine($"Ended : {p.ExitTime}");
};
p.StartInfo.FileName = @"cmd";
p.EnableRaisingEvents = true;
p.Start();
Console.WriteLine($"Started : {DateTime.Now}");
Console.WriteLine("Invoke Process completed");

The conversion from EAP to TAP is facilitated using the TaskCompletionSource class.

Console.WriteLine($"Ended : {InvokeProcess().Result}");

Task<string> InvokeProcess()
{
       var tcs = new TaskCompletionSource<string>();
       Process p = new Process();
       p.Exited += (e,args)=>{
       Console.WriteLine("Executing Exited Event");
       tcs.SetResult("Result Data");
       };
       p.StartInfo.FileName = @"cmd";
       p.EnableRaisingEvents = true;
       p.Start();
       Console.WriteLine("Invoke Process completed");
       return tcs.Task;
}