Thursday, October 12, 2017

Factory pattern in C#

Ok, so the idea is to create a class able to mass-produce instances of a different class or classess.
First, let's create something to be produced by our Factory class as in product:

    abstract class Product
    {
        public abstract ProductType GetProductType();
    }

    class Car : Product
    {
        public override ProductType GetProductType()
        {
            return ProductType.Car;
        }
    }

    class Motorcycle : Product
    {
        public override ProductType GetProductType()
        {
            return ProductType.Motorcycle;
        }
    }

    class Airplane : Product
    {
        public override ProductType GetProductType()
        {
            return ProductType.Motorcycle;
        }
    }

You don't have to do it exactly this way, I mean, you can use interfaces if you want or even concrete unrelated classes (which you can return from Factory as Object).

Now we need to make some Factories. I create one for each type of product, but again, this one is up to you, you can implement this functionality as you please:

    abstract class Factory
    {
        public abstract Product createProduct();
    }

    class CarFactory : Factory 
    {
        public override Product createProduct()
        {
            return new Car();
        }
    }

    class MotorcycleFactory : Factory
    {
        public override Product createProduct()
        {
            return new Motorcycle();
        }
    }

    class AirplaneFactory : Factory
    {
        public override Product createProduct()
        {
            return new Airplane();
        }
    }

Well, I guess, that's about it.

Singleton pattern in C#



Frankly I am a big fan of globals and there is no way you can convince me that Singleton is better in any way. Here is the quite popular (from what I heard) not thread-safe implementation:

class Singleton
{
    private static Singleton instance;

    private Singleton() {}

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }

             return instance;
        }
    }
}

If your extra cautious, you can also make this class uninheritable using keyword sealed like this:

sealed class Singleton
{
    private static Singleton instance;

    private Singleton() {}

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }

             return instance;
        }
    }
}

I mean it's crystal clear that this is not thread-safe, but the real question is, why do people keep mentioning thread-safety which isn't directly related to this design pattern in particular?. Singleton's goal is to merely restrict class instantiation, which has nothing to do with multithreading.

Ok, here is a thread-safe implementation. As you can see the primary difference between the two is a presence of a lock, which is beyond intuitive, I mean anyone would do it exactly this way:

sealed class Singleton
{
    private static object dummy = new Object();
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (dummy)
               {
                    if (instance == null)
                        instance = new Singleton();
               }
         }

         return instance;
         }       
    }
}

In case you forgot, volatile keyword tells the compiler that a variable is volatile, meaning its value may rapidly change, for example, if multiple threads change it. In other words, using volatile keyword we ask the compiler not to optimize anything about this variable in particular.



C# Boxing and Unboxing

Boxing in C# means wrapping a value inside an object. Correspondingly, Unboxing is a reverse operation allowing you to extract a value from an object. Value in this case implies a variable of Value Type, not instance of any type as it is in C++ for example. Here is what boxing looks like:

int number = 9;
object obj = number;

As you can see, conversion is implicit. Well, of course, if you want you can do it explicitly:

 int number = 9;
object obj = (object)number;

Unboxing is not as as safe as boxing, that's why you have to do it explicitly:

int number = 9;
object obj = number;
int numberOuttaBox = (int)obj;

Oh, and remember to extract exactly what you previously boxed, because for some reason C# is like real strict about it. Basically what I mean is that you cannot get away with this:

int number = 9;
object obj = number;
float numberOuttaBox = (float)obj;

Such misbehaving is gonna result in getting the following exception:
System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.Single'.'

In general, its very easy to bypass it, just unbox what you previously put and then cast to whatever you want either implicitly:

int number = 9;
object obj = number;
float numberOuttaBox = (int)obj;

Or explicitly:

int number = 9;
object obj = number;
float numberOuttaBox = (float)(int)obj; // Excessive, but it's just an example.

Please keep in mind that boxing/unboxing is not casting and excessive use of this operation may severely affect overall performance.

.NET Garbage Collector



.NET got quite sophisticated garbage collector operating over so-called managed heap, which is basically just a heap combining two more specific heaps intended for small and large objects. All objects on a heap belong to certain generation. The first generation (Generation 0) is small recently created objects with shortest life expectancy, second generation (Generation 1) is what objects of generation 0 become if they manage to survive garbage collection being younger generation and finally third generation (Generation 2) is a generation for either true survivors, meaning objects of younger generations that got promoted or just large objects (over 85kB).

If you need more flexibility you can actually control your Grabage Collector behavior through static class GC.

For example, you might want to collect some certain generation:

GC.Collect(0);
GC.Collect(1);
GC.Collect(2);
GC.Collect(); // This one is gonna collect all generations.


Or you can make GC enter so-called "no GC region latency mode" which allows you to execute certain parts of your code without GC intervention:

// Specify how much may be allocated without disturbing GC
GC.TryStartNoGCRegion(48);
// Your time-critical code
GC.EndNoGCRegion();


Keep in mind that TryStartNoGCRegion accepts size per heap.There are two heaps
(for small and large objects), so total size is whatever you pass in there
multiplied by 2. In the example above, total size would be 48 * 2 = 96.

C# multithreading

C# multithreading is a pretty straightforward thingy. Here is how we spawn a thread:

using System;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Whatever(){}

        static void Main(string[] args)
        {
            Thread thread = new Thread(Whatever);

            thread.start();
        }
    }
}

using System;
using System.Threading;

namespace ConsoleApp
{
    class Dummy
    {
        public void Whatever(){}
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dummy dummy = new Dummy();
            Thread thread = new Thread(dummy.Whatever());

            thread.start();
        }
    }
}

Thread class constructor accepts two types of delegate - ThreadStart and ParametrizedThreadStart. The difference between the two is that ParametrizedThreadStart allows us to pass some arbitrary object to a thread function like this:

using System;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Whatever(object obj){}

        static void Main(string[] args)
        {
            Thread thread = new Thread(Whatever);

            thread.Start("Whatever");
        }
    }
}

If your project requires massive parallelism, it probably makes sense to try using so-called thread pool which is basically nothing more than a collection of dormant threads you can reuse.

using System;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Whatever(object obj)
        {
            (obj as ManualResetEvent).Set();
        }

        static void Main(string[] args)
        {
            ManualResetEvent[] events = new ManualResetEvent[2];

            for (int i = 0; i < events.Length; ++i)
            {
                events[i] = new ManualResetEvent(false);

                ThreadPool.QueueUserWorkItem(Whatever, events[i]);
            }

            WaitHandle.WaitAll(events);
        }
    }
}



Monday, October 9, 2017

Fun with C# MongoDB driver

using MongoDB.Driver;

namespace MongoDBFun
{
    class Individual
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    class Program
    {
        static IMongoClient _client;
        static IMongoDatabase _database;

        static void Main(string[] args)
        {
            _client = new MongoClient();
            _database = _client.GetDatabase("mydb");

            var individuals = _database.GetCollection<Individual>("individuals");

            individuals.InsertOne(new Individual {
                FirstName = "John",
                LastName = "Smith"
            });
        }
    }
}

C# delegates

A delegate is socalled reference type possessing certain qualities of C pointer, but meant for methods. Yeah, exactly, you can use a delegate to pass around a method with a compatible signature of absolutely any class. Here is what a delegate looks like:

using System;

namespace MyConsoleApp
{
    delegate void MyDelegate();

    class A
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is A");
        }
    }

    class B
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is B");
        }
    }

    class C
    {
        public static void SayYourName()
        {
            Console.WriteLine("My name is C");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var a = new A();
            var b = new B();

            MyDelegate ADelegate = a.SayYourName;
            MyDelegate BDelegate = b.SayYourName;
            MyDelegate CDelegate = C.SayYourName;

            ADelegate();
            BDelegate();
            CDelegate();
        }
    }
}

As you can see it doesn't care whose method it refers to or if its static or not. Also one delegate may contain other delegates. Such a delegate is called multicast delegate and it looks like this:

using System;

 namespace MyConsoleApp
{
    delegate void MyDelegate();

    class A
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is A");
        }
    }

    class B
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is B");
        }
    }

    class C
    {
        public static void SayYourName()
        {
            Console.WriteLine("My name is C");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var a = new A();
            var b = new B();

            MyDelegate ADelegate = a.SayYourName;
            MyDelegate BDelegate = b.SayYourName;
            MyDelegate CDelegate = C.SayYourName;

            ADelegate += BDelegate + CDelegate;
            ADelegate(); // Now ADelegate is multicast delegate
        }
    }
}

If you want, you can exclude certain delegate or delegates from multicast delegate list:

using System;

 namespace MyConsoleApp
{
    delegate void MyDelegate();

    class A
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is A");
        }
    }

    class B
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is B");
        }
    }

    class C
    {
        public static void SayYourName()
        {
            Console.WriteLine("My name is C");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var a = new A();
            var b = new B();

            MyDelegate ADelegate = a.SayYourName;
            MyDelegate BDelegate = b.SayYourName;
            MyDelegate CDelegate = C.SayYourName;

            ADelegate += BDelegate + CDelegate;
            ADelegate -= BDelegate; // BDelegate has been excluded from ADelegate list
            ADelegate();
        }
    }
}