Wednesday, 28 December 2016

Differences between Stack and Heap

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM .



Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled.The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.

Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.

You can use the stack if you know exactly how much data you need to allocate before compile time and it is not too big. You can use heap if you don't know exactly how much data you will need at runtime or if you need to allocate a lot of data.

In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap. Stack is thread specific and Heap is application specific. The stack is important to consider in exception handling and thread executions.

Difference between a.Equals(b) and a == b

Data types can be classified according to whether a variable of a particular type stores its own data or a pointer to the data. If the variable stores its own data, it is a value type and if it holds a pointer to data elsewhere in memory it is a reference type. We can assign either a reference type or a value type to a variable of the Object data type
The Equals() and == operator are used for comparison and both returns the boolean value (true/false).

Value Type

For Value Type == and Equals() works in the same way, both compare two object by value.

int a = 10;
int b = 10;

a==b and a.Equals(b) returns true , because in this case both compare two object by value.

Reference Type

In case of Reference Type both works in different way.



StringBuilder sb1 = new StringBuilder("Test");
StringBuilder sb2 = new StringBuilder("Test");

sb1 == sb2 returns false and sb1.Equals(sb2) returns true.

StringBuilder sb1 = new StringBuilder("Test");
StringBuilder sb2 = sb1;

Both sb1 == sb2 and sb1.Equals(sb2) returns true.

== operator compares reference returns true when both references point to the same object and Equals() compares object by value and it will return true if the references refers object which are equivalent.

Tuesday, 27 December 2016

Abstract Class & Interface - When to use?

Abstract Class

The "abstract" keyword indicates that the thing has a missing or incomplete implementation and must be completed by others. An abstract class is a special kind of class that has no implementation. It cannot be instantiated. Its implementation logic is provided by the classes that derive from it. It can have both abstract as well as non-abstract methods. 
It is not compulsory to have only abstract methods in an abstract class. We can also have an abstract class with only non-abstract methods. 


Why do we need an Abstract Class?

With an Abstract Class, we can provide some kind of default functionality for all derived classes to extend from. This is useful to avoid code duplication in many cases. 

  



As shown in figure we are defining an iPhone base class for Apple and then inheriting it to iPhone6 and iPhone6s sub classes. The iPhone class should be an abstract class that contains some predefined functions like Call() and SMS() for all iPhone models to share . We can also add abstract methods like Model() and Color() into the iPhone class that must be implemented by all the subclasses inheriting iPhone. The main advantage of this approach is, whenever we inherit the iPhone class into a derived class, say iPhone6s, we need not define the Call() and SMS() methods again. We just need to implement the abstract methods and we are good to go. It helps to provide default functionality in all the derived classes and also avoids code duplication. 

Key Points

1. We cannot create an object of Abstract Class but we can create a reference of it.
2. An inheritance between abstract to abstract classes is possible. We don't need to implement abstract methods of the base abstract class into a derived abstract class. We can implement it later in concrete classes. 
3. An abstract class can never be sealed or static. 

4. An abstract class can have abstract as well as non-abstract methods. 

5. The abstract keyword can be used with class, methods, properties, indexers and events.

6. Abstract members can only be declared inside an abstract class. 

7. An abstract member cannot be static or private. 

8. An abstract method cannot be marked virtual. 


9. A concrete class cannot inherit more than one abstract class, in other words multiple Inheritance is not possible. 

Interface

An Interface means a medium to interact with something. In terms of programming, an interface means a contract to interact with multiple code modules. If a class wants to communicate with an interface, it must implement it and define its members. We can call it as pure abstract class. It can contain only signature but no implementation. Interface members are implicitly public and abstract, so we cannot prefix any access modifiers to it. An interface cannot contain fields, constant members, constructors, destructors and static members.

Why do we need an Interface?





As shown in figure, if we define a class for a Smart Phone. The class can have members like OS, AppStore and Call. The Smartphone can be either Android based or iOS based and cannot be both. There is no common functionality between an Android and iOS Smartphone, so we don't need to provide any kind of default functionality. For this we make the Smartphone class abstract and also all its members abstract. This approach works fine and classes like Samsung, Apple, HTC can inherit from it.
Now, suppose Apple wants to add a new feature to its Smartphone. We can add this feature as an abstract method in our abstract base class SmartPhone. But what if HTC doesn't want that feature. So the method for new feature cannot be placed inside the abstract class SmartPhone. An alternative is to define another abstract class for new features and add methods to it. This is also a bad idea since C# doesn't support inheritance of multiple classes (abstract or concrete) into a derived class.
In this situation, an interface is useful. An interface provides only the method definitions, just like an abstract class, but can be useful in multiple inheritances. We can make the new Features class as an interface and add methods to it. It provides only the method signature and whichever class inherits it can implement it in its own way. It is also completely valid for a class to inherit more than one interface in C#. Also, we can make the SmartPhone class an interface instead of an abstract class. It is better instead of making a pure abstract class, we can use interfaces.

Key Points

1. A class may inherit several interfaces.
2. An interface cannot provide any code, just the signature.
3. An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed      as public
4. If various implementations only share method signatures then it is better to use Interfaces.

5. Cannot contain fields, constant members, constructors, destructors and static members.



Monday, 26 December 2016

Can we declare class other then public or internal in namespace?

Private:

Allowing classes to be private to a namespace would achieve no meaningful level of protection. Because private means that the member is only access in the containing class. Since a top-level class has no class containing it; it cannot be private. If you force to create a private class in Namespace, compiler will throw a compile time error "Namespace elements cannot be explicitly declared as private, protected or protected internal" .


We can declare a class as Private inside other class:

 public class Class1
  {
    temp _temp ;
    public Class1()
    {
      _temp = new temp();   
    }    

    public void SetTempClass(string p_str, int p_Int)
    {
      _temp.setVar(p_str, p_Int);
    }

    public string GetTempClassStr()
    {
      return _temp.GetStr();
    }

    public int GetTempClassInt()
    {
      return _temp.GetInt();
    }

    private class temp
    {
      string str;
      int i;

      public void setVar(string p_str, int p_int)
      {
        str = p_str;
        i = p_int;
      }

      public string GetStr()
      {
        return str;
      }

      public int GetInt()
      {
        return i;
      }
    }
  }  


Protected:

You cannot declare protected classes at the namespace level because the access modifier for outer level classes defines their visibility in relation to other assemblies. The protected visibility is used to indicate 'visible to derived classes'; this makes sense on things inside a class, but normally has no meaning at the class level.

It can be done with nested classes.


    public class OuterClass
    {
        protected class NestedClass
        {
        }
    }

C# Static Classes vs Singleton Design Pattern

Singleton is a design pattern that makes sure that your application creates only one instance of the class anytime. It is highly efficient and very graceful. Singletons have a static property that you must access to get the object reference. So you are not instantiating an object such as in the manner we do for a normal class.

class SingletonLogger
    {
        StreamWriter outStream;
        int longNumber = 0;

        static SingletonLogger _instance;

        public static SingletonLogger Instance
        {
            get { return _instance ?? (_instance = new SingletonLogger()); }
        }

        SingletonLogger() { }
        public void InitializeLogging()
        {
            if(outStream!=null){
                 outStream = new StreamWriter("myLog.txt");
            }
        }

        public void ShutDownLogging()
        {
            outStream.Close();
        }

        public void LogMessage(string message)
        {
            outStream.WriteLine((longNumber++) + ";" + message);
        }
    }

Now to access above Singleton class methods:

SingletonLogger logger=SingletonLogger.Instance;
logger.InitializeLogging();
logger.LogMessage("Hello from sample application.!!");
logger.ShutDownLogging();


For static classes we do not need to instantiate and we access properties and methods by class name.

public static class Logger
    {
        static StreamWriter outStream;
        static int longNumber = 0;
        static public void InitializeLogging()
        {
            outStream = new StreamWriter("myLog.txt");
        }

        static public void ShutDownLogging()
        {
            outStream.Close();
        }

        static public void LogMessage(string message)
        {
            outStream.WriteLine((longNumber++) + ";"+message);
        }
    }

Now to access above static class methods:

Logger.InitializeLogging();
Logger.LogMessage("Hello from sample application.!!");
Logger.ShutDownLogging();

Singleton Class instance can be passed as a parameter to another method whereas static class cannot

class SampleClass
    {
        public void SingletonMethod(SingletonSampleClass singletonSampleClass)
        {
            
        }
    }

var SampleClass= new SampleClass();
someClass.SingletonMethod(anotherSingletonSampleClass);



Singleton classes support Interface inheritance whereas a static class cannot implement an interface. So we can reuse our singleton for any number of implementations of interface confirming objects.

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

A key point is that static classes do not require an instance reference. 

Singleton classes are just user coded classes implementing the Singleton design pattern. Singleton purpose is to restrict instantiation of an class to a single instance.

About Generics in C#

Generics provide a code template for creating type-safe code without referring to specific data types. They allow you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. They allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

It helps you to maximize code reuse, type safety, and performance.

Lets take an example of non-generic collection class like ArrayList, where we add integer values to the array list and perform addition operation on the list values.

using System.Collections;
namespace SampleTypeSafety
{
    class SampleOperation
    {
        public static int Add()
        {
            ArrayList list = new ArrayList();
            list.Add(6);
            list.Add(9);

            int result = 0;
            foreach (int value in list)
            {
                result += value;
            }
            return result;
        }
    }
}

If we run above code then ot will return a value. But now add one more value to the ArrayList that the data type is float and perform the same Add operation. 

using System.Collections;
namespace SampleTypeSafety
{
    class SampleOperation
    {
        public static int Add()
        {
            ArrayList list = new ArrayList();
            list.Add(6);
            list.Add(9);
            list.Add(6.9);

            int result = 0;
            foreach (int value in list)
            {
                result += value;
            }
            return result;
        }
    }
}

Now if we run above code then it will give an error (Specified cast is not valid). Because it contains both int and float values and while retrieving values we are type casting it to int.

Compared to above, Generics allow us to realize type safety at compile time. They allow us to create a data structure without committing to a specific data type. 

using System.Collections.Generic;
namespace SampleTypeSafety
{
    class SampleOperation
    {
        public static int Add()
        {
            List<int> list = new List<int>();
            list.Add(5);
            list.Add(9);            

            int result = 0;
            foreach (int value in list)
            {
                result += value;
            }
            return result;
        }
    }
}

In the code above we define a list of type int. In other words, we can only add an integer value to the list and can't add a float value to it so when we retrieve values from the list using a foreach statement we only get an int value.

We can also reuse code using Generics : 

using System.Collections.Generic;
namespace SampleReuse
{
    class SampleOperation
    {
        public static void Swap<T>(ref T lhs, ref T rhs)
      {
         T temp;
         temp = lhs;
         lhs = rhs;
         rhs = temp;
      }
    }
}

Here we have used a generic class and declared a generic method with a type parameter. We can use the same method to swap values for different types. e.g. : 

int a, b;
char c, d;
a = 10;
b = 20;
c = 'I';
d = 'V';
Swap<int>(ref a, ref b);
Swap<char>(ref c, ref d);

From Performance perspective, Generics give better performance as no boxing and unboxing is required.

Sunday, 25 December 2016

Why is Dictionary preferred over hashtable?

In Hashtable type casting will be required so performance wise Dictionary is preferred.

Below are some differences between them : 

Dictionary:

  • It returns error if we try to find a key which does not exist.
  • It is faster than a Hashtable because there is no boxing and unboxing.
  • Only public static members are thread safe.
  • Dictionary is a generic type which means we can use it with any data type.
Hashtable:
  • It returns null if we try to find a key which does not exist.
  • It is slower than dictionary because it requires boxing and unboxing.
  • All the members in a Hashtable are thread safe,
  • Hashtable is not a generic type,