Serializing/Deserializing Dictionaries with Tuple as Key

Sometimes you run into things that might look trivial but it just do not work as expected. One such example is when you attempt to serialize/Deserialize a Dictionary with Tuples as the key. For example

var dictionary = new Dictionary<(string, string), int>
[("firstName1", "lastName1")] = 5,
[("firstName2", "lastName2")] = 5

var json = JsonConvert.SerializeObject(dictionary);
var result = JsonConvert.DeserializeObject<Dictionary<(string, string), string>>(json);

The above code would trow an JsonSerializationException when deserializing. But the good part is, the exception tells you exactly what needs to be done. You need to use an TypeConverter here.

Let’s define our required TypeConverter

public class TupleConverter<T1, T2> : TypeConverter
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
var elements = Convert.ToString(value).Trim('(').Trim(')').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return (elements.First(), elements.Last());

And now, you can alter the above code as

TypeDescriptor.AddAttributes(typeof((string, string)), new TypeConverterAttribute(typeof(TupleConverter<string, string>)));
var json = JsonConvert.SerializeObject(dictionary);
var result = JsonConvert.DeserializeObject<Dictionary<(string, string), string>>(json);

With the magic portion of TypeConverter in place, your code would now work fine. Happy Coding.

Type Argument Inference during Type Initialization

One of the least discussed topics about compiler and Generic Methods is its ability to infer the Type Arguments. For example, consider the following code.

public void Display<T>(T value)

A typical invocation of the code might look like following.

var value = 45;

However, in some scenarios as above, the compiler is smart enough to allow you to skip the type argument from the generic method. For example, you could call the method as the following.

var value = 45;

This is because the compiler realizes you have passed an integer value as argument and it infers the type argument T as Int32.

This is great feature to have and allows you to do away with a lot of ceremony. However, the type inference is limited to Methods and doesn’t quite help you in Type Initialization. For example,

public class MyClass<T>


For initializing the above class, you would have to explicitly mention the Type Argument.

var instance = new MyClass<int>();

However, having said that, there is a easy-to-use pattern to work around the issue. If you were to inspect the Tuple static class, you might find some interesting methods there.

For example,

public static Tuple<T1> Create<T1>(T1 item1)
return new Tuple<T1>(item1);
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
return new Tuple<T1, T2>(item1, item2);

In the first glance, you might be temped to question the intend of the methods. What would one create a static method to create instances, when you could call the constructor directly. However, when closely examined, this is a great example of how to make type inference possible during initialization.

For example, for initializing a Tuple<int,int> using the constructor, you would have to pass the type arguments.

var instance = new Tuple<int,int>(3,4);
var instance = new Tuple(3,4); // This doesn't compile

However, the presence of static methods allows you to create the instance without passing the type arguments.

var instance = Tuple.Create(3,4);

This is a easy-to-use pattern if you ever want to support Type inference during initialization. Looking back at our sample class, we could now create helper methods as following.

public static class MyClass
public static MyClass<T> Create<T>(T value)
return new MyClass<T>();

The initialization code could now skip the type arguments, just like with the Tuples.

var instance = MyClass.Create(4);

C# over the years has reduced ceremony and boiler plate code and type inference is one yet another way to achieve the same.

Revisting Anonymous Type

While classes and structs are extremely powerful, there are times when you want to escape the cermonies they require even for simplest of design. This is where anonymous types comes handy and has been so frequent used by the developers.

So what are Anonymous types really ? Let’s consider an example first.

var point = new {X = 20, Y = 30}

Anonymous Types are compiler generated immutable reference type.

Though framed in few words, that definition probably describes a lot more than that meets the eye. From the point of definition of our anonymous type above, it means you are directing the compiler to generate an internal sealed class, which has two read-only properties namely X and Y. For example, the compiler might generate something similiar to following class for the anonymous type we just declared.

internal sealed class Point
private int _x;
private int _y;

public int X => _x;
public int Y => _y;

public Point(int x,int y)
_x = x;
_y = y;

Do notice this might not be exactly what compiler generates. There could be certain things which you cannot do yourself, but the above example kind of provides the gist.

The Anonymous Type syntax allows you to do all that declaration with very little need to type them yourself. This eliminates the chances of human error, in addition to saving your time as well as polluting the application namespace. The scope of the defined anonymous type is restricted to the method it is defined.

But, Anonymous Types has their drawbacks as well. As a developer, you do not know the Type. Imagine, you need to pass the anonymous type to a method, how would you do it ? Tricky, isn’t it.

If you do not have to individually process different properties of the Anonymous types, you can achieve this using Generic methods. For example, you can use following method to compare two anonymous types.

bool IsEqual<T>(T source, T itemToCompare)
return source.Equals(itemToCompare);
// Client Code
var point1 = new {X = 20, Y = 45};
var point2 = new {X = 20, Y = 45};

var comparisonResult = IsEqual(point1,point2);

But what if you need to process the individual properties of Anonymous types within the method ? For example, you want to increment the X and Y of Point by 1 (let’s ignore reflection for the moment)

One way to achieve this would be use Generic methods with Func parameters. For example,

T Execute<T>(T source, Func<T,T> incrementFunction)
return incrementFunction(source);

You can invoke the method as the following.

var result = Execute(point,(p)=> new {X=p.X + 1, Y=p.Y+1});

Let’s now explore another possibility. Consider a method that returns an anonymous type.

object GetPoint()
return new {X = 20, Y = 45};

How would one process the individual properties in the caller method ? Surely, following would fail to compile

// Following would fail to compile
var point = GetPoint();
var x= point.X;

Deconstruction won’t be a help either as anonymous types doesnt support it.

// Following would fail to compile
var (x,y) = GetPoint();

What we would require it to cast the returned object to anonymous type, that resembles the original. Let us write a quick extension method it.

public static class Extensions
public static T Cast<T>(this object source,T sampleType)
return (T)source;

Now you can use the return type by casting it to desired Anonymous Type and use it in your rest of code.

var point = GetPoint();
var result = point.Cast(new{X=default(int),Y=default(int)});

That’s it for now, Happy Coding.

Json Custom Filtering : Remove Properties of a Type T

One of the recent questions that came up in SO which fascinated me was how do one filter a Json string by removing properties from Json, which is of a particular Type. For example, consider the following Json.

'debug': 'on',
'window': {
'title': 'Sample Widget',
'name': 'main_window',
'width': 500,
'height': 500
'image': {
'src': 'Images/Sun.png',
'name': 'sun1',
'hOffset': 250,
'vOffset': 250,
'alignment': 'center'
'text': {
'data': 'Click Here',
'size': 36,
'style': 'bold',
'name': 'text1',
'hOffset': 250,
'vOffset': 100,
'alignment': 'center',


What if you want to remove all Json Properties that has a value of Integer Type. What would be a good way to achieve it if the format of Json is unknown ?

I ended up writing an extension method.

public static class Extensions
public static JToken RemoveFieldTypes(this JToken token,params JTokenType []fieldTypes)
JContainer container = token as JContainer;
if (container == null) return token;

var tokensToRemove = new List<JToken>();
foreach (JToken el in container.Children())
JProperty p = el as JProperty;
if(p!=null && fieldTypes.Contains(p.Value.Type))
foreach (JToken el in tokensToRemove)
return token;

Client Code Sample

JToken nodeList = JToken.Parse(strJson);

Sample Ouput

"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window"
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"alignment": "center"
"text": {
"data": "Click Here",
"style": "bold",
"name": "text1",
"alignment": "center"

External Tracker for OxyPlot

Back with another hack with Oxyplot. This time around what I would like to achieve is to actively update a TextBlock with Tracker values as the user moves around the graph. This could be useful when you want to have an external mini-dashboard which would the tracker values as User works on the graph after turning off your original tracker.

For sake of demo, we would leave the OxyPlot Tracker on, so that the results could be verified with our external tracker.

Let’s set up the View first.


<oxy:PlotView Model="{Binding DemoPlotModel}"/>
<TextBlock Grid.Row="1" Text="{Binding CurrentTrackerValue}"/>

We will now define our PlotModel and define our Series.

DemoPlotModel = new PlotModel();
var xAxis = new LinearAxis
Position = AxisPosition.Left,
Maximum = 100,
Minimum = 0

var yAxis = new LinearAxis
Position = AxisPosition.Bottom,
Maximum = 100,
Minimum = 0


var listOfDataPoints = new DataPoint[]
new DataPoint(10,5),
new DataPoint(20,15),
new DataPoint(30,20),
new DataPoint(40,28),
new DataPoint(50,39),
new DataPoint(60,55),
new DataPoint(70,60),
new DataPoint(80,73),
new DataPoint(90,90),
var series = new LineSeries
ItemsSource = listOfDataPoints,
Color = OxyColors.Green,
MarkerType = MarkerType.Square,
MarkerSize = 5,
MarkerFill = OxyColors.DarkGreen


And now it is time our adding our little hack to update the Label’s bound property – CurrentTrackerValue.

DemoPlotModel.TrackerChanged += (sender, eventArgs) =>
CurrentTrackerValue = eventArgs.HitResult != null ? eventArgs.HitResult.Text : CurrentTrackerValue;

public string CurrentTrackerValue { get; set; }

That’s it, now you have your external live tracker.

Json : Fetch all keys using Linq

Given a Json, how do we get all the keys in it ? Just the keys. For example, Consider the Json below.

Person:['Jia Anu', 'Anu Viswan','Sreena Anu'],
Name: 'Jia Anu',
Name: 'Anu Viswan',
Name: 'Sreena Anu',
Address : 'Address here',
State : 'Kerala',
Country : 'India'

Given the above Json, you would like to get all the keys. You might be later interested to show this as a Menu or Dropdown, that’s down to the requirements. But, how do we get the keys in first place ? May be a Linq One liner would be great ?


Of course, you do have the option to loop through the JTokens, but the easiest way out would be using Linq.

var data = JObject.Parse(jsonString);
var result = data.Descendants()

The Regex involed is to ensure the arrays indices are removed and keys in arrays aren’t duplicated. The output of above Linq would give you collection of all keys in the Json as expected.

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];

Output of above code would be


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.



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.