Friday, 12 April 2013

C# Dictionary: How to create and use Key / Value pairs in C# using Dictionary?

C# Dictionary: How to create and use Key / Value pairs in C# using Dictionary?

The Dictionary type provides fast lookups with keys to get values. With dictionary, we can use keys and values of any type, including ints and strings. Dictionary is used when we have many different elements. We specify its key type and its value type. It provides good performance.

The Dictionary instance is represented by a collection of key and value pairs. Dictionary is a generic class. This means it requires you to specify a type for it to use. So, you can use an int key, just as easily as a string key.

C# Program to add Key/Value to dictionary

using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
       Dictionary<string, int> dictionary = new Dictionary<string, int>();
       dictionary.Add("cat", 2);
       dictionary.Add("dog", 1);
       dictionary.Add("cow", 0);
       dictionary.Add("horse", -1);
    }
}

How to get values depending on the keys? How to check whether dictionary contains the desired value or not? Here is a simple program which will check and fetch the values corresponding to the keys.

using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
      Dictionary<string, int> dictionary = new Dictionary<string, int>();
      dictionary.Add("crow", 1);
      dictionary.Add("cow", 5);
      // See whether Dictionary contains this string.
      if (dictionary.ContainsKey("crow"))
      {
         int value = dictionary["crow"];
         Console.WriteLine(value);
      }
      // See whether Dictionary contains this string.
      if (!dictionary.ContainsKey("cat"))
      {
       Console.WriteLine(false);
      }
   }
}

Output
1
False

Now lets try to fetch all the values of dictionary using foreach loop by storing dictionary in list.  We can use the Keys property and then look through each key and lookup the values. This method is slower but has the same results. Using the Keys collection and putting it in an array or List is effective. The Keys property returns a collection of type KeyCollection, not an actual List. We can convert it into a List.

using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
       Dictionary<string, int> d = new Dictionary<string, int>()
       {
           {"cat", 2},
           {"dog", 1},
           {"cow", 0},
           {"horse", -1}
       };
      
       // Store keys in a List
       List<string> list = new List<string>(d.Keys);
       // Loop through list
       foreach (string k in list)
       {
          Console.WriteLine("{0}, {1}", k, d[k]);
       }
    }
}

Output
cat, 2
dog, 1
cow, 0
horse, -1

You can use the GetHashCode method and override it to create Dictionaries or hashes with the class. This can improve performance in those cases. A custom GetHashCode can influence performance.

Thursday, 11 April 2013

Difference between "string" and "String" in C# and DOTNET

Difference between "string" and "String" in C# and DOTNET
 
Well, Difference between "string" and "String, is the obvious question anybody can ask you in any .NET technical interview. So be prepared for it.
 
"string" and "String" are same thing. "string" is a C# keyword which is simply an alias for the System.String. "string" is a compiler shortcut for System.String class.
 
"string" and "String" are interchangeable and there is no difference when and where you should use one or the other. But I will advise to be consistent with which one you did use though.
 
Difference between "string" and "String":
 
1. "string" does not exist in .NET, it only exists in C#. .NET Framework implicitly converts "string" into "System.String" which is compatible with .NET Framework. CTS (Common Type System) does this conversion. String belongs to .NET platform (is accessible in all languages), while string is language specific (C#). Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference.
 
2. "String" is an class (System.String) and is a Reference type while "string" is value type.
 
3. String is a class name while string is a restricted keyword
 
When to use what?
 
You can use whichever you prefer, although I generally use string when I'm planning on using it much like a primitive data type (similar to int, float, or bool) and String when I'm planning on using it as an object/class. For example:
 
string abc = "   ";
if (String.isNullOrWhitespace(abc))
{
    // ...
}
 
In the case above, I'm planning on using abc simply to store some text (effectively as a primitive), so I use string; however, when I call String.isNullOrWhitespace(string), I use String. I do this, because generally the first letter of class names are capitalized (String) while the first letter of primitives (such as int) are not.

Wednesday, 10 April 2013

Difference between an Abstract Class and Interface in C#

Difference between an Abstract Class and Interface in C#

Difference between an abstract class and interface is a very common concept and technical interview question. One must know this difference as its common in all the programming languages. I will try to make difference between abstract classes and interfaces with examples in C#.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

Example of Interface in C#

using System;
interface IMyInterface
{
    void Read();
}
class Test : IMyInterface
{
    public void Read()
    {
      Console.WriteLine("Read");
    }
}
class Program
{
    static void Main()
    {
      IMyInterface myInterface = new Test(); // Create instance.
      myInterface.Read(); // Call method on interface.
    }
}

Output
Read

Example of Abstract Class in C#

using System;
abstract class Test
{
    public int _a;
    public abstract void A();
}
class Example1 : Test
{
    public override void A()
    {
      Console.WriteLine("Example1.A");
      base._a++;
    }
}
class Example2 : Test
{
    public override void A()
    {
      Console.WriteLine("Example2.A");
      base._a--;
    }
}
class Program
{
    static void Main()
    {
      // Reference Example1 through Test type.
     Test test1 = new Example1();
     test1.A();
     // Reference Example2 through Test type.
     Test test2 = new Example2();
      test2.A();
    }
}

Output
Example1.A
Example2.A

Conclusion

1. Multiple inheritance: A class may inherit several interfaces while a class may inherit only one abstract class.

2. You cannot declare any data member in an interface while you can do this in an abstract class.

3. You can only declare member functions but not define their bodies, but you can also define bodies of member functions. In case of abstract class you can declare and define bodies of member functions but atleast on member functions should be abstract which has no body.

4. An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public but in abstract class you have this flexibility.

Abstract and Override Methods in C#

Abstract and Override Methods in C#

Abstract methods have no implementations. The implementation logic is provided rather by classes that derive from them. We use an abstract class to create a base template for derived classes.

Example

We introduce first an abstract class named Test. Two other classes derive from Test: the Example1 and Example2 classes. In the Test class, we have a field and also an abstract method.

Abstract methods cannot have bodies. This makes sense because those bodies would never be used.

using System;
abstract class Test
{
    public int _a;
    public abstract void A();
}
class Example1 : Test
{
    public override void A()
    {
       Console.WriteLine("Example1.A");
       base._a++;
    }
}
class Example2 : Test
{
    public override void A()
    {
       Console.WriteLine("Example2.A");
       base._a--;
    }
}
class Program
{
    static void Main()
    {
      // Reference Example1 through Test type.
      Test test1 = new Example1();
      test1.A();
      // Reference Example2 through Test type.
      Test test2 = new Example2();
       test2.A();
    }
}

Output
Example1.A
Example2.A

When you create a derived class like Example1 or Example2, you must provide an override method for all abstract methods in the abstract class. The A() method in both derived classes satisfies this requirement.

Static Class and Methods in C#

Static Class and Methods in C#

A static class is never instantiated. The static keyword on a class enforces that a type not be created with a constructor. In the static class, we access members directly on the type. A static class cannot have non-static members. All methods, fields and properties in it must also be static.

Example

To start, there are two classes in this program: the Program class, which is not static, and the ABC class, which is static. You cannot create a new instance of ABC using a constructor. Trying to do so results in an error.

Inside the ABC class, we use the static modifier on all fields and methods. Instance members cannot be contained in a static class.

using System;
class Program
{
    static void Main()
    {
      // Cannot declare a variable of type ABC.
      // This won't blend.
      // ABC abc= new ABC ();
      // Program is a regular class so you can create it.
      Program program = new Program();
      // You can call static methods inside a static class.
      ABC._ok = true;
      ABC.Blend();
    }
}

static class ABC
{
    // Cannot declare instance members in a static class!
    // int _test;
    // This is ok.
    public static bool _ok;
    // Can only have static methods in static classes.
    public static void Blend()
    {
      Console.WriteLine("Blended");
    }
}

Output
Blended

Tuesday, 9 April 2013

Virtual Methods and Override Modifier in C#

Virtual Methods and Override Modifier in C#

Virtual methods are meant to be re-implemented in derived classes. The C# language provides the override modifier for this purpose. This keyword specifies that a method replaces its virtual base method.

Whereas a virtual method introduces a new method, an override method specializes an existing inherited virtual method by providing a new implementation of that method.

Example

This program illustrates the difference between an override method in a derived class, and a method that is not an override method. It does nothing useful but helps us learn about override methods.

In the example, the class A is the base class. It has the virtual method Y. In class B, we override Y. In class C, we implement Y but do not specify that it overrides the base method.

using System;
class A
{
    public virtual void Y()
    {
       // Used when C is referenced through A.
       Console.WriteLine("A.Y");
    }
}

class B : A
{
    public override void Y()
    {
        // Used when B is referenced through A.
        Console.WriteLine("B.Y");
    }
}

class C : A
{
    public void Y() // Can be "new public void Y()"
    {
       // Not used when C is referenced through A.
       Console.WriteLine("C.Y");
    }
}

class Program
{
    static void Main()
    {
       // Reference B through A.
       A ab = new B();
       ab.Y();
       // Reference C through A.
       A ac = new C();
       ac.Y();
    }
}

Result
B.Y
A.Y

In this example, the A type is used to reference the B and C types. When the A type references a B instance, the Y override from B is used. But when the A type references a C instance, the Y method from the base class A is used.

C# Base and Constructor Initializer: How to overload constructors in C#?

C# Base and Constructor Initializer: How to overload constructors in C#?

Base is used in constructors. A derived class constructor is required to call the constructor from its base class.

Example

The program uses a base class and a derived class. The derived class must use a base constructor initializer, with the base keyword, in its constructor declaration. This initializer is specified by adding a colon and the base keyword after the derived constructor parameter list.
using System;

public class A // This is the base class.
{
    public A(int value)
    {
       // Executes some code in the constructor.
       Console.WriteLine("Base constructor A()");
    }
}

public class B : A // This class derives from the previous class.
{
    public B(int value)
                                   : base(value)
    {
       // The base constructor is called first.
       // ... Then this code is executed.
       Console.WriteLine("Derived constructor B()");
    }
}

class Program
{
    static void Main()
    {
       // Create a new instance of class A, which is the base class.
       // ... Then create an instance of B, which executes the base constructor.
       A a = new A(0);
       B b = new B(1);
    }
}

Output
Base constructor A()
Base constructor A()
Derived constructor B()

Explanation

In this program, class A and class B both introduce constructors. Class A is the parent or base class for class B, which is referred to as the derived class. The "B : A" syntax indicates that class B derives from class A. The constructor in class B calls into the constructor of class A using base initializer syntax.

C# Constructor Initializer

This is used in constructors. It is used to overload the constructors in a C# program. It allows code to be shared between the constructors. Constructor initializers, which use the this-keyword, prove useful in nontrivial classes.

Example

This program contains a class called Mouse with two public constructors. The first constructor is parameterless and it calls into the second constructor, using this-constructor initializer syntax.

The this-keyword in this context instructs the compiler to insert a call to the specified constructor at the top of the first constructor. The target constructor is determined through the process of overload resolution.

using System;
class Mouse
{
    public Mouse()
                              : this(-1, "")
    {
           // Uses constructor initializer.
    }
   
    public Mouse(int weight, string name)
    {
        // Constructor implementation.
        Console.WriteLine("Constructor weight = {0}, name = {1}", weight,  name);
    }
}

class Program
{
    static void Main()
    {
       // Test the two constructors for Mouse type.
       Mouse mouse1 = new Mouse();
       Mouse mouse2 = new Mouse(10, "Sam");
    }
}

Output
Constructor weight = -1, name =
Constructor weight = 10, name = Sam

Explanation:

We see the this-keyword in the context of a constructor. To use the this-keyword, specify it after a colon following the parameter list. The constructor name must match that of the declared class where you are adding it.