C# Queue, Stack, Dictionary

C# Queue uses Circular buffer internally. Using linear array or list is inefficient. Therefore Circular Buffer/ Circular array can be used to implement Queue. Also, Queue can be implemented using Linked List. Similaryly, Stack implementation can use Circular buffer or linked lists.

HashTable uses collision detection and collision avoidance to prevent collision of items inserted to it. HashTable uses linear probing and quadratic probing to do this. Linear probing works as following, while inserting an element to a hashtable, item’s hashcode is being calculated. if there is already an item with the same hashcode in the hastable, next item to the existing item is checked. if it s empty new item is inserted there. So it checks one item at a time next to the existing item until there is an empty spot. Quadratic probing work with squaring the element position and inserting the available spot. N + 1*1 , N + 2*2 , N+3*3 and so on.

Dictionary uses chaining for hashcode collision. This is one of the other difference between hashtable and dictionary the other being generics.  Chaining doesnt work like probing, instead of searching for an available slot, collided item is chained, attached to the existing item using a linked list (another data structure). Moreover, dictionary is much more efficient than stack, queue or list because of expansion strategy. While list doubles the size of the internal structure when it needs to resize, dictionary uses the next big prime number. Moreover, while inserting items to dictionary order is discarded, unlike list, queue or stack. Seaching for an element in dictionary is constant time O(1). where as in list or array, it takes linear time O(n). Therefore dictionaries are very efficient.

Moreover, Dictionaries can be used to compress, compact data and save memory. such as Huffman encoding.

c# Comparer

In C#, Comparer<T> base class can be implemented and sub typed in order for ordering, such as sorting.

Since Comparer<T> base class implements IComparer, and IComparer<T>, you wont have to implement them. Also IComparer (non generic version is already implemented for you.). You will just create a new Comparer class that extends Comparar<T> base class. and implement the custom ordering functionality.

Lets say we have a Person class that have id and name properties. and we have a PersonComparerById as follows

public class Person
{
   public string Name { set; get; }
   public int id { set; get; }
}

public class PersonComparerById : Comparer<Person>
{

  public override int Compare(Person x, Person y)
  {
    if(ReferenceEquals(x,y) || x.id == y.id)
    {
      return 0;
    }

   return x.id.CompareTo(y.id);
  }
}

// And we have the following code set:

var persons = new List<Person>();
persons.Add(new Person { id = 3, Name = "serkan" });
persons.Add(new Person { id = 5, Name = "atagun" });
persons.Add(new Person { id = 2, Name = "firat" });

IComparer<Person> personComparer = new PersonComparerById();

persons.Sort(personComparer);

foreach (var person in persons)
{
    Console.WriteLine(person.Name);
}

The result would be

firat
serkan
atagun

in sorted order. Comparer<T> base class is used for custom ordering. It can be plugged to collections for ordering.

c# EqualityComparer

EqualityComparer is used for Hashtables and Dictionaries for custom equality comparison. You ll need to make a new class and implement base class EqualityComparer<T> which have two abstract methods namely, Equals(T t1, T t2) and getHashCode().

Next is to pass an instance of the custom EqualityComparer class to the collection.

class Person{
string Name{set;get;}
int id {set;get;}
}

class PersonEqualityComparer : EqualityComprarer{

public override bool Equals(Person a, Person b){

return a.id == b.id;

}

public override int GetHashCode(){

return id.getHashCode();

}

}

This class does the equality comparison based on Person’s Id.

IEqualityComparer<Person> comparer = new PersonEqualityComparer();

Dictionary<Person, string> collection = new Dictionary<Person, string>(comparer);

collection.add(new Person{ name =”serkan”, id=1});

collection.add(new Person{name=”serkan”, id= 1});

this statement would throw and exception due to duplicate keys. Which is expected.

Dictionary<Person, string> collection = new Dictionary<Person, string>();

collection.add(new Person{ name =”serkan”, id=1});

collection.add(new Person{name=”serkan”, id= 1});

However, this statements wouldnt throw an exception cause the default comparers use different hashcode and equality comparison.

Custom EqualityComparer classes are used with dictionary and hashtables.

C# Default Parameters

public static void Method(int num, int val = 1)
{
Console.WriteLine(string.Format(“{0}, {1}”, num, val));
}

Above method can be invoked as follows :

Method(1,9);
Method(1);

and the output will be

1,9
1,1

If you dont pass a value do the optional, default parameter, it will take the default value stated in the method decleration.

C# Named Arguments

public static  void Method(string key, string value)
{
Console.WriteLine(key+” “+ value);
}

Above code can be invoked as follows :

Method(“foo”, “bar”);

or with named argument as follows :

Method(value : “bar”, key : “foo”);

This is all about the named arguments. They can be in brackets as well. []

C# Custom Exception

Suggested Custom Exception Formation in c#

[Serializable]
internal class MyException : Exception
{
public MyException()
{
}

public MyException(string message) : base(message)
{
}

public MyException(string message, Exception exception) : base(message, exception)
{
}

public MyException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}