I really appreciate if you can share the link with your friends via Facebook,twitter,blog etc.

24 April 2011

Calling Virtual Functions from a Constuructor

when the virtual method is overriden in a derived class, this method will be invoked even before the constructor of the derived class has been invoked! which probably was not anticipated by the developer of the derived class!

Example

using System;
namespace VirtualTest
{
    public class Base
    {
        protected  string StrMyString= "Value In Base";


        public Base()
        {
            Console.WriteLine("Base Class Constructor");
            Example1();
        }
        // This will be overridden in the derived type.
        public virtual void Example1()
        {
            Console.WriteLine ("Base DoSomething");
        }
    }

    public class Derived: Base
    {
        public Derived()
        {
            Console.WriteLine("Derived Class Constructor");
            StrMyString= "Value In Derived";
        }
        public override void Example1()
        {
            Console.WriteLine("Derived function is called and Value of StrMyString is {0}", StrMyString);
        }
    }

    public class TestingClass
    {
        public static void Main()
        {
            Derived d = new Derived (); 
        }
    }
}

Output will be

Base Class Constructor
Derived DoSomething is called - initialized ? Value In Base

Derived Class Constructor


Because this is very contra-intuitive, it is best not to invoke virtual methods from a constructor altogether. Except when the class is sealed of course, because then there can be no derived class.

Extract Only Date from Date time field

The following SQL Script helps to Extract only Date from DateTime field, it will ignore the time and display as "00:00:00.000".


SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

Here I used the GetDate() function. In the Same way, we can use any datefield column.