What is the default capacity of a List?

As an .net developer we use List very frequently. List represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

Most of us think framework development team would have made all the List operations optimal. We never try to put thought, if we can do some thing to make it better. We can do few things as a developer to help .net framework to use List  optimally. One of those things is setting its capacity when we create a list. if you know in advance how many items you are going to add in a list, then it will be a better to make a list of predefined capacity.

if we don’t define a capacity of a list then it starts with a Capacity of 0. When you add the first element, then .net framework allocates a capacity of 4. After that, the capacity keeps doubling if expansion is needed.

This code spinet should demonstrate the behavior:

List<int> list = new List<int>();
int capacity = list.Capacity;
Console.WriteLine("Capacity: " + capacity);

for (int i = 0; i < 100000; i++)
{
    list.Add(i);
    if (list.Capacity > capacity)
    {
        capacity = list.Capacity;
        Console.WriteLine("Capacity: " + capacity);
    }
}

Capacity should be used if you know roughly how many items you want to store in List (or in Stack, or Queue).

That way you will avoid memory copying. The memory copying happens because under the hood Lists (Stacks and Queues) rely on array to store their items. That array size is you capacity, but it’s not the same as the list size. As size of list needs to be bigger than the size of array, the List implementation will allocate a bigger array and will copy all items from old array to the new one plus newly added items.

So, if you know that you may have from, say, 50 to 60 items in your list, create a list with capacity 60 and no memory deallocation will happen. And Garbage Collector will not have to clean up old arrays

What is the default capacity of a List?

Why isn’t the static constructor from my base class called?

Lets say we have 2 classes:

public abstract class Foo
{
    static Foo()
    {
        print("4");
    }
}

public class Bar : Foo
{
    static Bar()
    {
        print("2");
    }

    static void DoSomething()
    {
        /*...*/
    }
}

We expected that after calling Bar.DoSomething() (assuming this is the first time we access the Bar class) the order of event will be:

  1. Foo’s static constructor (again, assuming first access) > print 4
  2. Bar’s static constructor > print 2
  3. Execution of DoSomething

At the bottom line we expect 42 to be printed. After testing, it seems that only 2 is being printed.

Reason :

The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

  1. An instance of the class is created.
  2. Any of the static members of the class are referenced.

Because you are not referencing any of the members of the base class, the constructor is not being executed.

Why isn’t the static constructor from my base class called?

nameof Operator in C#

C# 6.0 introduced a new operator named, nameof  that accepts the name of code element and returns a string literal of the same element.  The nameof operator can take as a parameter like class name and its all members like method, variables, properties and return the string literal.  This avoids having hardcoded strings to be specified in our code as well as avoid explicitly use of reflection to get the names.

Below is the simple code snippets that show the uses of nameof operator.

class Program
{
    static void Main(string[] args)
    {
        WriteLine(nameof(Student));
        WriteLine(nameof(Student.Roll));
        WriteLine(nameof(Student.Name));
        WriteLine(nameof(Student.Address));
    }
}

class Student
{
    public int Roll { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
}

The output would be like below :image_thumb

nameof Operator in C#

Null Propagation C#

Null propagation enable developers to check the null value with in an object reference chain. The null –  propagation operator ( ?.) , returns null if anything in the object reference chain in null. This avoid checking null for each and every nested objects if they are all in referenced and having null values.

Consider we have class called Student, and which having another property Address of type Address class. Now we can have the following code snippet to print the HomeAddress.

if (student != null &amp;&amp; student.Address != null)
{
    WriteLine(student.Address.HomeAddress);
}
else
{
    WriteLine("No Home Address");
}

As we can see, to avoid  the null-reference exception, we have checked the null for student, and student.Address as they can have null reference as object.

Now, the above code block can be re-written using null – propagation( ?.) operator as follows:

WriteLine(student?.Address?.HomeAddress ?? "No Home Address");

Isn’t it really nice. Instead of check each and individual objects, using ?. we can check entire chain of reference together and whenever there is a null values, it return null.

Null Propagation C#

What’s New in C# 7.0

C# 7.0 adds a number of new features and brings a focus on data consumption, code simplification and performance. Perhaps the biggest features are tuples, which make it easy to have multiple results, and pattern matching which simplifies code that is conditional on the shape of data. But there are many other features big and small. They all combine to make your more efficient and clear and make developers more productive.

Continue reading “What’s New in C# 7.0”

What’s New in C# 7.0

Singleton Design Pattern

Singleton pattern is one of the simplest design patterns. This type of design pattern comes under creational pattern as this pattern provides one of the ways to create an object.

This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

Continue reading “Singleton Design Pattern”

Singleton Design Pattern