Filter List and Display Type members with specified attribute

One of the recent questions that was intriguing (for me) in Stackoverflow was the need to Process a List and while displaying the result, display only the properties that are decorated with a specific attribute.

Let me explain with an example. Consider the following Entity.

public class Employee
{
public int ID { get; set; }

public string Place { get; set; }

[IncludeinReport]
public string BusinessVertical { get; set; }

[IncludeinReport]
public string Region { get; set; }

public string Country { get; set; }

[IncludeinReport]
public string BusinessUnit { get; set; }
}

For a List<Employee>, the expected result would display only “BusinessVertical”, “Region”, and “BusinessUnit” in the result. Let’s begin by creating a mock sample data to test it.

var list = new List<Employee>
{
new Employee{ID = 1, Region = "Europe", BusinessUnit="Software", BusinessVertical = "Sample1"},
new Employee{ID = 1, Region = "Asia", BusinessUnit="Software", BusinessVertical = "Sample1"},
new Employee{ID = 1, Region = "Asia", BusinessUnit="Hardware", BusinessVertical = "Sample1"},
new Employee{ID = 1, Region = "Europe", BusinessUnit="Software", BusinessVertical = "Sample1"},
new Employee{ID = 1, Region = "Asia", BusinessUnit="Telecom", BusinessVertical = "Sample1"},
new Employee{ID = 1, Region = "Europe", BusinessUnit="Software", BusinessVertical = "Sample1"},
};

Just to make things interesting, we would add restriction that the result needs to be Sorted By Region and Then by BusinessUnit. A LINQ solution would have been ideal, but unfortunately, I couldn’t go all the way with LINQ. But here is the solution I could suggest.
The first step, obviously was to get the List of Properties that has the required Attribute, which we can achieve using Reflection.

var properties = typeof(Employee).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(IncludeinReport))).Select(v=>v);
var intermediate = list.OrderBy(c => c.Region).ThenBy(x=>x.BusinessUnit).SelectMany((x,index)=> properties.Select(v=> new {GroupId = index, Dict = new KeyValuePair<string,object>(v.Name, v.GetValue(x))})) ;
var resultList = intermediate.GroupBy(x=>x.GroupId).Select(x=>x.ToList().Select(c=>c.Dict).CreateObject());

Where CreateObject is defined as

public static class Extensions
{
public static ExpandoObject CreateObject(this IEnumerable<KeyValuePair<string,object>> source)
{
dynamic returnValue = new ExpandoObject();
var dict = returnValue as IDictionary<string, object>;
foreach (var kvp in source)
{
dict.Add(kvp.Key, kvp.Value);
}
return returnValue;
}
}

Since even anonymous types needs to have Property Names defined in compile time, the only solution to create a Dynamic Type (including property names) was using ExpandoObject.
This would give you the desired output as enclosed in the screenshot.

Capture

Again, this is the solution I could arrive at, there would be better ones. I would certainly be interested to know a better solution. If anyone would like to follow the OP in question, please follow it StackoverFlow

Assignment using Ternary Operator

Couple of days back, I happened to come across a question in StackOverflow. Question seemed pretty straightforward, but at the same time, interesting. How would one use ternary operator for assignment. For example, how would write following code using ternary operator.

var a = 1;
var b = 2;
var c = 3;
var flag = false;
if(flag)
a = c;
else
b = c;

Obviously, following wouldn’t work.

// CS0131 The left-hand side of an assignment must be a variable, property or indexer
(flag?a:b) = c;

One way to use ternary operator would using Action.

(flag ? new Action(() => a = c): () => b = c)();

But that doesn’t quite give you the clean syntax of Ternary Operator. That brings us to the second way using features exposed by C# 7.2. Let us rewrite the code.

(flag ? ref a : ref b) = c;

Enjoy coding…

C# 8.0 : Default Implementation of Interface Members

The way C# language is evolving is definitely exciting and one feature that truly makes the wait for C# 8.0 all the more exciting is default implementation of interfaces.

Since the onset, interfaces were behaviors characterized by member signatures, strictly disallowing any implementation. All that is going to change when C# 8.0 rolls out, as it supposedly, plans to support default implementation of interfaces. What it means is further trimming down the walls between interface and class (but remember, walls would still exist : Interface and Classes will still have significant difference, we will talk about it a bit later.)

Let’s look at an example, courtesy MSDN Blogs.

interface ILogger
{
void Log(LogLevel level, string message);
void Log(Exception ex) => Log(LogLevel.Error, ex.ToString()); // New overload
}

class ConsoleLogger : ILogger
{
public void Log(LogLevel level, string message) { ... }
// Log(Exception) gets default implementation
}

Doesn’t that look exciting ? Gone are days when as an Author of an interface, you were almost handicapped extending the interface fearing it might break any of implementing code. You could now provide the default implementation of your interface member, and still be assured that all implementing code works as fine as it was before.

If this doesn’t excite you, think from another perspective. What this implies is possibility of multiple inheritance (almost) in a language that was never really supported it. You could now provide two interfaces with default implementation, and have a class inherit from both.

interface IParentA
{
string MethodA() => nameof(MethodA);
}

interface IParentB
{
string MethodB() => nameof(MethodB);
}

class Child : IParentA,IParentB
{
void MethodChild()
{
Console.WriteLine($"{nameof(MethodA)} = {MethodA()}");
Console.WriteLine($"{nameof(MethodB)} = {MethodB()}");
}
}

This effectively brings in Multiple Inheritance in place. What would be interesting to see is how Microsoft circumvented the Diamond Problem. Let’s delve a bit into Diamond Problem first, before trying to understand Microsoft’s workaround from what ever we know as of now.

Diamond Problem

Let’s consider the following inheritance structure assuming C# were to support Multiple Inheritance.

class A
{
public virtual string DemoMethod() => $"{nameof(A)}.{nameof(A.DemoMethod)}()";
}

class B : A
{
public override string DemoMethod() => $"{nameof(B)}.{nameof(B.DemoMethod)}()";
}

class C : A
{
public override string DemoMethod() => $"{nameof(C)}.{nameof(C.DemoMethod)}()";
}

// Let's assume this works for sake of demonstration
class D:B,C
{
public void Print()=> Console.WriteLine(DemoMethod());
}

In the above code, class D inherits from both Class B and Class C, both of which, in-turns inherits from Class A and overrides virtual member DemoMethod. Assuming this code compiles, what would be the output of Print() Method in Class D. Will it invoke method from Class B or Class C ? This ambiguity is better known as Diamond Problem.

Microsoft intents to work around the Diamond Problem here by taking the most specific override at the time. As Microsoft pens it down

“Diamonds with Classes

A class implementation of an interface member should always win over a default implementation in an interface, even if it is inherited from a base class. Default implementations are always a fallback only for when the class does not have any implementation of that member at all.”

Let’s rewrite the above code using default implementation of interfaces.

interface A
{
string DemoMethod() => $"{nameof(A)}.{nameof(A.DemoMethod)}()";
}

interface B: A
{
override string DemoMethod() => $"{nameof(B)}.{nameof(B.DemoMethod)}()";
}

interface C: A
{
override string DemoMethod() => $"{nameof(C)}.{nameof(C.DemoMethod)}()";
}

// This would be Error as no most specific override for A.DemoMethod()
class D:B,C
{
public void Print()=> Console.WriteLine(DemoMethod());
}

// This would be Error as no most specific override for A.DemoMethod()
class E:B,C,A
{
string DemoMethod()=> B.base.DemoMethod();
public void Print()=> Console.WriteLine(DemoMethod());
}

So will now abstract class == interface ?

No, not really. Even though the differences are diminishing, there still lies a lot of difference between the two. To name a few
– Unlike Abstract Class ,you still can’t write a default constructor for interface.
– Covariance and Contravariance

Essentially, abstract class and interface would continue to coexist in its own space. What Microsoft has done with Default Implementation of Interface is making use of Traits (more on traits later.)

 

Early Exceptions for Iterator and async Methods

One of the first things you would need to be vary of while working with Iterator methods and async methods is exception handling. Both Iterator methods and async methods delay the execution of your code, right until you need the result, but it also results in delayed exceptions.

Late Exception With Iterator Methods

Let’s consider a typical example. The following method generates positive integers from 1 to ‘n’. Of course, you could do this with Enumerable.Range but, that’s not the whole point.

void Main()
{
var maxValue = 0;
var generatedCollection = GenerateSequence(maxValue);
Console.WriteLine("No Exception raised yet");
foreach(var item in generatedCollection)
Console.WriteLine(item);
}

IEnumerable<int> GenerateSequence(int maxValue)
{
if(lastNumber <= 0)
throw new Exception($"Parameter {nameof(maxValue)} should be positive, non-zero");

for(int i=0;i<maxValue;i++)
yield return i;
}

The above method has a precondition which validates if the maxValue parameter is a positive, non-zero number. However if one was to execute the code, one can notice that exception isn’t raised until the result is consumed. This is expected. But, there could be scenarios where one might require you to have methods raise early exceptions.

Early Exception With Iterator Methods

Let’s rewrite the method with a little bit of tweak1.

void Main()
{
var maxValue = 0;
var generatedCollection = GenerateSequence(maxValue);
Console.WriteLine("No Exception raised yet");
foreach(var item in generatedCollection)
Console.WriteLine(item);
}

IEnumerable<int> GenerateSequence(int lastNumber)
{
if(lastNumber <= 0)
throw new Exception($"Parameter {nameof(lastNumber)} should be positive, non-zero");

return Generate();
IEnumerable<int> Generate()
{
for(int i=0;i<lastNumber;i++)
yield return i;
}
}

Try executing the code, and you can notice that now it supports early exception. This very approach could be used for async method. Let’s do the problematic code first.

Late Exception with async Methods

async Task<int> Increment(int numberToPrint)
{
if(numberToPrint <= 0)
throw new Exception($"Parameter {nameof(numberToPrint)} should be positive, non-zero");

return await Task.FromResult(++numberToPrint);
}

// Client code
var value = 0;
var task = Increment(value);
Console.WriteLine("No Exception raised yet");
await task;

The problem with late exceptions is visible in the above code as well. The exception is not raised where the method is called (in code), but rather it is raised when the Task is awaited.

Early Exception with async Methods

Task<int> Increment(int numberToPrint)
{
if(numberToPrint <= 0)
throw new Exception($"Parameter {nameof(numberToPrint)} should be positive, non-zero");

return Increment();
async Task<int> Increment()
{
return await Task.FromResult(++numberToPrint);
}
}

// Client Code
var value = 0;
var task = Increment(value);
Console.WriteLine("No Exception raised yet");
await task;

Reference


  1. Reference : More Effective C# : version 7.0 

Allocation free ‘async’ Methods

Task Asynchronous Programming (TAP) model will go down as one of the landmark of C# language revolution. The typical method signature with return type Task/Task<T> has since then made significant appearances in our programming life.

But despite all its glorious functionalities, it needs to be noted that it comes at a certain cost – performance bottleneck, especially when you are working in tight loops in a memory constrained environment. Memory allocations of Task/Task<T> (note both are references types) impacts the performances adversely in critical paths. What developers longed for in such scenarios is a comparatively light-weight value type, which could be returned instead of the references types in the async methods. This was a limitation till C# 7.x happened.

Starting from C# 7, an async method could return any type that has an accessible ‘GetAwaiter’ method, which returns an object that implements INotifyCompletion and ICriticalNotifyCompletion Interfaces. The ValueTask<T> is a "goto" under such circumstances. Being a value type, it doesn’t require additional memory allocations. This is extremely useful when you already have the ‘cached result’ and the operation can be completed synchronously. But like Task, it comes at a cost, which we will discuss later in the article.

To begin with, let’s write some sample code to demonstrate the need of ValueTask<T> or rather, need for replacing Task<T>. Consider the following code.

public interface IWeatherService
{
  Task<double> GetWeather();
}

public class MockWeatherService : IWeatherService 
{
  public async Task<double> GetWeather() => await Task.FromResult(30);
}

The above code demonstrate a Mock Weather Service. In real world scenario, this might be accessing a Web API to fetch current weather details. For the sake of example, only the temperature is fetched, which is hard coded. Consider GetWeather to be invoked quite frequently (say in a loop) by the Client. There is a chance this might turn disastrous if this was executed in a memory constraint environment.

Ideally, you wouldn’t want to fetch from the Web API always. You would prefer to cache the result, and only fetch from the Web API only after specific interval (from the time the last value was cached). Despite doing the operation (fetch from cache) synchronously, you are allocating memory for the reference type Task<T>. One would have wished to avoid this scenario and yet use the async syntax.

This is possible by making use of the ValueTask<T> DataType. Let’s change our syntax a bit.

public interface ICachedWeatherService
{
  ValueTask<double> GetWeather();
}
public class MockCachedWeatherService : ICachedWeatherService
{
  private DateTime _lastAccessedTime = DateTime.MinValue;
  private double _lastAccessedValue = 30;
  public async ValueTask<double> GetWeather()
  {
    if(DateTime.Now - _lastAccessedTime < TimeSpan.FromSeconds(10))
    {
      return _lastAccessedValue;
    }
    _lastAccessedTime = DateTime.Now;
    return await Task.FromResult(30);
   }
}

In the above code, we have changed the signature of the method (return type) to ValueTask<T>. Since it implements all the necessary requirements that is needed for async method (as discussed earlier), we could still use the same signature in client to access the method, just like in Task based syntax.

Using Task Return Type

var _weatherService = new MockWeatherService();
           
for(int i = 0; i < 10; i++)
{
  await Task.Delay(5000);
  var currentWeather = await _weatherService.GetWeather();
  Console.WriteLine($"Weather @ {DateTime.Now.ToString("hh:mm:ss")}={currentWeather}");
}

Using ValueTask Return Type

var _cachedWeatherService = new MockCachedWeatherService();
for (int i = 0; i < 10; i++)
{
  await Task.Delay(5000);
  var currentWeather = await _cachedWeatherService.GetWeather();
  Console.WriteLine($"Weather @ {DateTime.Now.ToString("hh:mm:ss")}={currentWeather}");
}

Check Complete Code Sample

Difference is, when the method needs to return from the cache, it returns ValueTask avoiding the pain of creating the Task Reference Type. However, when it has to go through the Web API, it can still return Task<T>.

Even though ValueTask seem highly useful, you need to maintain caution and should rather use it only if there is considerable performance issues that were measured. The reason for this is that, despite the ValueTask helps you avoid unnecessary allocation, it comes with its own cost. The ValueTask is a two field structure compared to Task<T>, which despite being reference type has single field. More fields would result in more data to copy. It fact Microsoft warns us in the API documentation itself.

Quoting from Documentation

There are tradeoffs to using a ValueTask<TResult> instead of a Task<TResult>. For example, while a ValueTask<TResult> can help avoid an allocation in the case where the successful result is available synchronously, it also contains two fields whereas a Task<TResult> as a reference type is a single field. This means that a method call ends up returning two fields worth of data instead of one, which is more data to copy. It also means that if a method that returns one of these is awaited within an async method, the state machine for that async method will be larger due to needing to store the struct that’s two fields instead of a single reference.

Hence, stick onto Task/Task<T> for almost all your use, until performance analysis pushes you to use ValueTask<T>. Complete code samples described in the example is available in my Github

Updated Span API : NonPortableCast and AsReadOnlySpan to MemoryMarshal.Cast and AsSpan

One of the interesting changes (not sure why Microsoft changed this) was moving/changing the Span<T> API’s a bit. For example, the Span<T>.NonPortableCast Method was moved as an extension method under MemoryMarshal.

Previous API

Span<byte> byteSpan = BitConverter.GetBytes(originalPrimitiveType);
Span<int> intSpan = byteSpan.NonPortableCast<byte, int>();

Current API

Span<byte> byteSpan = BitConverter.GetBytes(originalPrimitiveType);
Span<int> intSpan = MemoryMarshal.Cast<byte, int>(byteSpan);

Similarly, the string.AsReadonlySpan method has been renamed. The new API is as follows.

Previous API

ReadOnlySpan<char> keyString = "SomeText".AsReadOnlySpan();

Current API

ReadOnlySpan<char> keyString = "SomeText".AsSpan();

The MemoryMarshal extensions can be found under the System.Runtime.InteropServices namespace. Code discussed in my earlier post about Benchmarking Span has been updated in my Github.

The new String Interpolation and Ternary Operator

A quick tip for the new C# string interpolation. The new string interpolation has made things more simpler and readable. One might be tempted to include ternary operators within string interpolation.

However if you attempt something like following, the compiler would throw an error

Console.WriteLine($"{1==1?"Msg1":"Msg2"}");

The fix is as simple as it can get. Just include a brace within your ternary statement.

Console.WriteLine($"{(1==1?"Msg1":"Msg2")}");

That’s it. Brace up for a week with lot of fun and coding.