Enumerable.Empty vs new T[0]

The need for creating an Empty array/collection rises quite often in most applications. This, normally presents us with two options.

  • Using the Constructor, new T[0];
  • Using the extension method, Enumerable.Empty

Let’s dive a bit deeper into both and examine how both these options work and differ.

Using new T[0]

Creating an empty array with Array Construction syntax is as follows.

var collection = new T[0];

What exactly happens behind the scenes. Let’s examine the following code.

var collection1 = new string[0];
var collection2 = new string[0];
object.ReferenceEquals(collection1,collection2).Dump();

Output of above code would be

False

The reason for this is self-explanatory. Each call to ‘new T[0]’ create a new Empty array in the memory. Both these, are as noticable, separate instances. What happens with Enumerable.Empty then ? Let’s examine that next.

Using Enumerable.Empty

Consider the complimentary code using Enumerable.Empty approach.

var collection1 = Enumerable.Empty<string>();
var collection2 = Enumerable.Empty<string>();
var result = object.ReferenceEquals(collection1,collection2);

What would be output of code in above scenario ? As you might have guessed, the output would be true.

Output

True

Enumerable.Empty caches the result for calls and reuses it later on. As MSDN states it

The Empty<TResult>() method caches an empty sequence of type TResult. When the object it returns is enumerated, it yields no elements.

This can be further verified by checking out the source code of Enumerable.Empty.

public static IEnumerable<TResult> Empty<TResult>()
{
return EmptyEnumerable<TResult>.Instance;
}
internal class EmptyEnumerable<TElement>
{
public static readonly TElement[] Instance = new TElement[0];
}

This difference might be of less significance in applications where memory constraints aren’t too critical, but when your applications requires to ensure memory allocations are used well, then Enumerable.Empty is your friend. Personally, I felt Enumerable.Empty should be the “go to” under all circumstances for not only for the reasons described above, but it also is more verbose in declaration and increases code readability manifold.

Linq Join on Like%

One of the recent requirements I came across recently needed what looks like a Join on a ‘Like%’. Let me cite an example to demonstrate the requirement.
Consider the Collections below.

Master Collection

ID Name
1 Jia Anu
2 Sreena Anu
3 Anu Viswan

Child Collection

ID First Name Age
1 Jia 2
3 Sreena 34
5 Anu 35

I would like to Join on Master.Name and Child.FirstName where Child.FirstName StartsWith Master.Name. The expected output is as follows.

Name FirstName Age
Jia Anu Jia 2
Sreena Anu Sreena 34
Anu Viswan Anu 35

Let’s begin by defining the input collections.

var master = new List<Master>
{
new Master{Id=1,Name="Jia Anu"},
new Master{Id=2,Name="Sreena Anu"},
new Master{Id=3,Name="Anu Viswan"}
};

var child = new List<Child>
{
new Child{Id=1,FirstName="Jia",Age=2},
new Child{Id=2,FirstName="Sreena",Age=34},
new Child{Id=3,FirstName="Anu",Age=35}
};

Where Master and Child is defined as

public class Master
{
public int Id {get;set;}
public string Name {get;set;}
}

public class Child
{
public int Id{get;set;}
public string FirstName {get;set;}
public int Age {get;set;}
}

The default Join uses Equality as Comparer, and is not useful for us in this scenario. The solution lies in a little known overload of Group, which allows to provide our own customer Comparer. Let’s define our Custom Comparer.

class StartsWithEqualityComparer: IEqualityComparer<string>
{
public bool Equals(string right, string left)
{
return left.StartsWith(right);
}
public int GetHashCode(string obj) { return 0; }
}

Now, we can use our StartsWithEqualityComparer.

var result = master.Join(child,
m=>m.Name,
c=>c.FirstName,
(m,c)=> new
{
Name = m.Name,FirstName = c.FirstName,Age = c.Age
}
},new StartsWithEqualityComparer());

That’s it, we have our GroupBy with Like%.

Caliburn.Micro #008: Gesture Recognition using Short-Hand Syntax

In this part of Caliburn.Micro tutorials we would explore how to configure and use Gesture Recognition with Caliburn.Micro, particularly exploiting the Short-Hand syntax for Actions. Caliburn.Micro doesn’t support this out of the box, so obviously we need to work around the Actions to provide support for Gestures. Let’s first formulate the syntax of how we would like to add a Gesture and its binding in XAML and then find our way to it.

We would ideally like to use a syntax, that is close to Action Syntax for triggering events.

[Event Click]=[Action Method1] // Normal Events
[Key F12]=[Action Method1] // Ideal Gesture Syntax.

The first step required would be to write a Trigger that would catch the KeyPress event. The trigger should provide ability to pass the expected “Key” and invoke the binded action when the expected “Key” is pressed. Let’s go ahead and write the required Custom Trigger.

public class KeyTrigger : TriggerBase<UIElement>
{
public static readonly DependencyProperty KeyProperty =
DependencyProperty.Register("Key", typeof(Key), typeof(KeyTrigger), null);

public Key Key
{
get => (Key)GetValue(KeyProperty);
set => SetValue(KeyProperty, value);
}

protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.KeyDown += OnAssociatedObjectKeyDown;
}

protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.KeyDown -= OnAssociatedObjectKeyDown;
}

private void OnAssociatedObjectKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key)
{
InvokeActions(e);
}
}
}

The KeyTrigger is quite self-explainatory. It declares Dependency Property called “Key” of System.Windows.Input.Key, and verifies if the Key Pressed is actually the one registered in KeyDown Event of AssociatedObject. If the Key matches the registered Key, it invokes the associated Action.

The Step is to Write our Custom Action Format, that would be recognized by the Caliburn.Micro Parser, and calls from Trigger(and there by Action). In order to achieve this, we re-define Parser.CreateTrigger method, which is responsible to generate the trigger. We do this in our Bootstrapper, overriding Configure Method.

// In Bootstrapper

protected override void Configure()
{
var defaultCreateTrigger = Parser.CreateTrigger;

Parser.CreateTrigger = (target, triggerText) =>
{
if (string.IsNullOrEmpty(triggerText)) return defaultCreateTrigger(target, null);

var regex = new Regex($@"^\[(?<{X_ACTION}>[a-zA-Z]+)\s(?<{X_SHORTCUT}>[a-zA-Z0-9]+)\]$");
var matches = regex.Match(triggerText.Trim());

switch (matches.Groups[X_ACTION].Value.ToUpper())
{
case X_KEY:
return new KeyTrigger
{
Key = (Key)Enum.Parse(typeof(Key), matches.Groups[X_SHORTCUT].Value, true),
};
default:
return defaultCreateTrigger(target, triggerText); ;
}
};
}

As observed, we check if the triggerText contains our special keywords, and if so, create our Custom trigger, namely KeyTrigger. In all other case, it returns the default trigger.

That’s all we require to configure our Gesture Recognition. We can now move on to our View and define the Gesture using our custom Action syntax.

cal:Message.Attach="[Key Enter] = [Action Increment]"

You can access the complete code sample, demonstrated in this post in my Github.

Btw, Merry Christmas !!!

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