Back to Basics #002

Continuing with our series of subtle changes that make differences, let’s look into Conditional Attributes over Directives.

static void Main(string[] args)

Queue queue = new Queue();

Console.WriteLine("All Done");

// Approach One
private static void Method01()
Console.WriteLine("Hello Method01");
private static void Method02()
Console.WriteLine("Hello Method02");

private static void Method03(string Value)

What would be the output of above code under
a) Debug Mode
b) Release Mode

The Debug Mode should be easy and as expected

Hello Method01
Hello Method02
All Done

What about release mode ?
All Done

You might have a tendency to say “2”, considering you might expect the dequeue statement to be executed. However, that is not the case. The dequeue is not called either because the result is not used as the method is not called.This leads to unexpected errors .
This is one the reasons why it is recommended not to decorate a method that accepts parameter with conditional Attributes.


Back to Basics #001

Welcome to first post on ‘Back to basics’. Yeah, as you guessed right, this series attempt to check minor differences in our understanding of basic concepts.

Predict the output of following.

public class FirstType

public class SecondType
private FirstType _mType;

public static implicit operator FirstType(SecondType t)
return t._mType;

static void Main(string[] args)
object objectInstance = new SecondType();

FirstType attempt1 = objectInstance as FirstType;
if (attempt1 != null)
Console.WriteLine("'As' Conversion Succeeded");
Console.WriteLine("'As' Conversion Failed");

FirstType attempt2 = (FirstType)objectInstance;
Console.WriteLine("Cast Succeeded");
catch (Exception)
Console.WriteLine("Cast Failed");


Ideally, One would expect the first attempt to fail, but would feel the second would succeed considering we have implemented implicit conversion. But unfortunately, that’s not the case. The output would be

‘As’ Conversion Failed.
Cast Failed.

The reason for this is that, the compiler generates code based on the compile time type of the objectInstance, which in this case is ‘object’. It then checks if there is any conversion declared to convert object to FirstType, which doesn’t exist. The compiler doesn’t check the type of the objectInstance during runtime, which results in the above output.

The reason for this is that, the compiler generates code based on the compile time type of the objectInstance, which in this case is ‘object’. It then checks if there is any conversion declared to convert object to FirstType, which doesn’t exist. The compiler doesn’t check the type of the objectInstance during runtime, which results in the above output.


The behavior is even more tricky when we change the type of¬†objectInstance from ‘object’ to SecondType. We would expect it to work smoothly now, however, you end up with a compiler exception this time .

“Cannot convert type ‘Cast.SecondType’ to ‘Cast.FirstType’ via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion”

This is what makes ‘as’ operators great as it provides early detection of errors. The ‘as’ operator, notices that there is a implicit conversion declared between FirstType and SecondType. However, it also recognizes that two types aren’t related by inheritance. This is the reason ‘as’ statements throws a compile-time error at this stage.


Revamping Interview Strategies.

One of the things which bothers me with the current interview process relevant in most companies if the focus on measuring candidate’s capabilities on the basis of his knowledge of particular sub-technology. There might be wrong with this approach, but what if the Candidate is a strong programmer who unfortunately hadn’t got the opportunity to work on the particular technology/framework ?

Programming or analytical skills, according to me, is something which is heart and soul of a software programmer. He might or might not have worked in a particular technology, but that doesn’t mean he cann’t do good when given a chance. After all, none has worked in every technology under sun. What matters is his ability to solve a problem.

Recently I saw an article in Medium and was quite fascinated by the thought. What if ask something very familiar to candidate, but prompting him to think outside the box.

For example, counting the odd numbers in an array of integers or checking if a given day is weekday or weekend is something we would have done when we learn the first steps in programming. What if we ask the candidate to accomplish the same without any form of conditional operators ?

Now that would get his thought process reset. He would have think, which is more important than remembering something and answering. So, revisit your interview strategies and allow the candidate on put on his thinking cap on

Here is my 2 cents on accomplishing the above mentioned questions in C#

public int CountNonConditional(int[] Arr)
     var sum = 0;
     Array.ForEach(Arr, (x) => sum+= x % 2);
     return sum;
public bool IsWeekDayNonConditional(DayOfWeek Day)
     return Convert.ToBoolean(((int)Day % 6));

MongoDb 002 : CRUD – Part 1

We will continue with our exploration of MongoDb in this second part of tutorial, working our CRUD examples.

Let’s beging with the ‘C’. In order to create a document, you would need to use, as you can guess, the Insert command.


Notice that we are using a new collection named subject here. MongoDb would automatically create the collection if it doesn’t exist. As you would have rightly guessed by now, we would be relying on JSON for passing any parameters for commands.

Let’s now do the same using C#. The first step you need to do is to install the MongoDB.Driver official Nuget package. Once the nuget is installed for our project, let’s start pushing some code in to our collection.

Following Commands gives us access to

string ConnectionString = "mongodb://localhost:27017";
var Client = new MongoClient(ConnectionString);
var Database = Client.GetDatabase("testdb");

The next step is to create the Data Structure which would be serialized and pushed into the DB.

public class SubjectEntity
public ObjectId Id { get; set; }

public string Title { get; set; }

If you look closely, I have decorated each of the elements with BsonElement Attribute. This tells the compiler the literal it should use as key while creating the JSON document. Also if you notice, I have a property called Id of type ObjectId. This is a special type which would hold the unique ID which would be generated by MongoDb. This value is similiar to a GUID and unlike relational Db, we cannot use an autoincrement key, unless we do that bit of logic within our C# code. Honestly I wouldn’t recommend that.

Since I would like to use the ID generated by MongoDb, I have not decorated the Id field with BsonElement attribute, however I would still need in my Data Structure so that I could use it while retrieving data.

Okay, fine then. Let’s push some data to the Db now.

var subjectCollection = Database.GetCollection("subject");
subjectCollection .InsertOne(SubjectEntityInstance);

The above code inserts a object of type SubjectEntity to the Db. Once executed, hit our Console again and check if the Document is added to the SubjectCollection using the find command we learned in the first part of tutorial. Looks good right ?

Let’s try finding it with a find command from C# now.

var nameFilter = Builders.Filter
.Eq(x => x.Title,'maths');
var result = subjectCollection

As you can understand from the code, we are first creating an instance of the filter we would like to use. In this case, we are using an Equality Filter (Subject title should be “maths”). We finally pass the filter to our FindSync Method.

We would be exploring part two of CRUD, Update and Delete in the second part of the tutorial.

The complete list of beginners guide in this series can be found in here

MongoDb 001 : Basic Commands

Before we actually get into MongoDb, let’s begin by importing a Test Db. You can access the JSON file here. Once you have downloaded the file, use following command to import the document into mongodb.

mongoimport --db testdb --collection students --drop --students.json

Let’s break it down, the command tells you to import a file students.json into a database called testdb and collection called students. Let’s go ahead verify if our import is good.

show dbs
use students
show collections

We first checked if the db named students has been created by checking the list of dbs. ‘show dbs’ command displays list of all dbs in the server. We followed it up with ‘use students’ command, which is similiar to the ‘use ‘ command in MySql. Finally, we issued ‘show collection’ command to view the collections in the db. Remember collections are analogous to tables in relational database.

We will now go ahead check out data. In relational database, data is saved as a row in the table. When it comes to Nosql databases, each row is represented as a document.
To view contents of a collection, we issue a find command
In our case, it would be


This would show our 3 documents within the collection. Let’s explore the find command a bit. We could give a specific search filter as arguement, in case we need to find a particular document, similiar to the ‘where’ condition in relational database. Instead of the customary “=” syntax, MongoDb relies on JSON for passing the argument.

db.students.find({"name":"jia anu"})

In case you want to pass more than one arguement, things don’t change much. Yes, you guess right, you pass more data in json.

db.students.find({"name":"jia anu","age":1})

If we need to search use a comparison operator ‘greater than’ or ‘less than’, you would need to use the ‘$gte and $lte commands.
Let’s go ahead and issue a command, say, we need to find all students who age is ‘less than or equal to 1’

db.students.find({"name":"jia anu","age":{$lte:1}})

A comprehensive list of comparison operator can be found in here

The complete list of beginners guide in this series can be found in here

Circular Button Using Xamarin (Custom Renderer)

The shift to appcompat has affected Android developers, while developing cross platform xamarin application. The first difference you would notice is the buttons are no longer having rounded corner despite assigning the radius. That is a define roadblock when you consider you need a perfect circular button.

However things aren’t actually that bad as it sounds to be. You cannot discount the power custom renderering brings in. What we need to do is write a custom Renderer and ensure shape is set to Oval. Let’s get hands dirty and do some coding.

class CircularButtonRender : Xamarin.Forms.Platform.Android.ButtonRenderer
private GradientDrawable _NormalState, _PressedState;

protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)

if (Control != null)
var button = e.NewElement;

// Create a drawable for the button's normal state
_NormalState = new Android.Graphics.Drawables.GradientDrawable();
_NormalState.SetStroke((int)button.BorderRadius, button.BorderColor.ToAndroid());

_PressedState = new Android.Graphics.Drawables.GradientDrawable();
_PressedState.SetStroke((int)button.BorderRadius, button.BorderColor.ToAndroid());

// Add the drawables to a state list and assign the state list to the button
var sld = new StateListDrawable();
sld.AddState(new int[] { Android.Resource.Attribute.StatePressed }, _PressedState);
sld.AddState(new int[] { }, _NormalState);


 The entire source can be found in my Git project here [GitHub].