System.Generic.Collections.List–internal structure

Ever wondered how List<T> is implemented? Do you know what is the default capacity for List<T> when you call it’s constructor? If not, read on – after this post you should be able to answer such kind of questions. This is not the post for ordinary developers 🙂

Capacity vs. Count

These two can be sometimes troublesome and one can mistake one from another. But most of us get it correct – the count is the actual number of elements on the List<T>. Where the capacity is the total number of elements the internal data structure can hold without resizing.

As you can expect – behind the curtain there is a data structure like this:

private T[] _items;

In such table the List stores it’s elements – all the methods base on this.

So in other words:

  • count – the number of elements actually in the table,
  • capacity – the length of the table.

Default capacity

Ok, so there is a table behind the List<T> object – but actually what is the default capacity when you call default ctor of list? We do not provide any elements at all, we also do not tell how many elements we do expect.

Here, I have to mention that this is not DEFINED and can be changed in the future. I have checked it on the .NET Framework v4.0 (and before) – it is still the same value.

private const int _defaultCapacity = 4;

This is not a big number you say. So the other question is – what happen when you would like to add 5 elements.

Going further, let’s check the Add(T item) method where the first two lines are like that:

if (this._size == this._items.Length)
        this.EnsureCapacity(this._size + 1);

So going further, analyze of EnsureCapacity(int) method leaves us such operation in case if there is no more space to add new element to the table:

int num = this._items.Length == 0 ? _defaultCapacity  : this._items.Length * 2;

As you can see – this line is responsible not only for extending the capacity (binary growth!) but also for setting the default storage capacity.

This gives us quite important info – when you call List() ctor actually the internal table used for storing data object is EMPTY! That’s quite a surprise, you have to admit..

Summary

So in other words List<T> is a simple implementation of the table data objects where extending the data structure is always a nightmare. Thankfully folks at Microsoft created BCL with a great implementation of the List<T> generic collection which gives us all the speed known from table data structure and the nice execution and usage options at the same time.

Object initializers

When you would like to create an object – you simply call the ctor of specific class. But sometimes building plenty of constructors just for adding another parameter is a waste of time (yours and developer who will use your code). This is why in C# 3.0 the object initializers were introduced.

But let’s start with simple example where we have a class such as below.

class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }

    public Person(string name)
    {
        Name = name;
    }
}

With that to initialize it we were used to do it like that:

var p1 = new Person("Tom");
p1.Surname = "Kuj";

But starting from C# 3.0 you could also do it like that:

var p2 = new Person("Tom2") { Surname = "Kuj2" };

Ok – looking at that there seems to be only the language (compiler) feature to write the initialization differently. BUT there is also a different execution approach which can have significant influence on your multithreaded application.

IL code examination

Let’s check the IL code generated by the compiler.

.locals init (
  [0] class TestObjectInitialazerConsoleApplication.Person p1,
  [1] class TestObjectInitialazerConsoleApplication.Person p2,
  [2] class TestObjectInitialazerConsoleApplication.Person '<>g__initLocal0'
)
IL_0000: nop IL_0001: ldstr "Tom" IL_0006: newobj instance void TestObjInitApp.Person::.ctor(string) IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldstr "Kuj" IL_0012: callvirt instance void TestObjInitApp.Person::set_Surname(string) IL_0017: nop IL_0018: ldstr "Tom2" IL_001d: newobj instance void TestObjInitApp.Person::.ctor(string) IL_0022: stloc.2 IL_0023: ldloc.2 IL_0024: ldstr "Kuj2" IL_0029: callvirt instance void TestObjInitApp.Person::set_Surname(string) IL_002e: nop IL_002f: ldloc.2 IL_0030: stloc.1 IL_0031: ret

First look at this code does not provide much information but with a closer look – there will be interesting flow.

First of all let’s look at the locals initialization – we have 3, not 2 objects in there!!! We have two named p1 and p2 and there is something called ‘<>g__initLocal0’ – this is just temporary variable which will be used for the object creation (you probably understand it already :-)).

For our investigation the most interesting lines starts at IL_0022  where we allocate the object created in IL_001d object into [2] local and we work on that one. The lines IL_002f and IL_0030 – the temporary variable is assigned to the p2 object.

Summary

So object initialization gives us another temporary variable and when it’s finished – this is assigned to our object. But what do we get because of that? Why did designers decide not to work on the original object?

The answer is – the multithreading. You can imagine that it’s possible that some thread will read p1 when its ctor was called but not all properties were set. That is why using the object initialization is a better idea – will make our code more “atomic” I can write. So the object will never be in the state which we did not expect – it’s either not assigned or assigned as expected.

Additional summary (EDIT)

This seems to be the path taken by the designers with more than just object initializers. If you inspect the IL code of collection initializers – this works exactly the same way (with the temporary variable).

C# application connected to ElasticSearch server

Some time ago I mentioned that I will start playing around with ElasticSearch. This is the search engine which is based on Lucene but can be easily distributed to the cloud. There is a server side (git repository) which is responsible for building the indexes and for distributing the requests.

Start the server

This is the simplest step – you need to download source from http://www.elasticsearch.org/ and extract it. Then run bin\elasticsearch.bat and voila! For the first project there is no more interesting things so far (more interesting things will come when the indexes will just be too big to maintain it on one ES server).

Test the connection

The documentation of the ElasticSearch suggest that we should use curl. Of course that is cool if we would like to check whether the connection is established – but more fun we will have when playing with C# code. 🙂

Simple application testing the server

OK, so we have a running server. For todays post the only thing to be done is the test of the connection. ES offers us the RESTful interface which we can easily consume in our application

string uri = "http://localhost:9200/";

var req = System.Net.WebRequest.Create(uri);
System.Net.WebResponse resp = req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());

Console.WriteLine(sr.ReadToEnd().Trim());

The result we get is shown on the picture below.

elastic_ping

This is the information from the server that it exists and the default response for the server.

As you can see parsing it is not a very beautiful way of connection from the C# application – one need to consume the response (JSON data) and act according to the response. Building the query is also quite tricky.

I have found one of the .NET clients – PlainElastic.Net which seems to be a good choice to go next.

Stay tuned for more ES posts..

Virtual method dispatch – how does it work?

Working with object oriented programs mostly is very straightforward. But sometimes the execution just looks like a bit of magic. Especially the virtual methods where the compiler did know about the static type at the compile time BUT that virtual method was called at the runtime. How does it work? I will try to explain that in this post.

First of all we have to understand how does our execution look like from the intermediate language point of view.

There are two IL instructions for calling methods – call and callvirt. The assumption you make based on their names is correct – one is used for calling static methods with, the second for virtual ones (REMEMBER: static methods can NEVER be virtual – yet you have to specify the type name to call it!). One thing worth mentioning is that the CLR virtual dispatch works at the method level – i.e. properties will be considered as two methods (get_X and set_X).

The motto you should remember about virtual methods is rather simple – the least derived type declaring the virtual method will be used. What does it mean is – the runtime will call to the most specific implementation of the method it can find.

Learn by example

I know this could be quite confusing – and learning by reading is not always the best way, and the easiest way for sure. Let’s consider a simple hierarchy of classes:

class AClass
{
    public virtual void Do()
    {
        Console.WriteLine("AClass here!");
    }
}
class BClass : AClass
{
    public override void Do()
    {
        Console.WriteLine("BClass here!");
    }
}
class CClass : AClass
{
    public void Do()
    {
        Console.WriteLine("CClass here!");
    }
}

The structure is rather simple, so let’s try to use such implementation in sample code:

AClass a = new AClass();
AClass b = new BClass();
AClass c = new CClass();

a.Do();
b.Do();
c.Do();

The question rises – will you be able to answer that the output will look like that on the prtsc below?

virtuality_calls

As you can see there are two interesting cases (let’s leave the a object, this is just way too simple! :_) ) – b and c objects. Each of them has it’s own story, let’s talk about it now.

b and c objects and the override keyword

This is cool – you have AClass object, but you assign to it an object which type is BClass. This means that the runtime has the info about it. Let’s dive into the IL code generated:

IL_0000: nop
IL_0001: newobj instance void TestVirtualityApp.AClass::.ctor()
IL_0006: stloc.0
IL_0007: newobj instance void TestVirtualityApp.BClass::.ctor()
IL_000c: stloc.1
IL_000d: newobj instance void TestVirtualityApp.CClass::.ctor()
IL_0012: stloc.2
IL_0013: ldloc.0
IL_0014: callvirt instance void TestVirtualityApp.AClass::Do()
IL_0019: nop
IL_001a: ldloc.1
IL_001b: callvirt instance void TestVirtualityApp.AClass::Do()
IL_0020: nop
IL_0021: ldloc.2
IL_0022: callvirt instance void TestVirtualityApp.AClass::Do()
IL_0027: nop

As you can expect there are two interesting lines for our derived objects – line IL_001b and IL_0022. As you can see both of them use callvirt method call to execute, AClass::Do() method. That is what you would expect from the compiler – the type of the object is AClass so we need to call its method. But the reason we get such results is of course the IL instruction.

As you can read on the spec of the language, this instruction is used for late-bound method call on an object. This is where the whole “magic” lies – late-bound call found that BClass overrides the original virtual method Do() from AClass (because of the override keyword). This is called the polymorphism, where for the base class object the most specific type is called.

But why doesn’t the c object method Do() been called? Everything will be clear if you look at the IL_0022 line where the call is made. We call AClass method and there is no direct connection between Do() in CClass and Do() in AClass. Even though the name of the method is the same, we are calling the Do() method on the AClass and the runtime has no connection between this method and the method in CClass. This would be the case if there was the override keyword.

The new operator – not only for object creation

The designers of the language found this mechanism quite confusing for most developers and introduced the new keyword in the context of overriding methods. This one mustn’t be confused with the ctor calls (how the compiler achieves such differential is the other topic).

One will get the warning CS0114 message from the compiler when he will write a method with the same signature like the base class and there will be no override for the virtual method (this warning states that if the inherited member is hidden there will be a warning). This will make the code more readable – there will be no confusion whether this is another method or the overridden one.

EDIT: One interesting thing to be noticed in here – the different approach between Rebuild and Build. During the first one – there will be a warning because the compiler will do a full build of the project. But the second one will not find any change (if none was made) so no warning message! Quite confusing…

The easiest way to deal with such cases is just to play with the code – you can start with the one I posted and extend it by more classes and dependencies.. I hope this background makes it a good starting point for you to explore this very interesting topic.