Great way to earn money!

Zone1

Showing posts with label CSHARP. Show all posts
Showing posts with label CSHARP. Show all posts

Wednesday, February 29, 2012

Some CSHARP Questions Part 4



Abstract Class vs Interface


A class can implement any number of interfaces but a subclass can at most inherit from only one abstract class.
 
An abstract class can have non-abstract Methods(concrete methods) while in case of Interface all the methods has to be abstract.
 
An abstract class can declare or use any variables while an interface is not allowed to do so.


following Code will not compile
interface TestInterface
{
    int x = 4;  // Filed Declaration in Interface
    void getMethod();
 
    string getName();
}
An abstract class can have constructor declaration while an interface can not do so.

An abstract Class is allowed to have all access modifiers for all of its member declaration while in interface  we can not declare any access modifier(including public) as all the members of interface are implicitly public. 
Although it is perfectly legal to make interface access specifier as  Public (Remember only public is allowed)




Below code is correct :
public interface TestInterface
{
    void getMethod();
    string getName();
}

Below code is wrong:
interface TestInterface
{
    public void getMethod();
    string getName();
}




Tuesday, February 28, 2012

Some CSHARP Questions Part 3

Differentiate Finalize(), Dispose() and Destructors
Dispose() is called by as an indication for an object to release any unmanaged resources it has held.

Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.

Dispose() operates determinalistically due to which it is generally preferred.


In C#, a destructor and a finalizer refer to the same thing, the function called before the object is fully-removed from the memory (i.e. GC-collected)   and it applies to c sharp only.





class BaseClass {     public ~BaseClass()     {         Console.WriteLine("dtor of BaseClass");     } } class DerivedClass : BaseClass {     public ~DerivedClass()     {         Console.WriteLine("dtor of DerivedClass");     } } class ChildClass : DerivedClass {     public ~ChildClass()     {         Console.WriteLine("dtor of ChildClass");     } }



When you define a class destructor with that C++-alike syntax (preceding the function name with a ~) the compiler actually replaces your destructor with an override of the virtual Object.Finalize() function. 



That is, before the object is removed (i.e. GC-collected) from the memory, the finalizer (i.e. destructor) is called first. 



This finalizer first executes your code. After that it calls the finalizer of the base type of your object. If we could decompile your assembly, would see that our destructor in the ChildClass (so other classes) has been replaced with this function:
protected virtual void Finalize()

{

    try

    {

        Console.WriteLine("dtor of ChildClass");

    }

    finally

    {

        base.Finalize();

    }
}
Finalizers are a feature of GC managed objects (i.e. managed classes). 


That's because the finalizer is called only when the GC removes the object from the memory (i.e. frees memory associated with).

You can't determine when finalizers would be called


That's because you don't know when the next garbage collection would occur, even if you performed a manual garbage collection (using System.GC.Collect() function) you won't know exactly when memory would be released.










Difference between System.String and StringBuilder


Every time we manipulate a string object we get a new string object created.


String is immutable means that once it has been created, a string cannot be changed.

No characters can be added or removed from it, nor can its length be changed.
The String object is immutable while StringBuilder object is mutable.

Both String and StringBuilder are reference type. But String acts like a value type.

StringBuilder is located in the System.Text namespace.
The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object.

Using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Below is a small program:

        private void Example_StringBuilder()

        {
            StringBuilder String1 = new StringBuilder("beautiful");

            StringBuilder String2 = new StringBuilder();

            String2 = String1.Append(" Picture");

            // value of String2="beautiful Picture"

            String2 = String1.Remove(2, 4);

            // value of String2="beful Picture"

            String2 = String1.Insert(2, "auti");

            // value of String2="beautiful Picture"

            String2 = String1.Replace("beautiful", "Wonderful");

            // value of String2="Wonderful Picture"

          }



StringBuilder object contains a buffer, typically initialized with a string but usually larger than that string. 
This buffer can be manipulated in place without creating a new string: You can insert, append, remove, and replace characters. 
When you're done manipulating the characters, use StringBuilder's ToString method to extract the finished string from it. 



Both String and StringBuilder contain Unicode characters of type Char and support an indexer that returns Char. 


Because the String class is immutable, its indexer is read-only, but the StringBuilder indexer is readable/writeable. 


If you modify the string frequently-in operations like reassigning, appending, removing, and replacing some characters-you should choose the StringBuilder class. 


Whenever you modify a string in the String class, the methods of the String class returns a new string as the result. Creating many String objects might degrade the performance of your program. You can avoid creating a new instance of a string by using the StringBuilder class. 



Some CSHARP Questions Part 2

Explain the difference between a class and a structure

Class:

a. It is reference type.
 
b. Null value can be assigned to a variable in a class
 
c. It can have destructor.
 
d. All variables in classes are by default private.
 
e. Good to be used from architecture view as it provides high flexibility.

Structure:

a. It is value type.
 
b. Null value assignment is not feasible here.
 
c. Cannot have destructor.
 
d. All variables in structures are public.
 
e. Good to be used for simple data structures.




What are virtual, sealed, override, new, and abstract keywords.

The virtual keyword enables a class to be overridden.

If it has to be prevented from being overridden, then the sealed keyword needs to be used.

The override keyword is used to override the virtual method in the base class.

Abstract keyword is used to modify a class, method or property declaration.

You cannot instantiate an abstract class or make calls to an abstract method directly.

An abstract virtual method means that the definition of the method needs to be given in the derived class.


Lets have some examples :

  1. By using virtual and override keywords we can accomplish Method overriding.
  2. The virtual modifier indicates to derived classes that they can override this method.
  3. The override modifier allows a method to override the virtual method of its base class at run-time.
To achieve Run-time polymorphism or Late Binding, we are using Method Overriding concept.

using System;

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

namespace ConsoleApplication3
{
    class baseclass
    {
        public virtual int Add(int a, int b)
        {
            return a + b;
        }
    }
    class subclass : baseclass
    {
        public override int Add(int x, int y)
        {
            int d = 20;
            return base.Add(x,y)+d;
        }
    }
    class subclass2 : baseclass
    {
        public int Add(int x, int y)
        {
            int d = 40;
            return base.Add(x, y) + d;
        }
    }
    class something
    {
        public static void Main(String[] args)

        {
            baseclass baseclsinst = new baseclass();
            Console.WriteLine("Base class Addition::::::::::::" + baseclsinst.Add(23, 23));
            baseclass bscls = new subclass();
            Console.WriteLine("Derived class addition:::::::::" + bscls.Add(34, 54));
            baseclass bscls2 = new subclass2();
            Console.WriteLine("Derived class addition:::::::::" + bscls2.Add(34, 54));
            Console.ReadLine();
        }
    }
}


 
Sealed class is used to define the inheritance level of a class.
 
The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. 

.  A class, which restricts inheritance for security reason is declared, sealed class.
2.  Sealed class is the last class in the hierarchy.
3.  Sealed class can be a derived class but can't be a base class.
4.  A sealed class cannot also be an abstract class. Because abstract class has to provide functionality and here we are restricting it to inherit.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace sealed_class
{
    class Program
    {
        public sealed class BaseClass
        {
            public void Display()
        {
            Console.WriteLine("This is a sealed class which can;t be further inherited");
        }
    }
 
        public class Derived : BaseClass
        {
            // this Derived class can;t inherit BaseClass because it is sealed
        }
   
        static void Main(string[] args)
        {
            BaseClass obj = new BaseClass();
 
            obj.Display();
 
            Console.ReadLine();
        }
    }
}


Sealed method is used to define the overriding level of a virtual method.
 
Sealed keyword is always used with override keyword

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace sealed_method
{
    class Program
    {
        public class BaseClass
        {
           
            public virtual void Display()
            {
                Console.WriteLine("Virtual method");
            }
        }
 
       public class DerivedClass : BaseClass
        {
            // Now the display method have been sealed and can;t be overridden
            public override sealed void Display()
            {
                Console.WriteLine("Sealed method");
            }
        }
 
       //public class ThirdClass : DerivedClass
       //{
 
       //    public override void Display()
       //    {
       //        Console.WriteLine("Here we try again to override display method which is not possible and will give error");
       //    }
       //}
 
        static void Main(string[] args)
        {
 
            DerivedClass ob1 = new DerivedClass();
            ob1.Display();
 
            Console.ReadLine();
        }
    }
}


'abstract' modifier before a class indicates that the class is incomplete and intended to be used only as base class and must be implemented in derived class 

 it cannot be instantiated 

it may contain abstract methods

'Abstract' modifier before a method indicates that the method (or property) does not have implementation

it's implicitly a virtual method

The implementation is provided in the overriding method




Difference between Abstract Method & Virtual Method

A virtual method must have its implementation in the base class and may optionally be overriden in the derived class if some additional functionality is required WHEREAS, Abstract Method has no implementation in the base class; it is implemented by the overriding method in the derived class.

In other words, Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method. 




Now lets come to overriding and new:



A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses
    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }
        class B : A {}         class Test
        {
            static void Main(string[] args)
            {
                A a = new A();
                a.Foo();  // output --> "A::Foo()"
                B b = new B();
                b.Foo();  // output --> "A::Foo()"
            }
        }
    }
The method Foo() can be overridden in classes B and C:
    using System;
    namespace Polymorphism
    {
        class A
        {
              public void Foo() { Console.WriteLine("A::Foo()"); }
        }
        class B : A
        {
              public void Foo() { Console.WriteLine("B::Foo()"); }
        }
        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;
                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"
                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }
The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual.  

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
    using System;
    namespace Polymorphism
    {
        class A
        {
            public virtual void Foo() { Console.WriteLine("A::Foo()"); }
        }
        class B : A
        {
            public override void Foo() { Console.WriteLine("B::Foo()"); }
        }
        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;
                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"
                a = new B();
                a.Foo();  // output --> "B::Foo()"
            }
        }
     }

C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:
    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }
        class B : A
        {
            public new void Foo() { Console.WriteLine("B::Foo()"); }
        }
        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;
                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"
                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }
Combining Method Overriding and Hiding

Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
            class A
            {
                public void Foo() {}
            }
            class B : A
            {
                public virtual new void Foo() {}
            }
     
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
            class C : B
            {
                public override void Foo() {}
                // or
                public new void Foo() {}
            }
Only methods in base classes need not override or hide derived methods. All methods in derived classes require to be either defined as new or as override.










Some CSHARP Questions Part 1





What is the difference between const and readonly


When using the const keyword to set a constant variable, the value needs to be set at compile time.

The const keyword may not be used with an object of reference type. 
All the constant variables are static ie they are shared across all the instances of the class. You dont have to add the keyword "static".

In case a reference type needs to be assigned a non-changeable value, it may be set as readonly

Readonly fields are delayed initalized constants. 

When we declare a field as const it is treated as a static field. where as the Readonly fields
are treated as normal class variables.

if we want a field that can have different values between different objects of same class, however
the value of the field should not change for the life span of object; We should choose the Read
Only fields rather than constants.Since the constants have the same value across all the
objects of the same class; they are treated as static.


What are value types and reference types


When you declare a variable in a .Net application, it allocates some chunk of memory into the RAM. 

This memory has 3 things first the name of the variable, second data type of the variable and finally the value of the variable.

Depending on what kind of data type your variable is, the memory is allocated to it. 

There are two types of memory allocation stack memory and heap memory. 

Value types are types which hold both data and the memory on the same location. 

While a reference type has a pointer which points to the memory location.

Below is a simple integer data type with name 'i' whose value is assigned to an other integer data type with name 'j'.

Both these memory values are allocated on the stack.

When we assign the 'int' value to the other 'int' value it creates a complete different copy. In other word if you change either of them the other does not change. These kinds of data types are called as 'Value types'.

public void method()
{
    int i = 9;
    int j=i;
}

When we create an object and when we assign one object to the other object, they both point to the same memory location as show in the below code snippet. 

So when we assign 'obj' to 'obj1' they both point to the same memory location.

In other words if we change one of them the other object is also affected this is termed as 'Reference types'.


public void method()
{
     Class1 obj = new Class1();
     Class1 obj1 = obj;
}
 In .NET depending on data types the variable is either assigned on the stack or on the heap. 
'String' and 'Objects' are reference types and any other .NET primitive data types are assigned on the stack. 







What is boxing and unboxing

Boxing is used to store value types in the garbage-collected heap. 

Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. 

Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Consider the following declaration of a value-type variable:

 int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

// Boxing copies the value of i into object o.
object o = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable.


Consider follwing C# code:

class TestBoxing
{
    static void Main()
    {
        int i = 123;

        // Boxing copies the value of i into object o.
        object o = i; 

        // Change the value of i.
        i = 456; 

        // The change in i does not effect the value stored in o.
        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);
    }
}
/* Output:
    The value-type value = 456
    The object-type value = 123
*/

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface.

An unboxing operation consists of:
Checking the object instance to make sure that it is a boxed value of the given value type.

Copying the value from the instance into the value-type variable.

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing