Tuesday, August 12, 2014

Static Class

  1. Cannot derive from Static Class
  2. Cannot create instance of Static class using new keyword
  3. Static class can be public or internal
  4. Static class can NOT be private or protected or protected internal
  5. Static class can NOT have non-static members

1) 
static class ThisClassIsStatic
{
    static string comment;
    static int count = 0;
}
class ThisIsDervied : ThisClassIsStatic   //NOT POSSIBLE
{
}

2)
ThisClassIsStatic obj = new ThisClassIsStatic(); //NOT POSSIBLE

3) 
public static class ThisClassIsStatic  //POSSIBLE
{
}

4)
private static class ThisClassIsStatic  //NOT POSSIBLE

5)
    static class ThisClassIsStatic
    {
        static string comment;
        static int count = 0;
        int index = 0; //NOT POSSIBLE

    }

C# Base

    class Program
    {
        static void Main(string[] args)
        {
            B b = new B();
            Console.Read();
        }
    }

    class A
    {
        internal int x = 10;
        public int MyProperty { get; set; }
        public A()
        {          
            Console.WriteLine("A Constructor");
        }
    }

    class B:A
    {
        public B(): base()
        {                
            Console.WriteLine("B Constructor ");
        }
    }

What's the output of the above program?

Note: base keyword can be used ONLY from derived class's constructor to access base class members (non-private members)

Saturday, August 9, 2014

C# Extension Method - Sample

class Program
{
    static void Main(string[] args)
    {
        string s = "hello please tell me the word count";
        Console.Write(s.WordCount());
        Console.Read();
    }
}

public static class StringExtension
{
    public static int WordCount(this string value)
    {
        return value.Split(' ').Length;
    }
}