Saturday, March 29, 2014

C# OOPs Concepts



Encapsulation: Encapsulation is a process of binding the data members and member functions into a single unit.

Example for encapsulation is class. A class can contain data structures and methods.
Consider the following class

public class Aperture
{
public Aperture ()
{
}
protected double height;
protected double width;
protected double thickness;
public double get volume()
{
Double volume=height * width * thickness;
if (volume<0 span="">
return 0;
return volume;
}
}

In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier

Abstraction: Abstraction is a process of hiding the implementation details and displaying the essential features.

Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works.  You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.

So here the Laptop is an object that is designed to hide its complexity.
How to abstract: - By using Access Specifiers

.Net has five access Specifiers

Public - Accessible outside the class through object reference.
Private - Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member 
functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.

In object-oriented software, complexity is managed by using abstraction.

Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details.

Inheritance:Inheritance is a process of deriving the new class from already existing class
C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. A simple example to understand inheritance in C#.


Using System;
Public class BaseClass
{
    Public BaseClass ()
    {
        Console.WriteLine ("Base Class Constructor executed");
    }
                                 
    Public void Write ()
    {
        Console.WriteLine ("Write method in Base Class executed");
    }
}
                                 
Public class ChildClass: BaseClass
{
                                 
    Public ChildClass ()
    {
        Console.WriteLine("Child Class Constructor executed");
    }
   
    Public static void Main ()
    {
        ChildClass CC = new ChildClass ();
        CC.Write ();
    }
}

In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.

The output of the above program is

Output:
  Base Class Constructor executed
  Child Class Constructor executed
  Write method in Base Class executed

this output proves that when we create an instance of a child class, the base class constructor will automatically be called before the child class constructor. So in general Base classes are automatically instantiated before derived classes.

In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name.

Syntax:  class ChildClassName: BaseClass
              {
                   //Body
              }

C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B at the same time. This is not allowed in C#. This will lead to a compile time 
error: Class 'C' cannot have multiple base classes: 'A' and 'B'.

public class A
{
}
public class B
{
}
public class C : A, B
{
}

In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have access to all members present in both Class A and Class B. As a result of multi-level inheritance Class has access to A_Method(),B_Method() and C_Method().

Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces.

Using System;
Public class A
{
    Public void A_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
}
Public class B: A
{
    Public void B_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
}
Public class C: B
{
    Public void C_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
                   
    Public static void Main ()
    {
        C C1 = new C ();
        C1.A_Method ();
        C1.B_Method ();
        C1.C_Method ();
    }
}
When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. In the code snippet below class B will inherit both M1 and M2 from Class A, but you cannot access M2 because of the private access modifier. Class members declared with a private access modifier can be accessed only with in the class.

Common Interview Question: Are private class members inherited to the derived class?
Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error.

Using System;
Public class A
{
Public void M1 ()
{
}
Private void M2 ()
{
}
}

Public class B: A
{
Public static void Main ()
{
B B1 = new B ();
B1.M1 ();
//Error, Cannot access private member M2
//B1.M2 ();
}
}

What is wrong with multiple inheritance?

The main problem with multiple inheritance is that there can be times when the results of using multiple inheritance will be uncertain. The best example of this is the classic problem known as the diamond problem where a class inherits from 2 different classes, but those 2 different classes inherit from the same class, like in the graphic below (where class D derives from both classes B and C, and classes B and C both derive from class A:

And here is what the code for that example would look like:
class A {
           protected: 
               bool testing;
};
 
class B: public A { };
 
class C: public A { };
 
class D: public B, public C  {
  public:
    void setTesting ( bool xTesting)  {
            testing = xTesting; // this is uncertain
           }
};
 
In the code above we have the testing data member which is defined by class A. But, the problem is that class D derives from both classes B and C, which both derive from class A. This means that there are essentially 2 copies of the testing flag that are available because there are 2 instances of A in D’s class hierarchy. So, this creates a problem because which copy of the testing flag will be set? And the compiler will give an error and say that the reference to testing in class D is ambiguous.
But, there are some fixes to this problem. One fix is to make it very clear which classe’s version of testing is going to be set:
B :: testing = xTesting;  // use B's version of testing
The other fix for this problem is to declare B and C as virtual base classes. This allows only one copy of A to be created for class D, and that clears up any ambiguities.
Different languages actually have different expectations for how multiple inheritance works. For example, how conflicts are resolved and whether duplicate bases are merged or redundant. Before microsoft can implement multiple inheritance  in the CLR, microsoft have to do a survey of all the languages, figure out the common concepts, and decide how to express them in a language-neutral manner. microsoft could also have to decide whether multiple inheritance belongs in the CLS and what this would mean for languages that don't want this concept (presumably VB.NET, for example).
Polymorphism: Polymorphism means many forms (ability to take more than one form).
In polymorphism we will declare methods with same name and different parameters in same class or methods with same name and same parameters in different classes. Polymorphism has ability to provide different implementation of methods that are implemented with same name.

In Polymorphism we have 2 different types those are
     -      Compile Time Polymorphism (Called as Early Binding or Overloading or static binding)
     -      Run Time Polymorphism (Called as Late Binding or Overriding or dynamic binding)

Compile Time Polymorphism or Early Binding

In Compile time polymorphism, the decision is made at compile time. It means we will declare methods with same name but different signatures because of this we will perform different tasks with same method name. This compile time polymorphism also called as early binding or method /operator /constructor overloading.

Overloading is mainly three types i.e.
1.       Method Overloading: Method Overloading or compile time polymorphism means same method names with different signatures (different parameters)
2.       Operator Overloading
3.       Constructor overloading
                                                 
Example:
public class Class1
{
public void NumbersAdd(int a, int b)
{
Console.WriteLine(a + b);
}
public void NumbersAdd(int a, int b, int c)
{
Console.WriteLine(a + b + c);
}
}

In above class we have two methods with same name but having different input parameters this is called method overloading or compile time polymorphism or early binding. 

Run Time Polymorphism or Late Binding

Run time polymorphism also called as late binding or method overriding or dynamic polymorphism. Run time polymorphism or method overriding means same method names with same signatures.

In this run time polymorphism or method overriding we can override a method in base class by creating similar function in derived class this can be achieved by using inheritance principle and using “virtual & override” keywords.

In base class if we declare methods with virtual keyword then only we can override those methods in derived class using override keyword





Example:

//Base Class
public class Bclass
{
public virtual void Sample1()
{
Console.WriteLine("Base Class");
}
}
// Derived Class
public class DClass : Bclass
{
public override void Sample1()
{
Console.WriteLine("Derived Class");
}
}
// Using base and derived class
class Program
{
static void Main(string[] args)
{
// calling the overriden method
DClass objDc = new DClass();
objDc.Sample1();
// calling the base class method
Bclass objBc = new DClass();
objBc.Sample1();
}
}
Virtual Method: Virtual method is a method whose behavior can be overridden in derived class. Virtual method allows declare a method in base class that can be redefined in each derived class.
  • By default, methods are non-virtual. You cannot override a non-virtual method.
  • You cannot use the virtual modifier with the static, abstract, private or override modifiers.
  • Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.
  • A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
·         If a Virtual function derived in derived class without mentioning “override” keyword then it will work as in case of new keyword.

Sealed Keyword: Sealed keyword can be used to stop method overriding in a derived classes.  Sealed function cannot be hidden by new keyword.



Friday, March 28, 2014

SQL -Server - In case of multiple transaction in a procedure, what will happen if error will occur after inner transaction commit statement?

Committing inner transactions is ignored by the SQL Server Database Engine. The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction. If the outer transaction is committed, the inner nested transactions are also committed. If the outer transaction is rolled back, then all inner transactions are also rolled back, regardless of whether or not the inner transactions were individually committed.

Thursday, September 19, 2013

Dotnet Interview Question

1. What is Property?
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Example:

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}
 
2. What is the difference between abstraction and encapsulation?
Abstraction:
Abstraction lets you focus on what the object does instead of how it does it
That means we use the object without knowing the source code of the class.

Encapsulation:
Encapsulation means hiding the internal details or mechanics of how an object does something.
Encapsulation is warping data into single unit.


3. What is the difference between classes and structs in Microsoft.Net? 
  • A struct is a value type, while a class is a reference type.
  • When we instantiate a class, memory will be allocated on the heap, But when struct gets initiated, it gets memory on the stack.
  • Classes can have explicit parameter less constructors. But structs cannot have this.
  • Classes support inheritance. But there is no inheritance for structs. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Like classes, structures can implement interfaces.
  • We can assign null variable to class. But we cannot assign null to a struct variable, since structs are value type.
  • We can declare a destructor in class but can not in struct.

4. In which event are the controls fully loaded?
Page load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that view state is not fully loaded during this event.


5. How can we identify that the Page is Post Back?
Page object has an "IsPostBack" property, which can be checked to know that is the page posted back.

6. What is Query String? What are its advantages and limitations?

The Query String helps in sending the page information to the server.

The Query String has the following advantages:
  • Every browser works with Query Strings.
  • It does not require server resources and so does not exert any kind of burden on the server.
The following are the limitations of Query String:
  • Information must be within the limit because URL does not support many characters.
  • Information is clearly visible to the user, which leads to security threats.
7. What is View State?
The View State is a feature used by ASP.NET web page to store the value of a page and its controls just before posting the page. Once the page is posted, the first task by the page processing is to restore the View State to get the values of the controls.

8. How can you register a custom server control to a web page?
You can register a custom server control to a Web page using the @Register directive.
OR
You can also add in web config like below
<pages>
      <controls>
        <add assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajax"></add></controls></pages>

9.  What are the types of comment in C# with examples?
Single line
Eg:
[csharp]   //This is a Single line comment[/csharp]
ii. Multiple line (/* */)
Eg:
[csharp] /*This is a multiple line comment
We are in line 2
Last line of comment*/[/csharp]
iii. XML Comments (///).
Eg:
[csharp]/// summary;
///  Set error message for multilingual language.
/// summary[/csharp]
10. Can multiple catch blocks be executed?
No, Multiple catch blocks can’t be executed. Once the proper catch code executed, the control is transferred to the finally block and then the code that follows the finally block gets executed.

11. Can “this” be used within a static method?  
We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.

12. What is difference between constants and read-only?
Constant and ReadOnly keyword are used to make a field constant which value cannot be modified.

Constant
Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
public const int X = 10;
A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
void Calculate(int Z)
{
  const int X = 10, X1 = 50;
  const int Y = X + X1; //no error, since its evaluated a compile time
  const int Y1 = X + Z; //gives error, since its evaluated at run time
}
You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.
const MyClass obj1 = null;//no error, since its evaluated a compile time
const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time
Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly
A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.
class MyClass {
  readonly int X = 10; // initialized at the time of declaration
  readonly int X1;

  public MyClass(int x1)
  {
    X1 = x1; // initialized at run time
  }
}
Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
Use the readonly modifier when you want to make a field constant at run time.