Translate

Sunday, October 13, 2013

C# operator overloading and conversion operator example

Operator overloading means you can give your own meaning to an operator (+,- etc) when working on specific types. In the example below I will make it possible to add two complex numbers.


using System;
using System.Collections.Generic;
using System.Threading;



internal class Playground
{
   
    private static void Main(string[] args)
    {
        var c1 = new ComplexNumber {Real = 1,Imaginary =2};
        var c2 = new ComplexNumber { Real = 2, Imaginary = 2 };
        var c3 = c1 + c2;
    }

    public struct ComplexNumber
    {
        public int Real { get; set; }
        public int Imaginary { get; set; }

        public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
        {
            var result = new ComplexNumber {Real = (c1.Real + c2.Real), Imaginary = (c1.Imaginary + c2.Imaginary)};
            return result;
        }
    }

  
}

I could also provide a method to convert an integer to a complex number, using a converter operator as shown below.


using System;
using System.Collections.Generic;
using System.Threading;



internal class Playground
{
   
    private static void Main(string[] args)
    {
        var c1 = new ComplexNumber {Real = 1,Imaginary =2};
        var c2 = new ComplexNumber { Real = 2, Imaginary = 2 };
        var c3 = c1 + c2;

        var c4 = (ComplexNumber) 5;//Convert an int into a complex number
    }

    public struct ComplexNumber
    {
        public int Real { get; set; }
        public int Imaginary { get; set; }

        public static implicit operator ComplexNumber(int i)
        {
            return new ComplexNumber {Real = i};
        }

        public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
        {
            var result = new ComplexNumber {Real = (c1.Real + c2.Real), Imaginary = (c1.Imaginary + c2.Imaginary)};
            return result;
        }
    }

  
}




C# Events Tutorial using standard .net event pattern

using System;
using System.Threading;

namespace ConsoleApplication5
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var publisher = new Publisher();
            var johnsSubscriber = new JohnsSubscriber();
            var stevesSubscriber = new StevesSubcsriber();

            publisher.SqlServerDownEvent += johnsSubscriber.SendJohnEmail;
            publisher.SqlServerDownEvent += stevesSubscriber.SendSteveText;

            while (true)
            {
                if (PingSqlServer() == false)
                {
                    //When SQL server is down raise event
                    Console.WriteLine("Server down!");
                    publisher.RaiseEvent();
                }
                else
                {
                    Console.WriteLine("All is good");
                }
                Thread.Sleep(1000);
            }
        }

        private static bool PingSqlServer()
        {
            //All this method does is randomly return a false
            var random = new Random();

            int i = random.Next(1, 30);
            if (i > 20)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }

    public class Publisher
    {
        public event EventHandler<ServerDownEventArgs> SqlServerDownEvent;

        public void RaiseEvent()
        {
            SqlServerDownEvent(this, new ServerDownEventArgs(DateTime.Now));
        }
    }

    public class ServerDownEventArgs : EventArgs
    {
        public readonly DateTime Dt;

        public ServerDownEventArgs(DateTime dt)
        {
            Dt = dt;
        }
    }

    public class JohnsSubscriber
    {
        public void SendJohnEmail(object sender, ServerDownEventArgs e)
        {
            Console.WriteLine("An email was set to John, that the server went down as {0}", e.Dt);
        }
    }

    public class StevesSubcsriber
    {
        public void SendSteveText(object sender, ServerDownEventArgs e)
        {
            Console.WriteLine("A text was set to Steve, that the server went down as {0}", e.Dt);
        }
    }
}


C# Fibonacci Series

By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.

0,1,1,2,3,5,8,13...

A C# program that prints out first 6 fibonacci numbers

using System;

namespace ConsoleApplication4
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            int[] fibonacci = GetFibonacci(6);

            for (int i = 0; i < fibonacci.Length; i++)
            {
                Console.WriteLine(fibonacci[i]);// 0 1 1 2 3 5
            }
        }

        private static int[] GetFibonacci(int i)
        {
            var fibonacciSeries = new int[i];

            //Initialize first two values
            fibonacciSeries[0] = 0;
            fibonacciSeries[1] = 1;

            for (int x = 2; x < i; x++)
            {
                fibonacciSeries[x] = fibonacciSeries[(x - 1)] + fibonacciSeries[(x - 2)];
            }

            return fibonacciSeries;
        }
    }
}



A C# program that prints out first 6 fibonacci numbers using an Iterator


using System;
using System.Collections.Generic;

namespace ConsoleApplication4
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            IEnumerable<int> fibonacci = GetFibonacci(6);
            foreach (int f in fibonacci)
            {
                Console.WriteLine(f); // 0 1 1 2 3 5
            }
        }

        private static IEnumerable<int> GetFibonacci(int i)
        {
            var fibonacciSeries = new int[i];

            for (int x = 0; x < i; x++)
            {
                switch (x)
                {
                    case 0:
                        fibonacciSeries[0] = 0;
                        yield return fibonacciSeries[0];
                        break;
                    case 1:
                        fibonacciSeries[1] = 1;
                        yield return fibonacciSeries[1];
                        break;
                    default:
                        fibonacciSeries[x] = fibonacciSeries[(x - 1)] + fibonacciSeries[(x - 2)];
                        yield return fibonacciSeries[x];
                        break;
                }
            }
        }
    }
}


Saturday, October 12, 2013

Covariant and contravariant generic interface C#

Covariance

If the type T is marked as "out" in a generic interface, then that means the interface will only output T. It doesnot have any method that takes T as an input. An example of a Covariant interface in .net is IEnumerable<T>. This interface is defined as

public interface IEnumerable<out T> : IEnumerable
  {
     
    IEnumerator<T> GetEnumerator();
  }


Significance:
What this practically means is that, in place of T, you can give it a child class of T.

For example if its expecting a List of objects you can give a List of strings.

using System;
using System.Collections.Generic;

namespace ConsoleApplication5
{
  
    internal class Program
    {
        private static void Main(string[] args)
        {
            var s = "";
            var o=new object();

            IEnumerable<string> strings;
            IEnumerable<object> objects;

            objects=new List<string>();//allowed 
            strings = new List<object>();//Throws Compile time error
        }
    }

    
}


Contravariance

This is the opposite of Covariance. If a type T is marked "in" in a generic interface, then that means that the interface has methods that accept T as an input and no methods in this interface output T. In the .net framework IComparer<T> is contravariant.


  public interface IComparer<in T>
  {     
    int Compare(T x, T y);
  }

Significance

 In place of T you can give it a Parent of T.

For example 

using System;
using System.Collections.Generic;

namespace ConsoleApplication5
{


    internal class Program
    {
        private static void Main(string[] args)
        {
            var s = "";
            var o = new object();

            var strings = new List<string>();


            IComparer<Animal> a1 = new ObjectComparer();//allowed
            IComparer<Animal> a2 = new PersonComparer();//throws compile time error

        }
    }
    public class Animal
    {

    }

    public class Person : Animal
    {


    }

    public class ObjectComparer : IComparer<object>
    {


        public int Compare(object x, object y)
        {
            return 0;
        }
    }

   

    public class  PersonComparer : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            return 0;
        }
    }




}


Thursday, October 10, 2013

HTTP Error 404.15 - Not Found (asp.net 4.0, IIS 7.5)

HTTP Error 404.15 - Not Found

The request filtering module is configured to deny a request where the query string is too long.


This is what I did to increase the query string length accepted by the asp.net web application (.net 4.0, IIS 7.5). It worked for me.


Add this to your web.config

<system.web> 
    <httpRuntime maxQueryStringLength="2097151"></httpRuntime> 
</system.web>

  <system.webServer> 
    <security>
      <requestFiltering>
        <requestLimits maxQueryString="2097151"/>
      </requestFiltering>
    </security>
  </system.webServer>




Tuesday, October 8, 2013

C# When to explicity implement an interface

You will explicitly implement interface mainly for these reasons

1>If two of the implemented interfaces have the same method signature.Then implementing them explicitly is the only way.

using System;

namespace ConsoleApplication5
{
    class Program
    {

        static void Main(string[] args)
        {
            var calc = new Calculator();

            /*Note: When you implement an interface explicitly,
            then casting your class instance into that interface,
             is the only way to access it's methods*/

            ((IOrderCount)calc).GetCount();    //Displays Order Count
            ((IInventoryCount)calc).GetCount();//Displays Inventory Count
        }
    }

    interface IOrderCount
    {
         void GetCount();
    }

    interface IInventoryCount
    {
        void GetCount();
    }

    public class Calculator  : IOrderCount, IInventoryCount
    {
          void IOrderCount.GetCount()
        {
            Console.WriteLine("Order Count");
        }

        void IInventoryCount.GetCount()
        {
            Console.WriteLine("Inventory Count");
        }
    }

}


2>Another reason you want to explicitly implement an interface is if you want to focus only on that interface when using it. For instance in the example above, when I do  ((IOrderCount)calc)  I can only access methods on IOrdercount.

Sunday, October 6, 2013

Difference between class and struct C#

class
struct
Reference type
Value Type
Cannot have explicit parameter less constructor
If you define constructor, then all the fields must be initialized, in the constructor.
Cannot have finalizer.

Cannot have field initializers
Supports Inheritance
Does not support inheritance



Class instantiation execution order (Initialization order)

When you instantiate a class, this is the order in which it takes place
  • Static fields (if not already initialized)
  • Static constructor (if not already called)
  • Instance fields
  • Parent class static field (if not already initialized)
  • Parent class static constructor (if not already called)
  • Parent class instance field
  • Parent class instance constructor
  • Instance constructor
If you run this line of code, in the green comments you can see the order in which execution takes place

var c = new Child();



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibrary1
{
    public class Parent
    {
        public int I=0;//Executes 6th
        public static int X=0;//Executes 4th

         static Parent()
         {
             X = 10;//Executes 5th
         }

        public Parent()
        {
           I = 100;//Executes 7th
        }
    }

    public class Child:Parent
    {
        public int J=0;//Executes 3rd
        public static int Y=0;//Executes 1st

        static Child()
        {
            Y = 55;//Executes 2nd
        }

        public Child()
        {
            J = 5;//Executes 8th
        }
       
    }
}