Sunday, September 18, 2011

Static constructor

Que: Where static members are allocated?
Ans: Data Segment.
Here is memory model which shows static member's location in memory -

Que: Is it possible to make constructor private?
Ans: yes. It is useful if we know that a class has only static member in it.Or when we want to control object creation with its constructor(Ex. Singleton pattern)

Que: Is it possible to have constructor static?
Ans: Yes. Here is the signature:
class A
{
public static int a;
    static A()
    {
       a = 5;
    }
}
It doesn't have any access modifier in it. It is class level.

Que: What is the use of static constructor?
Ans: It is used to initialize static variables in the class or to perform some action which needs to be performed only once.

Que: When is static constructor called?
Ans:  It is called when we try to create an object of class or when we try to access the static variable in class(whichever comes first.).

Que: What if the static constructor throws some exception?
Ans: If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Override and overload


Que: What is overriding?
Ans: Redefine a method in derived class that is in base class, i.e. same method name in base and derived class with different implementation.

Que: What is difference between override and new keyword?
Ans:  New -> Method is not overridden, it is different in derived.It means if a reference of base type which is pointing at derived type will execute a method of base class, althod same signature is available in derived class.
override-> Indicates that this method is overridden. If a reference of base type is pointing at derived class then method of derived class should get execute.

Que: What is the use of virtual keyword?
Ans: Virtual keyword is to show that this method can be overridden. A method which is not virtual can not be overridden.

Exercise: Find the output of the program.
1)  r1=?,r2=?
public class A
        {
            public A(){}                                   
            public string myMethod()
            {
                return "A";
            }
        }
        public class B:A
        {
            public B():base(){}                                   
            public string myMethod()
            {
                return "B";
            }
        }

static void Main(string[] args)
        {       
            B b1 = new B();
            A a1 = new B();
            string r1 = b1.myMethod();
            string r2 = a1.myMethod();
        }
Ans: r1 = "B"; r2="A"

2) r1=?,r2=?
public class A
        {
            public A(){}                                   
            public virtual string myMethod()
            {
                return "A";
            }
        }
        public class B:A
        {
            public B():base(){}                                   
            public string myMethod()
            {
                return "B";
            }
        }

static void Main(string[] args)
        {       
            B b1 = new B();
            A a1 = new B();
            string r1 = b1.myMethod();
            string r2 = a1.myMethod();
        }


Ans: r1 = "B"; r2="A"

3)r1=?,r2=?
public class A
        {
            public A(){}                                   
            public virtual string myMethod()
            {
                return "A";
            }
        }
        public class B:A
        {
            public B():base(){}                                   
            public override string myMethod()
            {
                return "B";
            }
        }

static void Main(string[] args)
        {       
            B b1 = new B();
            A a1 = new B();
            string r1 = b1.myMethod();
            string r2 = a1.myMethod();
        }
Ans: r1 = "B"; r2="B"

4)r1=?,r2=?
public class A
        {
            public A(){}                                   
            public string myMethod()
            {
                return "A";
            }
        }
        public class B:A
        {
            public B():base(){}                                   
            public override string myMethod()
            {
                return "B";
            }
        }
static void Main(string[] args)
        {       
            B b1 = new B();
            A a1 = new B();
            string r1 = b1.myMethod();
            string r2 = a1.myMethod();
        }

Ans: compile error, cannot override inherited member because it is not marked virtual, abstract, or override.

5) r1,r2,r3,r4?
public class A
        {
            public A(){}
            public string method1()
            {
                return "A->method1";
            }           
        }

        public class B:A
        {
            public B():base(){}          
            public string method2()
            {
                return "B->method2";
            }
        }

static void Main(string[] args)
        {
            A a1 = new A();
            B b1 = new B();
            A ab1 = new B();           
            string r1 = a1.method1();
            string r2 = b1.method1();
            string r3 = ab1.method1();
            string r4 = b1.method2();
            // string r5 = ab1.method2(); -- method2 will not be found in ab1.
        }

Ans: r1= "A->method1" ; r2= "A->method1" ; r3= "A->method1" ; r4= "B->method1"

6)what is the output?
public class A
        {
            public A(){}
            public void method1()
            {
                Console.WriteLine("A->method1");
            }    
        public void method2()
            {
                Console.WriteLine("A->method2");
            }     
        }

        public class B:A
        {
            public B():base(){}         
            public void method2()
            {
                Console.WriteLine("B->method2");
            }
        }

static void Main(string[] args)
        {
            A a1 = new A();
            B b1 = new B();
            A ab1 = new B();          
            a1.method1();
            b1.method1();
            ab1.method1();
            b1.method2();
            ab1.method2();
        }
Ans:
A->method1
A->method1
A->method1
B->method2
A->method2

7)what is the output?
public class A
        {
            public A(){}
            public void method1()
            {
                Console.WriteLine("A->method1");
            }   
        public void method2()
            {
                Console.WriteLine("A->method2");
            }    
        }
        public class B:A
        {
            public B():base(){}        
            public void method2()
            {
                Console.WriteLine("B->method2");
            }
        }

static void Main(string[] args)
        {
            A a1 = new A();
            B b1 = new B();
            A ab1 = new B();         
            a1.method1();
            a2.method2();
            b1.method1();
            b1.method2();
            ab1.method1();          
            ab1.method2();
        }
Ans:
A->method1
A->method2
A->method1
B->method2
A->method1
A->method2

8) Find the output-
    class A { };   
    class B : A { };   
    class C
    {
        public virtual void Collide(A a)
        {
            Console.WriteLine("C -> A");
        }
        public virtual void Collide(B b)
        {
            Console.WriteLine("C -> B");
        }
    }
    class D : C
    {
        public override void Collide(A a)
        {
            Console.WriteLine("D -> A");
        }
        public override void Collide(B b)
        {
            Console.WriteLine("D -> B");
        }
    }
static void Main(string[] args)
        {
            C c = new C();
            A a = new A();
           
            B b = new B();

            c.Collide(a);
            c.Collide(b);

            D d = new D();
            d.Collide(a);
            d.Collide(b);

            C cd = new D();
            cd.Collide(a);
            cd.Collide(b);

            A ab = new B();
            c.Collide(ab);
            cd.Collide(ab);
        }
Ans -
C -> A
C -> B
 D -> A
 D -> B
 D -> A
 D -> B
 C -> A
 D -> A

Sunday, September 11, 2011

Thread Synchronization

Que: What are different mechanism provided by c# for thread synchronization?
Ans: 
Monitor:
Static class available in System.Threading namespace
Method available: Enter/Try Enter, Wait, Pulse/PulseAll,Exit
Code between Monitor.Enter and Monitor.Exit is considered in synch block.
It has some disadvantages like the code can end up in deadlock also if we don't use Enter and Exit method cleverly. That is why we prefer to use lock statement instead.

ReadWriterLock:
Available in System.Threading namespace.
It is generally used to secure shared resources for writing and reading. Main disadvantage of this is Reading thread is given preference over writing. Thus sometimes there is performance hit on writing method.

WaitHandle:
Available in System.Threading namespace.It is Abstract class.
Mutex,Semaphore and EventWaitHandle(AutoResetEvent and ManualResetEvent) are classes that are derived from this abstract class. Semaphore is available in System.dll and others are in MSCoreLib.Dll.

AutoResetEvent Class:
This class notifies one or more waiting threads that an event has occurred. It automatically changes the status to signaled when a waiting thread is released.This class cannot be inherited.

ManualResetEvent Class
This class also notifies one or more waiting threads that an event has occurred. The state of the event can be manually set or reset. The state of a manually reset event remains signaled until the ManualResetEvent.Reset method sets it to the nonsignaled state and the state remains nonsignaled until the ManualResetEvent.Set method changes the state back to signaled. This class cannot be inherited.

Interlocked Class
This class (in the System.Threading namespace) helps to synchronize access to variables that are shared amongst threads. It thus provides atomic operations for variables that are shared by multiple threads. You can increment or decrement a shared variable by calling Interlocked.Increment or Interlocked.Decrement on the shared variable.

Que: What is the advantage of Waithandle class over Monitor/ReadWriteLock?
Ans: Monitor and ReadWriteLock methods allow synchronization of thread in a single appdomain, whereas being a Kernel level Waithandle does allow to have thread synch in different Appdomain and different process also.

Que: Effect of passing value type in monitor:
Ans: Unboxed value type instance do not have a sync block index member therefore, they can not be used for synchronization. That is why when we pass Value type instance in Monitor.Enter c# compiler will generate code to box the instance.And if we pass the same value in Monitor.Exit,it gets boxed again. Our code endup locking one object and unlocking another. and we dont get any thread safety. In case of lock statement compiler will generate error saying valuetype not a reference type as required by lock statement.

Que: How to apply lock in static class?
Ans: We can use lock(typeOf(Class_Name)).

Que: What is difference between Mutex and Semaphore?
Ans: In Mutex we can have only one thread accessing the object whereas with Semaphore we can have more than one thread(upto certain max limit) accessing the object simultaneously.

Saturday, September 10, 2011

Garbage Collection

Que: What is Garbage collection?
Ans: Method of de-allocating and acquiring object unused objects.

Que: Is it possible to force Garbage collection?
Ans: Different people have different view on this, but there is method available GC.Collect(), which can help us to request Garbage collector to be invoked.

Que: What is the meaning of Generation?
Ans: Generation is term used by GC to identify how new an object is. object in generation 0 are newly created. Objects that survive the garbage collection once are in Generation 1 and objects that survive the garbage collection 2 or more are in generation 2.

Que: Explain the process of generational garbage collection.
Ans: Generational garbage collection makes following assumptions:
a) The newer an object is, the shorter is lifetime will be.
b) The older an object is, the longer its lifetime will be.
c)Collecting a portion of heap is faster than collecting the whole heap.
When CLR initializes, it selects a budget size for generation 0(say 256). Once this budget get full, it start garbage collection. Those object that survive are considered in generation 1(which also have some specific limit of memory). Once generation 1 budget get full CLR again call GC and collect the object in generation 1 and those which survived are considered in generation 2. CLR doesn't have more than generation 2. Objects which survived in generation 2 are still considered in generation 2 only. For optimization purpose CLR dynamically can change the budget of different generation.

Que:Explain the behavior of following program.
public static void main(){
Timer t = new Timer(TimerCallBack, null , 0 , 2000);
Console.ReadLine();
}
private static void TimerCallBack(object o)
{
    GC.Collect();
}
Ans: Ideally timer should be called every 2 sec, but as in call back GC.Collect is there thus through GC timer object will be collected as GC will see it is no longer used in main.

Que: What is drawback of finalization method?
Ans: IF we are using finalize method in our class then while creating an object of this class a separate pointer to this object is allocated(other than heap memory) on finalization list (a separate datastructure controlled by GC) and when this object is no longer in used GC will move this pointer from finalization to freachable queue. Next time when GC runs it will collect this memory. Hence we can understand it is taking more time to release memory.

Que: What is difference between Dispose and finalize?
Ans: Dispose method is used to clean up unmanaged resources and can be controlled by program while Finalize does the same thing but done by GC. We recommend to use IDispose interface and implemet Dispose method instead of using finalize method if we are using unmanaged resources.

Que: What is the meaning of resurrection?
Ans:In finalization object required and is dead, then GC forces the object back in life so that its finalize method can be called(freachable queue). After this finalize method is called and object is permanently dead. Act of preparing to call an object's finalize method is a form of resurrection.

.Net Fundamentals 20(Test 2)

1) A local variable:
A. Can be used anywhere in the program
B. Is declared within a method
C. Must accept a class
D. Represents a class object

Ans: B

2) An instance variable:
A. Is an object of class
B. Represents an attribute of an object
C. is a method of a class
D. A and C

Ans: B

3) An instance method
A. Represents the behavior of an object
B. Represents the attribute of an object
C. Represents another class
D. A and B

Ans: A

4) A constructor
A. Is used to create objects
B. must have the same name as the class it is declared with
C. May be overloaded
D. All of the above

Ans: D

5) class Test: Form()
A. Creates the class Test:Form
B. Creates the class Test that inherits the class Form
C. Creates the class form that inherits the class Test
D. A and B

Ans: B

6) Defining two method with the same name but with different parameters is called:
A. Loading
B. Overloading
C. Multiplexing
D. Duplexing

Ans: B

7) In order for a class to use an interface it must:
A. inherit the properties of the interface
B. Contain the same method as the interface
C. Create an interface objects
D. All of the above

Ans: All of the above

8) Every class directly or indirectly extends the ...... class
A. System
B. Object
C. Drawing
D. Console

Ans: B

9) The concept of composition specifies that you can
A. Compose good code with c#
B. Compose C# projects with different objects
C. Reduce errors by remaining composed during programming
D. All of the above

Ans: B
--
Def: Object composition is a way to combine simple objects or data types into more complex ones
--

10) Polymorphism occurs when the methods of child class
A. Override the parent class methods but maintain the implementation
B. Maintain the same return type and arguments as the parent class but implement it differently
C. Have different return types and arguments than the parent class
D. Are virtual

Ans: B

11) To output the value of multidimensional array, console.Writeline(...)
A. myArray[1][3]
B. myArray[1,3]
C. myArray(1)(3)
D. myArray(1),(3)

Ans: A

12) All methods in an abstract class must be declared abstract
A. True
B. False

Ans: B

13) Methods that are declared abstract in the base class must show implementation at the time of declaration.
A. True
B. False

Ans: B

14) The code public class B: A{}
A. Defines a class that inherits all the methods of A
B. Defines a class that inherits the public and protected methods of A only
C. Error
D. A and B

Ans: B

15) Assuming that public class B:A{public B(int i):base(i){}} compiles and runs correctly, what can we conclude about the constructor in the class A?
A. One constructor takes an argument of type i
B. There is only a default constructor
C. One constructor takes an arguments of the type int
D. A and B

16) Classes declared with the sealed keyword cannot be base class
A. True
B. False

Ans: A

17) An abstract class
A. May contains instance variables
B. May contain constructor
C. May extend another class
D. All of the above

Ans: D

18) Class String and the char structure found in the:
A. System.String namespace
B. System.Text namespace
C. System.Chars namespace
D. System namespace

Ans: D

19) The proper way to convert a string to all lowercase is:
A. String = string.ToLower(string)
B. ToLower(string)
C. string.ToLower()
D. string.ToLower(string)

Ans: C

20) If an indexof Any methods is passed an array of characters it:
A. Finds the first occurrence of each letter in the string
B. Searches for the first occurrence of any of the characters in the string
C. will search for the first occurrence of the sequence of characters
D. generates an error

Ans: B