Monday, 6 July 2015

oops q-1

What is Garbage Collector Gen 0,1,2 ?
What is IDisposable interface & finalize dispose pattern in GC ?
What is difference between String and String Builder?
What is anonymous methods in C#?
What is use of Lambda Expression Action<>, Predicate<> & Func<>?
What do you mean by Covariance & Contravariance in .NET4.0 ?
What is use of checked and unchecked keyword ?
What is optimistic and pessimistic locking?
What is Instrumentation, Debugging & Tracing ?
What is Routing in ASP.NET(URL rewriting)?
What are Genrics & What are generics collections?
What is difference between IEnumerable and IEnumerator?
What is use of VAR keyword in C#?
Can you explain Named Parameters , REF, Out, Volatile & Parsetry?
What is the difference between Const & ReadOnly?
What is the deifference between Debug and Release?
What is serialization and deserialization?
What is IComparable and IComparer?
What is the use of Yield Keyword in C#?
What is C# indexer?

Saturday, 4 July 2015

9 Key Concepts to Keyword 'Static'

http://www.c-sharpcorner.com/UploadFile/d2fdf5/9-key-concepts-to-keyword-static/


 key concept of the keyword static that is worth remembering.

1. Applicability 

A class can be static but a structure and interface cannot be. Similarly, constructors, fields, properties and methods can be static but destructors cannot be.

We can have static classes, fields, properties, constructors and methods.
  1. /// Static class  
  2. static class StaticClass  
  3. {  
  4.     //Some class members  
  5. }  
  6.   
  7. public class SomeClass  
  8. {  
  9.     //Static Field  
  10.     static int intstatic = 0;  
  11.   
  12.     //Static Property  
  13.     public static string StaticProperty { getset; }  
  14.   
  15.     //Static Constructor  
  16.     static SomeClass()  
  17.     { }  
  18.   
  19.     //Static Method  
  20.     public static void DoSomething()  
  21.     {  
  22.         Console.WriteLine(intstatic);  
  23.     }  
  24. }  
But we cannot have static interfaces, structures or destructors.
  1. /// Trying to declare static Interface  
  2. static interface IStaticInterface  
  3. {  
  4.     //some interface members  
  5. }  
  6.   
  7. /// Trying to declare static structure  
  8. static struct StaticStruct  
  9. {  
  10.     //some structure member  
  11. }  
  12.   
  13. /// Some Random class  
  14. class SomeClass1  
  15. {  
  16.     /// Trying to declare static Destructor  
  17.     static ~SomeClass1()  
  18.     { }  
  19. }  
If we try to create one, we will get the following compilation error:
    ” The modifier 'static' is not valid for this item”
Later, we will also explain why such implementation does make sense.  

2. Access Modifiers

A static constructor does not have access modifiers. Other static elements do.

We can have static classes, fields, properties and methods denoted with the access modifier. But if you do so with a static constructor as in the following:
  1. //Static class with Access Modifier  
  2. public class SomeClass  
  3. {  
  4.     //Static Field with Access Modifier  
  5.     public static int intstatic = 0;  
  6.   
  7.     //Static Property with Access Modifier  
  8.     public static string StaticProperty { getset; }  
  9.   
  10.     //Trying to declare static Constructor with Access Modifier  
  11.     public static SomeClass()  
  12.     { }  
  13.   
  14.     //Static Method with Access Modifier  
  15.     public static void DoSomething()  
  16.     {  
  17.         Console.WriteLine(intstatic);  
  18.     }  
  19. }  
It will result in the following compilation error.
    ”Access modifiers are not allowed on static constructors”
Also, if you notice, so far I have used word the constructor but not constructor(s). Why? We will see next.

3. Unique Static Constructor

A class can have only one static constructor and that too is parameterless.

If we use overloading, we can have multiple constructors, each having a different signature. If we try to mark them static as in the following:
  1. public class SomeClass  
  2. {  
  3.     /// Static Constructor without parameters  
  4.     static SomeClass()  
  5.     {  
  6.         //Do something  
  7.     }  
  8.   
  9.     /// Trying to declare Static Constructor with parameters  
  10.     static SomeClass(int input)  
  11.     {  
  12.         //Do something  
  13.     }  
  14. }  
We will get the compilation error:
    "A static constructor must be parameterless”
So, a class cannot have a static constructor with parameter(s) and hence it can have only one static constructor and that is parameterless.

4. Priority - Static vs Instance Constructor 

A static constructor executes well before an instance constructor and only executes once.

Let's create one simple program to prove this:
  1. public class SampleClass  
  2. {  
  3.     //Static Constructor  
  4.     static SampleClass()  
  5.     {  
  6.         Console.WriteLine("This is SampleClass Static Constructor.");  
  7.     }  
  8.   
  9.     //Instance Constructor  
  10.     public SampleClass()  
  11.     {  
  12.         Console.WriteLine("This is SampleClass Instance Constructor.");  
  13.     }  
  14. }  
  15.   
  16. class Program  
  17. {  
  18.     static void Main()  
  19.     {  
  20.         SampleClass objC1 = new SampleClass();  
  21.         SampleClass objC2 = new SampleClass();  
  22.         SampleClass objC3 = new SampleClass();  
  23.   
  24.         Console.ReadLine();  
  25.     }  
  26. }  
Output of this program is as follows:
program

As you can see, that static constructor was first to execute and only executes once. We will again revisit this point. Especially the words “well before”.

5. Accessibility

Instance members are accessed with a class object outside the class definition and "this" keyword inside the class definition whereas static members can be directly accessed with a class name outside and inside the definition.

This is an important point and it makes sense also since static members are independent of instance objects.
  1. public class SampleClass {  
  2.     public string instanceMsg = "This is instance Field.";  
  3.     public static string staticMsg = "This is static Field";  
  4.   
  5.     public SampleClass()  
  6.     {  
  7.         // Access within class definition  
  8.         Console.WriteLine("Within class instanceMsg:{0}",   
  9.                             this.instanceMsg);  
  10.         Console.WriteLine("Within class staticMsg:{0}",   
  11.                             SampleClass.staticMsg);  
  12.     }  
  13. }  
  14.   
  15. class Program  
  16. {  
  17.     static void Main()  
  18.     {  
  19.         SampleClass ObjS1 = new SampleClass();  
  20.   
  21.         // Access outside class definition  
  22.         Console.WriteLine("From Main Program instanceMsg: {0}",   
  23.                             ObjS1.instanceMsg);  
  24.         Console.WriteLine("From Main Program staticMsg: {0}",   
  25.                             SampleClass.staticMsg);  
  26.   
  27.         Console.ReadLine();  
  28.     }  
  29. }  
We will revisit this in future sections.

6. Compatibility – Static vs Instance members/container

An instance member cannot be created or accessed from a static container whereas static members can be created or accessed from an instance container.

Subheading is not clear! Don't worry. Let's understand this with some examples. 

In Scenario 1, we are trying to access the static field iInc within the instance method DoSomething().
  1. // This compiles successfully     
  2. public class InstanceContainerStaticMember  
  3. {  
  4.     static int iInc = 0;  
  5.       
  6.     // Instance Container Method  
  7.     public void DoSomething()  
  8.     {  
  9.         // Static Member  
  10.         iInc++;  
  11.         Console.WriteLine("iInc:{0}", iInc);  
  12.     }  
  13. }  
On the other hand, in Scenario 2, we tried to access an instance member iInc within the static methodDoSomething().
  1. // This will result in compilation Error  
  2. public class StaticContainerInstanceMember  
  3. {  
  4.     int iInc = 0;  
  5.   
  6.     /// Static Container Method  
  7.     public static void DoSomething()  
  8.     {  
  9.         //Instance Member  
  10.         iInc++;  
  11.         Console.WriteLine("iInc:{0}", iInc);  
  12.     }  
  13. }  
But when we compiled, Scenario 2 throws the following compilation error.
    “An object reference is required for the non-static field, method, or property”
So the compilation error is clear that we cannot access an instance member from a static container. Why? We will explore this with an example. Recall point 5. According to that, static members are referred to with a class name. So in the example below:
  1. public class SampleClass {  
  2.     private int _id;  
  3.   
  4.     public SampleClass(int ID)  
  5.     {  
  6.         _id = ID;  
  7.     }  
  8.   
  9.     public static void StaticMethod()  
  10.     {   
  11.         //I want to access _id but who will provide me  
  12.     }  
  13. }  
  14. class Program  
  15. {  
  16.     static void Main()  
  17.     {  
  18.         SampleClass s1 = new SampleClass(1);  
  19.         SampleClass s2 = new SampleClass(2);  
  20.         SampleClass s3 = new SampleClass(3);  
  21.   
  22.         //What will be the value for this s1, s2 or s3  
  23.         SampleClass.StaticMethod();  
  24.     }  
  25. }  
We have SampleClass that has a non-static field _id and static method StaticMethod() that wants to access _id. In the Main() program, there are the 3 objects s1, s2 and s3 created of the class SampleClass. And hence the value for _id will be 1, 2 and 3 for the objects s1s2 and s3 respectively. Now the program makes calls to the SampleClass.StaticMethod(). Since it is called with the class name, if the static method were allowed access to _id, which _id value should it return, s1s2 or s3? No, it cannot return any sinceStaticMethod() is independent of the class objects and hence independent of instance members and so the compiler shows the error. This holds true for static classes as well. A static class cannot have an instance member such as fields, properties, constructors or methods. Try it yourself!

7. Object creation and Instantiation

A static class object can neither be created nor instantiated.

Since a static class cannot have instance members, it cannot be instantiated. In the example below, we are trying to create an instance of the class SampleClass.
  1. public static class SampleClass {   
  2.     //static class members  
  3. }  
  4.   
  5. class Program  
  6. {  
  7.     static void Main()  
  8.     {  
  9.         //This statement will result compilation error.  
  10.         SampleClass s1 = new SampleClass();  
  11.     }  
  12. }  
We get the compilation error:
    Cannot declare a variable of static type 'SampleClass'
    Cannot create an instance of the static class ‘SampleClass'
Important
When building an application, you will encounter code blocks that are repetitively used in the application but don't belong to a specific code hierarchy. Usually developers refer to them as utility functions. They serve general utility purposes in the application. You certainly want to modularize such code. At the same time, you want to access these functions without any object creation. Static classes are great to organize these functions. In the Microsoft .NET Framework, one of the great examples of the utility class is the Mathclass. See the screenshot below:

Math class

8. Inheritance

A static class cannot be part of an inheritance. It cannot serve as a base class, child class or implement an interface.

Yes that's true. As always, let us see by the following examples.

Case 1: A static class cannot be a base class.
  1. public static class BaseClass   
  2. {   
  3.     //Class member goes here  
  4. }  
  5. public class DeriveClass : BaseClass  
  6. {   
  7.     //Class member goes here  
  8. }  
 “Cannot derive from static class 'BaseClass'”

Case 2:
 A static class cannot be a derived class.
  1. public class BaseClass  
  2. {  
  3.     //Class member goes here  
  4. }  
  5. public static class DeriveClass : BaseClass  
  6. {  
  7.     //Class member goes here  
  8. }  
Static class 'DeriveClass' cannot derive from type 'BaseClass'. Static classes must derive from object.”.

Case 3: A static class cannot implement interfaces.
  1. public interface IInterface  
  2. {  
  3.     //Interface member goes here  
  4. }  
  5. public static class DeriveClass : IInterface  
  6. {  
  7.     //Class member goes here  
  8. }  
“'DeriveClass': static classes cannot implement interfaces”

That's clear except for one question. As we have seen, a static class cannot be a part of an inheritance hierarchy, then what will happen to protected members in the static class? The answer is a static class cannot have protected members. If you try to declare one, it will throw:
  1. public class BaseClass  
  2. {  
  3.     public static virtual void StaticMethod()  
  4.     { }  
  5. }  
  6.   
  7. public class DerivedClass : BaseClass  
  8. {   
  9.     public override void StaticMethod()  
  10.     { }  
  11. }  
Compilation error.
 
Static classes cannot contain protected members

In fact, static members in non-static classes cannot be overridden. 
  1. public class BaseClass  
  2. {  
  3.     public static virtual void StaticMethod()  
  4.     { }  
  5. }  
  6.   
  7. public class DerivedClass : BaseClass  
  8. {   
  9.     public override void StaticMethod()  
  10.     { }  
  11. }  
Compilation error:
 
A static member cannot be marked as override, virtual, or abstract
 

 9. Lifetime

Static elements are in scope as soon as they are referred to in a program for the first time and will remain in scope throughout the life of the AppDomain.

This is an important concept to understand the scope of static elements but I will explain something more than that. Have a look at the example below. 
  1. public class SampleClass  
  2. {  
  3.     static int _iCount = 0;  
  4.   
  5.     static SampleClass()  
  6.     {  
  7.         Console.WriteLine("This is Static Ctor");  
  8.     }  
  9.   
  10.     public void SetValue(int Count)  
  11.     {  
  12.         _iCount = Count;  
  13.     }  
  14.   
  15.     public static void Print()  
  16.     {  
  17.         Console.WriteLine("The value of Count:{0}",  
  18.                             SampleClass._iCount);  
  19.     }  
  20. }  
In the class above, we have a static field _iCount and static method Print(). In the Main() program below, we are making a call to the functions function1() and function2(). In both of the functions, we are creating an object of the class SampleClass.
  1. class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         Console.WriteLine("First line in Main().");  
  6.         SampleClass.Print();  
  7.         function1();  
  8.         function2();  
  9.         SampleClass.Print();  
  10.         Console.WriteLine("Last line in Main().");  
  11.         Console.ReadLine();  
  12.     }  
  13.   
  14.     public static void function1()  
  15.     {  
  16.         Console.WriteLine("First line in function1().");  
  17.         SampleClass objS2 = new SampleClass();  
  18.         objS2.SetValue(1);  
  19.         Console.WriteLine("Last line in function1().");  
  20.     }  
  21.   
  22.     public static void function2()  
  23.     {  
  24.         Console.WriteLine("First line in function2().");  
  25.         SampleClass objS3 = new SampleClass();  
  26.         objS3.SetValue(2);  
  27.         Console.WriteLine("Last line in function2().");  
  28.     }  
  29. }  
And finally the following is the output of this program.

output of this program

A couple of interesting observations:
  • The second line of output is the call to the static constructor (see “This is static Ctor”). But if you refer to the Main() function, we are neither creating the object nor instantiating it. Even SampleClassis not declared as static. Yet, the program makes a static constructor call. Remember in Point 4, we discussed that a static constructor is called well before the instance constructor. The word “well before” is important since it suggests that as soon as static elements are accessed (with or without object creation), the constructor will initialize and then the static objects will be in scope but not as soon as the program begins executing. Because the first line in the output (in other words “First line in Main().”) is the Main() function Console.writeline() statement and then the constructor ofSampleClass is called. To conclude, static elements are in scope as soon as they are referred to by the program in any way.
  • Also, there are the objects ObjS2 and ObjS3 created in function1() and function2() respectively. Ideally their scope is within the respective function body only. But when we print the value of the_iCount in Main(), the printed value “2” is set by function2() (in other words objS3.SetValue(2)).
So the take-a-way from the last point is that a static element remains active until the last line of the program is executed. Our assumption is absolutely right with respect to this program. The reason being, the scope of our program is limited to one AppDomain. However if we introduce a different AppDomain, things will change. Let's see another example.

Assume we have one class library project.
  1. namespace RemoteClassLibrary  
  2. {  
  3.     public class RemoteClass  
  4.     {  
  5.         static int _myID = 0;  
  6.   
  7.         public RemoteClass()  
  8.         {  
  9.             Console.WriteLine("My ID is {0}", ++_myID);  
  10.         }  
  11.     }  
  12. }  
And we have saved the class library DLL to the local drive c:\app\. We have also created another program that uses reflection to execute this code.
  1. using System.Reflection;  
  2.   
  3. namespace TestingProgram  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main()  
  8.         {  
  9.             const string ClassLibraryPath = @"c:\app\RemoteClassLibrary.dll";  
  10.   
  11.             //Load assembly in current App Domain  
  12.             Assembly Assembly1 = Assembly.LoadFrom(ClassLibraryPath);  
  13.             Assembly1.CreateInstance("RemoteClassLibrary.RemoteClass");  
  14.   
  15.             //Load assembly in current App Domain  
  16.             Assembly Assembly2 = Assembly.LoadFrom(ClassLibraryPath);  
  17.             Assembly2.CreateInstance("RemoteClassLibrary.RemoteClass");  
  18.   
  19.             Console.ReadKey();  
  20.         }  
  21.     }  
  22. }  
And the obvious output of this program is:

obvious output

Please note that even though that assembly is loaded, static members still persist the value, or you can say only a single copy of the static class is created.

Now let's modify the main program to introduce multiple AppDomains that will load this assembly separately.
  1. class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         const string ClassLibrary = "RemoteClassLibrary.RemoteClass";  
  6.         const string ClassLibraryPath = @"c:\app\RemoteClassLibrary.dll";  
  7.   
  8.         //Load class Library in AppDomain1  
  9.         AppDomain AppDomain1 = AppDomain.CreateDomain("AppDomain1");  
  10.         AppDomain1.CreateInstanceFrom(ClassLibraryPath, ClassLibrary);  
  11.   
  12.         //Load class Library in AppDomain2  
  13.         AppDomain AppDomain2 = AppDomain.CreateDomain("AppDomain2");  
  14.         AppDomain2.CreateInstanceFrom(ClassLibraryPath, ClassLibrary);  
  15.   
  16.         Console.ReadKey();  
  17.     }  
  18. }  
Surprisingly the output:

output

And so even though a single program is executing, the different AppDomain is causing the program to maintain 2 copies of the static member per AppDomain. In short, their scope is limited to the AppDomain.

On final note, we explained that the static elements are in scope as soon as they are accessed first and limited to a specific AppDomain.