Saturday 26 October 2013

50 Interview Questions and Answers On OOP's in C# Language

1.How to prevent a class from being inherited?

In order to prevent a class in C# from being inherited, the keyword sealed is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class.

2.What is implementation inheritance and interface inheritance?

When a class is derived from another class in such a way that it will inherit all its members to its corresponding derived class, then it is implementation inheritance. When a class inherits only the signatures of the functions from its corresponding base class, then it is interface inheritance.

3.What is difference between out and ref keywords in C# .NET?

Ref parameter is both input and o/p parameter out parameter is only output parameter. As ref parameter treated as input parameter too, ref requires that the variable be initialized before being passed; otherwise you will receive compiler error.

As out parameter treated only as output parameter, out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

4.Can we call a base class method without creating instance?

It’s possible if it’s a static method.
It’s possible by inheriting from that class also.
It’s possible from derived classes using base keyword.

5.What is an abstract class?

An abstract class is a class which cannot be instantiated. Creation of an object is not possible with abstract class , but it can be inherited. An abstract class can contain only Abstract method.

6.What is method overriding?

Method overriding is a feature that allows sub class to provide implementation of a method that is already defined in the main class. This will overrides the implementation in the super class by providing the same method name, same parameter and same return type.

7.What is sealed modifiers?

Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed modifiers can also be applied to properties, events and methods. This modifier cannot be applied to static members.

8.What is the difference between new and override?

The new modifier instructs the compiler to use the new implementation instead of the base class function. Whereas, Override modifier helps to override the base class function.

9.What does the keyword virtual represented in the method definition?

It means, we can override the method.

10.Whether static method can use non static members?

False.

11.What are base class, sub class and super class?

Base class is the most generalized class , and it is said to be a root class.
Sub class is a class that inherits from one or more base classes.
Super class is the parent class from which another class inherits.

12.How many instances can be created for an abstract class?

Zero instances will be created for an abstract class

13.Which OOPS concept is used as reuse mechanism?

Inheritance is the OOPS concept that can be used as reuse mechanism.

14.Which OOPS concept exposes only necessary information to the calling functions?

Data Hiding / Abstraction

15.Is it possible for a class to inherit the constructor of its base class?

No, a class cannot inherit the constructor of its base class.

16.Can you declare an overridden method to be static if the original method is not static?

No. Two virtual methods must have the same signature.

17.Does .NET support multiple inheritance?

.NET does not support multiple inheritance directly because in .NET, a class cannot inherit from more than one class. .NET supports multiple inheritance through interfaces.

18.What is the difference between procedural and object-oriented programming?

Procedural programming is based upon the modular approach in which the larger programs are broken into procedures. Each procedure is a set of instructions that are executed one after another. On the other hand, OOP is based upon objects. An object consists of various elements, such as methods and variables.

Access modifiers are not used in procedural programming, which implies that the entire data can be accessed freely anywhere in the program. In OOP, you can specify the scope of a particular data by using access modifiers - public, private, internal, protected, and protected internal.

19.A structure in C# can implement one or more interfaces. Is it true or false?

Yes, it is true. Like classes, in C#, structures can implement one or more interfaces.

20.What are the different ways a method can be overloaded?

The different ways to overload a method are given as follows:

By changing the number of parameters used
By changing the order of parameters
By using different data types for the parameters

21.When do you really need to create an abstract class?

We define abstract classes when we define a template that needs to be followed by all the derived classes.

22. What is Structured Programming?

Breaking down a program into more manageable blocks of code is called structured programming. This process allows a large system to broken down into smaller manageable pieces.

23. What are the disadvantages in structured programming?

The disadvantage of structured programming depends with the way programs are written. Other disadvantages include the lack of encapsulation, longer code and lack of information hiding.

24. What is object-oriented programming (OOP)?

OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object is created in the program to represent a class. Therefore, an object encapsulates all the features, such as data and behavior that are associated to a class. OOP allows developers to develop modular programs and assemble them as software. Objects are used to access data and behaviors of different software modules, such as classes, namespaces, and sharable assemblies. .NET Framework supports only OOP languages, such as Visual Basic .NET, Visual C#, and Visual C++.

25. What is a class?

A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It is a comprehensive data type, which represents a blue print of objects. It is a template of object.

A class can be defined as the primary building block of OOP. It also serves as a template that describes the properties, state, and behaviors common to a particular group of objects.

A class contains data and behavior of an entity. For example, the aircraft class can contain data, such as model number, category, and color and behavior, such as duration of flight, speed, and number of passengers. A class inherits the data members and behaviors of other classes by extending from them.

26. What is an object?

They are instance of classes. It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Attributes and behavior of an object are defined by the class definition.

27. What is the relationship between a class and an object?

Class acts as a blue-print that defines the properties, states, and behaviors that is common to a number of objects. An object is an instance of the Class. For example, you have a class called Vehicle and Car is the object of that class. You can create any number of objects for the class named Vehicle, such as Van, Truck, and Auto.

The new operator is used to create an object of a class. When an object of a class is instantiated, the system allocates memory for every data member that is present in the class.

28. Explain the basic features of OOPs?

The following are the four basic features of OOP:

Abstraction - Refers to the process of exposing only the relevant and essential data to the users without showing unnecessary information.

Polymorphism - Allows you to use an entity in multiple forms.

Encapsulation - Prevents the data from unwanted access by binding of code and data in a single unit called object.

Inheritance - Promotes the re-usability of code and eliminates the use of redundant code. It is the property through which a child class obtains all the features defined in its parent class. When a class inherits the common properties of another class, the class inheriting the properties is called a derived class and the class that allows inheritance of its common properties is called a base class.

29. What are methods?

Methods are the building blocks of a class, in which they are linked together to share and process data to produce the result. In other words, a method is a block of code that contains a series of statements and represents the behavior of a class. While declaring a method you need to specify the access specifies, the return value, the name of the method, and the method parameters. All these combined together is called the signature of the method.

30. What is Association?

Association is a (*a*) relationship between two classes. It allows one object instance to cause another to perform an action on its behalf. Association is the more general term that defines the relationship between two classes.

31. What is Aggregation?

Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object cannot belongs to another parent object. Let’s take an example of Department and teacher. A single teacher cannot belong to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship.

32. What is composition?

Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have their life cycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically delete.

33. Difference between aggregation and composition?

Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.

34.How many types of classes?

Types of classes in C#.Net:

• Abstract Class (sometimes called a Pure Virtual Class)
• Partial Class
• Sealed Class
• Static Class

35. What is abstract class?

Abstract Class: An Abstract Class means that, no object of this class can be instantiated, but can make derivation of this. It can serve the purpose of base class only as no object of this class can be created.

Abstract Class is denoted by the keyword abstract.

36. What is partial class?

Partial Class: This special type of class called "Partial Class" is introduced with .Net Framework 2.0. Partial Class allows its members – method, properties, and events – to be divided into multiple source files (.cs). At compile time these files get combined into a single class.

Partial Class is denoted by the keyword partial.

37. What is sealed class?

Sealed Class: A sealed class is a class which cannot be inherited. A sealed class cannot be a base class. The modifier abstract cannot be applied to a sealed class. By default, struct (structure) is sealed. It is the last class in hierarchy. To access the members of a sealed class, you must create objects of that class. 

Sealed Class is denoted by the keyword sealed.

38. What is static class?

Static Class: A Static Class is one which cannot be instantiated. The keyword new cannot be used with static classes as members of such class can be called directly by using the class name itself.

39. What are the Characteristics of an object?

State: object stored information
Behavior: objects perform task
Identity: objects are distinguish from others

40.What is an abstract class?

Abstract class is a class that can not be instantiated, it exists extensively for inheritance and it must be inherited. There are scenarios in which it is useful to define classes that is not intended to instantiate; because such classes normally are used as base-classes in inheritance hierarchies, we call such classes abstract classes.

Abstract classes cannot be used to instantiate objects; because abstract classes are incomplete, it may contain only definition of the properties or methods and derived classes that inherit this implements it's properties or methods.

Static, Value Types & interface doesn't support abstract modifiers. Static members cannot be abstract. Classes with abstract member must also be abstract.

41.What is the diff. between abstract & interface?

Abstract Class:

1.It can contain Concrete methods(methods with implementation) So in other words, Abstract class can contain methods with both implemetaion and without implementation.
2.Multiple inheritance is not possible in case of abstract class.
3.Access Specifiers are been Supported in abstract class.

Interface:

1.Does not contain any concrete methods.
2.Multiple Inheritance is possible with interface.
3.Access Specifiers are not supported in Interface.


42.What are class access modifiers?

Public: There are no restrictions on accessing public members.

Private: Access is limited to within the class definition. This is the default access modifier type if none is formally specified

Protected: Access is limited to within the class definition and any class that inherits from the class

Internal: Access is limited exclusively to classes defined within the current project assembly

protected internal: Access is limited to the current assembly and types derived from the containing class. All members in current project and all members in derived class can access the variables.

43.What is Encapsulation?

Encapsulation is one of the fundamental principles of object-oriented programming.
Encapsulation is a process of hiding all the internal details of an object from the outside world.
Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required.
Encapsulation is a protective barrier that prevents the code and data being randomly accessed by other code or by outside the class.
Encapsulation gives us maintainability, flexibility and extensibility to our code.
Encapsulation makes implementation inaccessible to other parts of the program and protect from whatever actions might be taken outside the function or class.
Encapsulation provides a way to protect data from accidental corruption.
Encapsulation hides information within an object.
Encapsulation is the technique or process of making the fields in a class private and providing access to the fields using public methods.
Encapsulation gives you the ability to validate the values before the object user change or obtain the value.
Encapsulation allows us to create a "black box" and protects an objects internal state from corruption by its clients.

44.What is Abstraction?

The word abstract means a concept or an idea not associated with any specific instance.

In programming we apply the same meaning of abstraction by making classes not associated with any specific instance.

The abstraction is done when we need to only inherit from a certain class, but not need to instantiate objects of that class. In such case the base
class can be regarded as "Incomplete". Such classes are known as an "Abstract Base Class".

45.suppose a class has private data members but the setters and getters are in public scope. If you inherit from this class, you can still call those setters and getters -- enabling access to the private data members in the base class. How is this possible since it is mentioned that a derived class cannot inherit private data members.

Because the getters and setters are public -- they're callable by anyone, not just derived classes.

46.What will happen when the virtual keyword is used with a method without implementation? 

For example.
class A
{
public virtual void Show();
}
Answer:
Error 1 'ConsoleApplication.A.Show()' must declare a body because it is not marked abstract, extern, or partial

47.What will be the output of the C# .NET code snippet given below Where the base class method is overridden by a derived class using the new keyword?

class Program
{
static void Main(string[] args)
{
A obj = new B();
obj.Show();
Console.ReadLine();
}
}
class A
{
public virtual void Show()
{
Console.WriteLine("A.Show()");
}
}
class B : A
{
public new void Show()
{
Console.WriteLine("B.Show()");
}
}

Answer: A.Show()

48.What will be the output of the C# .NET code snippet given below?

class Program
{
static void Main(string[] args)
{
A obj = new B();
obj.Show();
Console.ReadLine();
}
}
class A
{
public virtual void Show()
{
Console.WriteLine("A.Show()");
}
}
class B : A
{
public void Show()
{
Console.WriteLine("B.Show()");
}
}
Answer:
Warning 1 'ConsoleApplication.B.Show()' hides inherited member 'ConsoleApplication.A.Show()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

49.Can fields inside a class be virtual?

No, Fields inside a class cannot be virtual. Only methods, properties, events and indexers can be virtual.

50.Can you access a hidden base class method in the derived class?

Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the derived class to an instance of the base class as shown in the example below.

Thursday 17 October 2013

Get Data From DB On Gridview Using StoredProcedure In Asp.Net

Write code in UI section i.e GridViewWithStoredProcedure.aspx:

Gridview Control WithOut Template Field:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewWithStoredProcedure.aspx.cs" Inherits="GridViewWithStoredProcedure" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="EmpID" HeaderText="EmpID" ReadOnly="True" SortExpression="EmpID" />
                <asp:BoundField DataField="Ename" HeaderText="Ename" SortExpression="Ename" />
                <asp:BoundField DataField="Job" HeaderText="Job" SortExpression="Job" />
                <asp:BoundField DataField="Sal" HeaderText="Sal" SortExpression="Sal" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Show" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

Add Connection String in web.config file: 

<connectionStrings>
  <add name="conStr" connectionString="Server=Subas-PC;Database=SubasDB;User id=sa;Pwd=123"/>
</connectionStrings>

Write Your Procedure in Sql Server for Show Data On Gridview for Employee Table:

Create Procedure SP_GetAllEmpDetails
As
Begin
Select * from Employee
End

Write code in CodeBehind section i.e GridViewWithStoredProcedure.aspx.cs:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class GridViewWithStoredProcedure : System.Web.UI.Page
{
    SqlConnection cn;
    SqlDataAdapter da;
    DataSet ds;
    string strSqlQuery;
    protected void Page_Load(object sender, EventArgs e)
    {
     
        if (Page.IsPostBack)
        {
            cn = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
            BindEmpData();
        }
    }
    void BindEmpData()
    {
        da = new SqlDataAdapter("SP_GetAllEmpDetails", cn);
        da.SelectCommand.CommandType = CommandType.StoredProcedure;
        ds = new DataSet();
        da.Fill(ds, "Employee");
        GridView1.DataSource = ds.Tables["Employee"];
        GridView1.DataBind();
    }
  
    protected void Button1_Click(object sender, EventArgs e)
    {

        BindEmpData();
    }
}