Tuesday, December 1, 2015

C # Interview Questions


C# INTERVIEW QUESTIONS:
Q)   What is C-Sharp (C#)?
Ans: C# is a type-safe, managed and object oriented language, which is compiled by .Net framework for generating intermediate language (IL).

Q) Explain the features of C#?

Ans: Below are some of the features supported in C# -
·       Constructors and Destructors
·       Properties
·       Passing Parameters
·       Arrays
·       Main
·       XML Documentation and
·       Indexers

Q) List some of the advantages of C#?

Ans: Below are the advantages of C# -
·       Easy to learn
·       Object oriented
·       Component oriented
·       Part of .NET framework

Q) What are IDE’s provided by Microsoft for C# development?

Ans: Below are the IDE’s used for C# development –
·       Visual Studio Express (VCE)
·       Visual Studio (VS)
·       Visual Web Developer

Q) Explain the types of comments in C#?

Ans: Below are the types of comments in C# -
·       Single Line Comment Eg : //
·       Multiline Comments Eg: /* */
·       XML Comments Eg : ///


Q) Explain sealed class in C#?

Ans: Sealed class is used to prevent the class from being inherited from other classes.So “sealed” modifier also can be used with methods to avoid the methods to override in the child classes.

Q) Give an example of using sealed class in C#?

Ans: Below is the sample code of sealed class in C# -
class X {}
sealed class Y : X {}
Sealed methods –
class A
{
 protected virtual void First() { }
 protected virtual void Second() { }
}
class B : A
{
 sealed protected override void First() {}
 protected override void Second() { }
}
If any class inherits from class “B” then method – “First” will not be overridable as this method is sealed in class B.

Q) List out the differences between Array and ArrayList in C#?

·        Array stores the values or elements of same data type but arraylist stores values of different datatypes.
·        Arrays will use the fixed length but arraylist does not uses fixed length like array.

Q) Why to use “using” in C#?

Ans:  “Using” statement calls – “dispose” method internally, whenever any exception occurred in any method call and in “Using” statement objects are read only and cannot be reassignable or modifiable.

Q) Explain namespaces in C#?

Ans: Namespaces are containers for the classes. We will use namespaces for grouping the related classes in C#. “Using” keyword can be used for using the namespace in other namespace.

Q) Why to use keyword “const” in C#? Give an example.

Ans:  “Const” keyword is used for making an entity constant. We can’t reassign the value to constant.
Eg: const string _name = "Test";

Q) What is the difference between “constant” and “readonly” variables in C#?

·        “Const” keyword is used for making an entity constant. We cannot modify the value later in the code. Value assigning is mandatory to constant variables.
·        “readonly” variable value can be changed during runtime and value to readonly variables can be assigned in the constructor or at the time of declaration.

Q) Explain “static” keyword in C#?

Ans:  “Static” keyword can be used for declaring a static member. If the class is made static then all the members of the class are also made static. If the variable is made static then it will have a single instance and the value change is updated in this instance.

Q) What is the difference between “dispose” and “finalize” variables in C#?

·        Dispose - This method uses interface – “IDisposable” interface and it will free up both managed and unmanaged codes like – database connection, files etc.
·        Finalize - This method is called internally unlike Dispose method which is called explicitly. It is called by garbage collector and can’t be called from the code.

Q) How the exception handling is done in C#?

Ans: In C# there is a “try… catch” block to handle the error.

Q) Can we execute multiple catch blocks in C#?

Ans: No. Once any exception is occurred it executes specific exception catch block and the control comes out.

Q) Why to use “finally” block in C#?

Ans:  “Finally” block will be executed irrespective of exception. So while executing the code in try block when exception is occurred, control is returned to catch block and at last “finally” block will be executed. So closing connection to database / releasing the file handlers can be kept in “finally” block.
·        Dispose - This method uses interface – “IDisposable” interface and it will free up both managed and unmanaged codes like – database connection, files etc.
·        Finalize - This method is called internally unlike Dispose method which is called explicitly. It is called by garbage collector and can’t be called from the code.

Q) What is the difference between “finalize” and “finally” methods in C#?

·        Finalize – This method is used for garbage collection. So before destroying an object this method is called as part of clean up activity.
·        Finally – This method is used for executing the code irrespective of exception occurred or not.

Q) What is the difference between “throw ex” and “throw” methods in C#?

·        “throw ex” will replace the stack trace of the exception with stack trace info of re throw point.
·        “throw” will preserve the original stack trace info.

Q) Can we have only “try” block without “catch” block in C#?

Ans: Yes we can have only try block without catch block.

Q) List out two different types of errors in C#?

Ans: Below are the types of errors in C# -
·       Compile Time Error
·       Run Time Error

Q) Do we get error while executing “finally” block in C#?

Ans: Yes. We may get error in finally block.

Q) Mention the assembly name where System namespace lies in C#?

Ans: Assembly Name – mscorlib.dll

Q) What are the differences between static, public and void in C#?

·        Static classes/methods/variables are accessible throughout the application without creating instance. Compiler will store the method address as an entry point. 
·        Public methods or variables are accessible throughout the application. 
·        Void is used for the methods to indicate it will not return any value.

Q) What is the difference between “out” and “ref” parameters in C#?

Ans:  “out” parameter can be passed to a method and it need not be initialized where as “ref” parameter has to be initialized before it is used.

Q) Explain Jagged Arrays in C#?

Ans: If the elements of an array is an array then it’s called as jagged array. The elements can be of different sizes and dimensions.

Q) Can we use “this” inside a static method in C#?
Ans: No. We can’t use “this” in static method.
Q) What are value types in C#?
Ans: Below are the list of value types in C# -
·       decimal
·       int
·       byte
·       enum
·       double
·       long
·       float

Q) What are reference types in C#?
Ans: Below are the list of reference types in C# -
·       class
·       string
·       interface
·       object

Q) Can we override private virtual method in C#?

Ans: No. We can’t override private virtual methods as it is not accessible outside the class.

Q) Explain access modifier – “protected internal” in C#?

Ans:  “protected internal” can be accessed in the same assembly and the child classes can also access these methods.

Q) In try block if we add return statement whether finally block is executed in C#?

Ans: Yes. Finally block will still be executed in presence of return statement in try block.

Q) What you mean by inner exception in C#?

Ans: Inner exception is a property of exception class which will give you a brief insight of the exception i.e, parent exception and child exception details.

Q) Explain String Builder class in C#?

Ans: This will represent the mutable string of characters and this class cannot be inherited. It allows us to Insert, Remove, Append and Replace the characters. “ToString()” method can be used for the final string obtained from StringBuilder. For example,
StringBuilder TestBuilder = new StringBuilder("Hello");
TestBuilder.Remove(2, 3); // result - "He"
TestBuilder.Insert(2, "lp"); // result - "Help"
TestBuilder.Replace('l', 'a'); // result - "Heap"

Q) What is the difference between “StringBuilder” and “String” in C#?

·        StringBuilder is mutable, which means once object for stringbuilder is created, it later be modified either using Append, Remove or Replace.
·        String is immutable and it means we cannot modify the string object and will always create new object in memory of string type.

Q) What is the difference between methods – “System.Array.Clone()” and “System.Array.CopyTo()” in C#?

·        “CopyTo()” method can be used to copy the elements of one array to other. 
·        “Clone()” method is used to create a new array to contain all the elements which are in the original array.

Q) How we can sort the array elements in descending order in C#?

Ans:  “Sort()” method is used with “Reverse()” to sort the array in descending order.

Q) Explain circular reference in C#?

Ans: This is a situation where in, multiple resources are dependent on each other and this causes
a lock condition and this makes the resource to be unused.

Q) List out some of the exceptions in C#?

Ans: Below are some of the exceptions in C# -
·       NullReferenceException
·       ArgumentNullException
·       DivideByZeroException
·       IndexOutOfRangeException
·       InvalidOperationException
·       StackOverflowException etc.

Q) Explain Generics in C#?

Ans: Generics in c# is used to make the code reusable and which intern decreases the code redundancy and increases the performance and type safety.
Namespace – “System.Collections.Generic” is available in C# and this should be used over “System.Collections” types.



Q) Explain object pool in C#?

Ans: Object pool is used to track the objects which are being used in the code. So object pool reduces the object creation overhead.

Q) What you mean by delegate in C#?

Ans: Delegates are type safe pointers unlike function pointers as in C++. Delegate is used to represent the reference of the methods of some return type and parameters.

Q) What are the types of delegates in C#?
Ans: Below are the uses of delegates in C# -
·       Single Delegate
·       Multicast Delegate
·       Generic Delegate

Q) What are the three types of Generic delegates in C#?
Ans: Below are the three types of generic delegates in C# -
·       Func
·       Action
·       Predicate

Q) What are the differences between events and delegates in C#?

Ans: Main difference between event and delegate is event will provide one more of encapsulation over delegates. So when you are using events destination will listen to it but delegates are naked, which works in subscriber/destination model.

Q) Can we use delegates for asynchronous method calls in C#?

Ans: Yes. We can use delegates for asynchronous method calls.

Q) What are the uses of delegates in C#?

Ans: Below are the list of uses of delegates in C# -
·       Callback Mechanism
·       Asynchronous Processing
·       Abstract and Encapsulate method
·       Multicasting

Q) What is Nullable Types in C#?

Ans: Variable types does not hold null values so to hold the null values we have to use nullable types. So nullable types can have values either null or other values as well.
Eg: Int? mynullablevar = null;

Q) Why to use “Nullable Coalescing Operator” (??) in C#?

Ans: Nullable Coalescing Operator can be used with reference types and nullable value types. So if the first operand of the expression is null then the value of second operand is assigned to the variable. For example,
double? myFirstno = null;
double mySecno;
mySecno = myFirstno ?? 10.11;

Q) What is the difference between “as” and “is” operators in C#?

·        “as” operator is used for casting object to type or class.
·        “is” operator is used for checking the object with type and this will return a Boolean value.

Q) Define Multicast Delegate in C#?

Ans: A delegate with multiple handlers are called as multicast delegate. The example to demonstrate the same is given below
public delegate void CalculateMyNumbers(int x, int y);
int x = 6;
int y = 7;
CalculateMyNumbers addMyNumbers = new CalculateMyNumbers(FuncForAddingNumbers);
CalculateMyNumbers multiplyMyNumbers = new CalculateMyNumbers(FuncForMultiplyingNumbers);
CalculateMyNumbers multiCast = (CalculateMyNumbers)Delegate.Combine (addMyNumbers, multiplyMyNumbers);
multiCast.Invoke(a,b);

Q) What is the difference between CType and Directcast in C#?

·        CType is used for conversion between type and the expression.
·        Directcast is used for converting the object type which requires run time type to be the same as specified type.

Q) Is C# code is unmanaged or managed code?

Ans: C# code is managed code because the compiler – CLR will compile the code to Intermediate Language.

Q) Why to use lock statement in C#?

Ans: Lock will make sure one thread will not intercept the other thread which is running the part of code. So lock statement will make the thread wait, block till the object is being released.

Q) Explain Hashtable in C#?

Ans: It is used to store the key/value pairs based on hash code of the key. Key will be used to access the element in the collection. For example,
Hashtable myHashtbl = new Hashtable();
myHashtbl.Add("1", "TestValue1");
myHashtbl.Add("2", "TestValue2");

Q) How to check whether hash table contains specific key in C#?

Ans: Method – “ContainsKey” can be used to check the key in hash table. Below is the sample code for the same –
Eg: myHashtbl.ContainsKey("1");

Q) What is enum in C#?

Ans: enum keyword is used for declaring an enumeration, which consists of named constants and it is called as enumerator lists. Enums are value types in C# and these can’t be inherited. Below is the sample code of using Enums
Eg: enum Fruits { Apple, Orange, Banana, WaterMelon};

Q) Which are the loop types available in C#?

Ans: Below are the loop types in C# -
For
While
Do.. While

Q) What is the difference between “continue” and “break” statements in C#?

·        “continue” statement is used to pass the control to next iteration. This statement can be used with – “while”, “for”, “foreach” loops.
·        “break” statement is used to exit the loop.

Q) Write a sample code to write the contents to text file in C#?

Ans: Below is the sample code to write the contents to text file –
Using System.IO;
File.WriteAllText(”mytextfilePath”, “MyTestContent”);


Q) What you mean by boxing and unboxing in C#?
Boxing – This is the process of converting from value type to reference type. For example,
int myvar = 10;
object myObj = myvar;
UnBoxing – It’s completely opposite to boxing. It’s the process of converting reference type to value type. For example,
int myvar2 = (int)myObj;

Q) Explain Partial Class in C#?

Ans: Partial classes concept added in .Net Framework 2.0 and it allows us to split the business logic in multiple files with the same class name along with “partial” keyword.

Q) Explain Anonymous type in C#?

Ans: This is being added in C# 3.0 version. This feature enables us to create an object at compile time. Below is the sample code for the same –
Var myTestCategory = new { CategoryId = 1, CategoryName = “Category1”};

Q) Name the compiler of C#?

Ans: C# Compiler is – CSC.

Q) Explain the types of unit test cases?

Ans: Below are the list of unit test case types –
·       Positive Test cases
·       Negative Test cases
·       Exception Test cases

Q) Explain Copy constructor in C#?

Ans: If the constructor contains the same class in the constructor parameter then it is called as copy constructor.
class MyClass
{
 public string prop1, prop2;
 public MyClass(string a, string b)
 {
 prop1 = a;
 prop2 = b;
 }

 public MyClass(MyClass myobj) // Copy Constructor
 {
 prop1 = myobj.prop1;
 prop2 = myobj.prop2;
 }
}

Q) Explain Static constructor in C#?

Ans: If the constructor is declared as static then it will be invoked only once for all number of instances of a class. Static constructor will initialize the static fields of a class.
class MyClass
{
 public string prop1, prop2;
 public MyClass(string a, string b)
 {
 prop1 = a;
 prop2 = b;
 }

Static MyClass()
 {
 Console.WriteLine(“Static Constr Test”);
 }
 public MyClass(MyClass myobj) // Copy Constructor
 {
 prop1 = myobj.prop1;
 prop2 = myobj.prop2;
 }
}

Q) Which string method is used for concatenation of two strings in c#?

Ans:  “Concat” method of String class is used to concatenate two strings. For example,
string.Concat(firstStr, secStr)

Q) Explain Indexers in C#?

Ans: Indexers are used for allowing the classes to be indexed like arrays. Indexers will resemble the property structure but only difference is indexer’s accessors will take parameters. For example,
class MyCollection<T>
{
 private T[] myArr = new T[100];
 public T this[int t]
 {
 get
 {
 return myArr[t];
 }
 set
 {
 myArr[t] = value;
 }
 }
}

Q) What are the collection types can be used in C#?

Ans: Below are the collection types in C# -
·       ArrayList
·       Stack
·       Queue
·       SortedList
·       HashTable
·       Bit Array

Q) Explain Attributes in C#?

·        Attributes are used to convey the info for runtime about the behavior of elements like – “methods”, “classes”, “enums” etc.
·        Attributes can be used to add metadata like – comments, classes, compiler instruction etc.

Q) List out the pre defined attributes in C#?

Ans: Below are the predefined attributes in C# -
·       Conditional
·       Obsolete
·       Attribute Usage

Q) What is Thread in C#?

Ans: Thread is an execution path of a program. Thread is used to define the different or unique flow of control. If our application involves some time consuming processes then it’s better to use Multithreading., which involves multiple threads.

Q) List out the states of a thread in C#?

Ans: Below are the states of thread –
·       Unstarted State
·       Ready State
·       Not Runnable State
·       Dead State

Q) Explain the methods and properties of Thread class in C#?
Ans: Below are the methods and properties of thread class –
·        CurrentCulture
·        CurrentThread
·        CurrentContext
·        IsAlive
·        IsThreadPoolThread
·        IsBackground
·        Priority

Q) What is a class?

Ans: A class is the generic definition of what an object is. A Class describes all the attributes of the object, as well as the methods that implement the behavior of the member object. In other words, class is a template of an object. For ease of understanding a class, we will look at an example. In the class Employee given below, Name and Salary are the attributes of the class Person. The Setter and Getter methods are used to store and fetch data from the variable.
public class Employee
{
private String name;
private String Salary;
public String getName()
{
  return name;
}
public void setName(String name)
{
  this.name = name; 

}
public String getSalary ()
{
  return Salary;
}
public void setSalary (String Salary)
{
  this. Salary = Salary;
}
} 


Q) What is an Object?

Ans: An object is an instance of a class. It contains real values instead of variables. For example, let us create an instance of the class Employee called “John”.
Employee John= new Employee();
Now we can access all the methods in the class “Employee” via object “John” as shown below.
John.setName(“XYZ”);

Q) What are the Access Modifiers in C# ?

Ans: Different Access Modifier are - Public, Private, Protected, Internal, Protected Internal
·        Public – When a method or attribute is defined as Public, it can be accessed from any code in the project. For example, in the above Class “Employee” getName() and setName() are public.
·        Private - When a method or attribute is defined as Private, It can be accessed by any code within the containing class only. For example, in the above Class “Employee” attributes name and salary can be accessed within the Class Employee Only. If an attribute or class is defined without access modifiers, it's default access modifier will be private.
·        Protected - When attribute and methods are defined as protected, it can be accessed by any method in the inherited classes and any method within the same class. The protected access modifier cannot be applied to classes and interfaces. Methods and fields in a interface can't be declared protected.
·        Internal – If an attribute or method is defined as Internal, access is restricted to classes within the current project assembly.
·        Protected Internal – If an attribute or method is defined as Protected Internal, access is restricted to classes within the current project assembly and types derived from the containing class. 

Q) Explain Static Members in C# ?

Ans: If an attribute's value had to be same across all the instances of the same class, the static keyword is used. For example, if the Minimum salary should be set for all employees in the employee class, use the following code.
private static double MinSalary = 30000;
To access a private or public attribute or method in a class, at first an object of the class should be created. Then by using the object instance of that class, attributes or methods can be accessed. To access a static variable, we don't want to create an instance of the class containing the static variable. We can directly refer that static variable as shown below.
double var = Employee.MinSalary ;



Q) What is Reference Type in C# ?

Ans: Let us explain this with the help of an example. In the code given below,
Employee emp1;
Employee emp2 = new Employee();
emp1 = emp2;
Here emp2 has an object instance of Employee Class. But emp1 object is set as emp2. What this means is that the object emp2 is referred in emp1, rather than copying emp2 instance into emp1. When a change is made in emp2 object, corresponding changes can be seen in emp1 object. 

Q) Define Property in C# ?

Ans: Properties are a type of class member, that are exposed to the outside world as a pair of Methods. For example, for the static field Minsalary, we will Create a property as shown below.
private double minimumSalary;
public static double MinSalary
{
 get
 {
   return minimumSalary;
 }
 set
 {
   minimumSalary = value;
 }
}

So when we execute the following lines code
double minSal = Employee.MinSalary;
get Method will get triggered and value in minimumSalary field will be returned. When we execute,
Employee. MinSalary = 3000;
set Method will get triggered and value will be stored in minimumSalary field.


Q) Explain Overloading in C# ?

Ans: When methods are created with the same name, but with different signature its called overloading. For example, WriteLine method in console class is an example of overloading. In the first instance, it takes one variable. In the second instance, “WriteLine” method takes two variable.
Console.WriteLine(x);
Console.WriteLine("The message is {0}", Message);
Q) Different types of overloading in C# are
·        Constructor overloading
·        Function overloading
·        Operator overloading

Q) What is Constructor Overloading in C# .net ?

Ans: In Constructor overloading, n number of constructors can be created for the same class. But the signatures of each constructor should vary. For example
public class Employee
{
 public Employee()
 { }
 public Employee(String Name)
 { }
}

Q) What is Function Overloading in C# .net ?

Ans: In Function overloading, n number of functions can be created for the same class. But the signatures of each function should vary. For example
public class Employee
{
 public void Employee()
 { }
 public void Employee(String Name)
 { }
}

Q) What is Operator Overloading in C# .net ?

Ans: We had seen function overloading in the previous example. For operator Overloading, we will have a look at the example given below. We had defined a class rectangle with two operator overloading methods.
class Rectangle
{
 private int Height;
 private int Width;

 public Rectangle(int w,int h)
 {
   Width=w;
   Height=h;
 }
 public static bool operator >(Rectangle a,Rectangle b)
 {
   return a.Height > b.Height ;
 }
 public static bool operator <(Rectangle a,Rectangle b)
 {
   return a.Height < b.Height ;
 }
}
Let us call the operator overloaded functions from the method given below. When first if condition is triggered, the first overloaded function in the rectangle class will be triggered. When second if condition is triggered, the second overloaded function in the rectangle class will be triggered. 
public static void Main()
{
Rectangle obj1 =new Rectangle();
Rectangle obj2 =new Rectangle();

 if(obj1 > obj2)
 {
  Console.WriteLine("Rectangle1 is greater than Rectangle2");
 }

 if(obj1 < obj2)
 {
  Console.WriteLine("Rectangle1 is less than Rectangle2");
 }
}

Q) What is Data Encapsulation?

Ans: Data Encapsulation is defined as the process of hiding the important fields from the end user. In the above example, we had used getters and setters to set value for MinSalary. The idea behind this is that, private field “minimumSalary” is an important part of our classes. So if we give a third party code to have complete control over the field without any validation, it can adversely affect the functionality. This is inline with the OOPS Concept that an external user should know about the what an object does. How it does it, should be decided by the program. So if a user set a negative value for MinSalary, we can put a validation in the set method to avoid negative values as shown below
set
{
 if(value > 0)
 {
  minSalary = value;
 }
}


Q) Explain Inheritance in C# ?

Ans: In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects. In inheritance, there will be two classes - base class and derived classes. A class can inherit attributes and methods from existing class called base class or parent class. The class which inherits from a base class is called derived classes or child class. For more clarity on this topic, let us have a look at 2 classes shown below. Here Class Car is Base Class and Class Ford is derived class.
class Car
{
 public Car()
 {
  Console.WriteLine("Base Class Car");
 }

 public void DriveType()
 {
  Console.WriteLine("Right Hand Drive");
 }
}

class Ford : Car
{
 public Ford()
 {
  Console.WriteLine("Derived Class Ford");
 }

 public void Price()
 {
  Console.WriteLine("Ford Price : 100K $");
 }
}
When we execute following lines of code ,
Ford CarFord = new Ford();
CarFord.DriveType();
CarFord.Price();
Output Generated is as given below.
Base Class Car
Derived Class Ford
Right Hand Drive
Ford Price : 100K $
What this means is that, all the methods and attributes of Base Class car are available in Derived Class Ford. When an object of class Ford is created, constructors of the Base and Derived class get invoked. Even though there is no method called DriveType() in Class Ford, we are able to invoke the method because of inheriting Base Class methods to derived class.

Q) Can Multiple Inheritance implemented in C# ?

Ans: In C#, derived classes can inherit from one base class only. If you want to inherit from multiple base classes, use interface.
 
Q) What is Polymorphism in C# ?

Ans: The ability of a programming language to process objects in different ways depending on their data type or class is known as Polymorphism. There are two types of polymorphism
·        Compile time polymorphism. Best example is Overloading
·        Runtime polymorphism. Best example is Overriding

Q) Explain the use of Virtual Keyword in C# ?

Ans: When we want to give permission to a derived class to override a method in base class, Virtual keyword is used. For example. lets us look at the classes Car and Ford as shown below.
class Car
{
 public Car()
 {
  Console.WriteLine("Base Class Car");
 }
 public virtual void DriveType()
 {
  Console.WriteLine("Right Hand Drive");
 }
}

class Ford : Car
{
 public Ford()
 {
  Console.WriteLine("Derived Class Ford");
 }
 public void Price()
 {
  Console.WriteLine("Ford Price : 100K $");
 }
 public override void DriveType()
 {
  Console.WriteLine("Right Hand ");
 }
}
When following lines of code get executed 
Car CarFord = new Car();
CarFord.DriveType();
CarFord = new Ford();
CarFord.DriveType();
Output is as given below.
Base Class Car
Right Hand Drive
Base Class Car
Derived Class Ford
Right Hand


Q) What is overriding in c# ?

Ans: To override a base class method which is defined as virtual, Override keyword is used. In the above example, method DriveType is overridden in the derived class.
Q) What is Method Hiding in C# ?

Ans: If the derived class doesn't want to use methods in the base class, derived class can implement it's own version of the same method with same signature. For example, in the classes given below, DriveType() is implemented in the derived class with same signature. This is called Method Hiding.
class Car
{
 public void DriveType()
 {
  Console.WriteLine("Right Hand Drive");
 }
}

class Ford : Car
{
 public void DriveType()
 {
  Console.WriteLine("Right Hand ");
 }
}




Q) What is Abstract Class in C#?

Ans: If we don't want a class to be instantiated, define the class as abstract. An abstract class can have abstract and non abstract classes. If a method is defined as abstract, it must be implemented in derived class. For example, in the classes given below, method DriveType is defined as abstract. 
abstract class Car
{
 public Car()
 {
  Console.WriteLine("Base Class Car");
 }
 public abstract void DriveType();
}

class Ford : Car
{
 public void DriveType()
 {
  Console.WriteLine("Right Hand ");
 }
}
Method DriveType get implemented in derived class.

Q) What is Sealed Classes in c# ?

Ans: If a class is defined as Sealed, it cannot be inherited in derived class. Example of a sealed class is given below.
public sealed class Car
{
 public Car()
 {
  Console.WriteLine("Base Class Car");
 }

 public void DriveType()
 {
  Console.WriteLine("Right Hand ");
 }
}

Q) What is an Interface in C# ?

Ans: An interface is similar to a class with method signatures. There wont be any implementation of the methods in an Interface. Classes which implement interface should have an implementation of methods defined in the abstract class.
Q) What is a Constructor in C# ?

Ans: Constructor is a special method that get invoked/called automatically, whenever an object of a given class gets instantiated. In our class car, constructor is defined as shown below
public Car()
{
 Console.WriteLine("Base Class Car");
}
When ever an instance of class car is created from the same class or its derived class(Except Few Scenarios), Constructor get called and sequence of code written in the constructor get executed.
interface Breaks
{
 void BreakType();
}
 
interface Wheels
{
 void WheelType();
}
 
class Ford : Breaks, Wheels
{
 public Ford()
 {
  Console.WriteLine("Derived Class Ford");
 }
 public void Price()
 {
  Console.WriteLine("Ford Price : 100K $");
 }
 public void BreakType()
 {
  Console.WriteLine("Power Break");
 }
 public void WheelType()
 {
  Console.WriteLine("Bridgestone");
 }
}




Q) What is a Destructor in C# ? 
Ans: Destructor is a special method that get invoked/called automatically whenever an object of a given class gets destroyed. Main idea behind using destructor is to free the memory used by the object.

ASP.NET INTERVIEW QUESTIONS

 

Q) Explain how a web application works.

Answer: A web application resides in the server and serves the client's requests over internet. The client access the web page using browser from his machine. When a client makes a request, it receives the result in the form of HTML which are interpreted and displayed by the browser.

A web application on the server side runs under the management of Microsoft Internet Information Services (IIS). IIS passes the request received from client to the application. The application returns the requested result in the form of HTML to IIS, which in turn, sends the result to the client.

Q) Explain the advantages of ASP.NET.

Answer: Following are the advantages of ASP.NET.

Web application exists in compiled form on the server so the execution speed is faster as compared to the interpreted scripts.

ASP.NET makes development simpler and easier to maintain with an event-driven, server-side programming model.

Being part of .Framework, it has access to all the features of .Net Framework.

Content and program logic are separated which reduces the inconveniences of program maintenance.

ASP.NET makes for easy deployment. There is no need to register components because the configuration information is built-in.

To develop program logic, a developer can choose to write their code in more than 25 .Net languages including VB.Net, C#, JScript.Net etc.

Introduction of view state helps in maintaining state of the controls automatically between the postbacks events.

ASP.NET offers built-in security features through windows authentication or other authentication methods.

Integrated with ADO.NET.

Built-in caching features.

Q) Explain the different parts that constitute ASP.NET application.

Answer: Content, program logic and configuration file constitute an ASP.NET application.

Content files
Content files include static text, images and can include elements from database.

Program logic
Program logic files exist as DLL file on the server that responds to the user actions.

Configuration file
Configuration file offers various settings that determine how the application runs on the server.

Q) Describe the sequence of action takes place on the server when ASP.NET application starts first time

Answer: Following are the sequences:

IIS starts ASP.NET worker process - worker process loads assembly in the memory - IIS sends the request to the assembly - the assembly composes a response using program logic - IIS returns the response to the user in the form of HTML.

Q) Explain the components of web form in ASP.NET

Answer: Server controls
The server controls are Hypertext Markup Language (HTML) elements that include a runat=server attribute. They provide automatic state management and server-side events and respond to the user events by executing event handler on the server.

HTML controls
These controls also respond to the user events but the events processing happen on the client machine.

Data controls
Data controls allow to connect to the database, execute command and retrieve data from database.

System components
System components provide access to system-level events that occur on the server.

Q) Describe in brief .NET Framework and its components.

Answer: .NET Framework provides platform for developing windows and web software. ASP.NET is a part of .Net framework and can access all features implemented within it that was formerly available only through windows API. .NET Framework sits in between our application programs and operating system.

The .Net Framework has two main components:

.Net Framework Class Library: It provides common types such as data types and object types that can be shared by all .Net compliant language.

The Common language Runtime: It provides services like type safety, security, code execution, thread management, interoperability services.

Q) What is an Assembly? Explain its parts

Answer: An assembly exists as a .DLL or .EXE that contains MSIL code that is executed by CLR. An assembly contains interface and classes, it can also contain other resources like bitmaps, files etc. It carries version details which are used by the CLR during execution. Two assemblies of the same name but with different versions can run side-by-side enabling applications that depend on a specific version to use assembly of that version. An assembly is the unit on which permissions are granted. It can be private or global. A private assembly is used only by the application to which it belongs, but the global assembly can be used by any application in the system.

The four parts of an assembly are:

Assembly Manifest - It contains name, version, culture, and information about referenced assemblies.

Type metadata - It contains information about types defined in the assembly.

MSIL - MSIL code.

Resources - Files such as BMP or JPG file or any other files required by application.

Q) Define Common Type System.

Answer: .Net allows developers to write program logic in at least 25 languages. The classes written in one language can be used by other languages in .Net. This service of .Net is possible through CTS which ensure the rules related to data types that all language must follow. It provides set of types that are used by all .NET languages and ensures .NET language type compatibility.

 

 

 

Q) Define Virtual folder.

Answer: It is the folder that contains web applications. The folder that has been published as virtual folder by IIS can only contain web applications.

Q) Describe the Events in the Life Cycle of a Web Application

Answer: A web application starts when a browser requests a page of the application first time. The request is received by the IIS which then starts ASP.NET worker process (aspnet_wp.exe). The worker process then allocates a process space to the assembly and loads it. An application_start event occurs followed by Session_start. The request is then processed by the ASP.NET engine and sends back response in the form of HTML. The user receives the response in the form of page.

The page can be submitted to the server for further processing. The page submitting triggers postback event that causes the browser to send the page data, also called as view state to the server. When server receives view state, it creates new instance of the web form. The data is then restored from the view state to the control of the web form in Page_Init event.

The data in the control is then available in the Page_load event of the web form. The cached event is then handled and finally the event that caused the postback is processed. The web form is then destroyed. When the user stops using the application, Session_end event occurs and session ends. The default session time is 20 minutes. The application ends when no user accessing the application and this triggers Application_End event. Finally all the resources of the application are reclaimed by the Garbage collector.

Q) What are the ways of preserving data on a Web Form in ASP.NET?

Answer: ASP.NET has introduced view state to preserve data between postback events. View state can't avail data to other web form in an application. To provide data to other forms, you need to save data in a state variable in the application or session objects.

Q) Define application state variable and session state variable.

Answer: These objects provide two levels of scope:

Application State
Data stored in the application object can be shared by all the sessions of the application. Application object stores data in the key value pair.

Session State
Session State stores session-specific information and the information is visible within the session only. ASP.NET creates unique sessionId for each session of the application. SessionIDs are maintained either by an HTTP cookie or a modified URL, as set in the application’s configuration settings. By default, SessionID values are stored in a cookie.

Q). Describe the application event handlers in ASP.NET

Answer: Following are the application event handlers:

Application_Start: This event occurs when the first user visits a page of the application.
Application_End: This event occurs when there are no more users of the application.
Application_BeginRequest: This occurs at the beginning of each request to the server.
Application_EndRequest: occurs at the end of each request to the server.
Session_Start: This event occurs every time when any new user visits.
Session_End: occurs when the users stop requesting pages and their session times out.

Q) What are the Web Form Events available in ASP.NET?

Answer: Page_Init
Page_Load
Page_PreRender
Page_Unload
Page_Disposed
Page_Error
Page_AbortTransaction
Page_CommitTransaction
Page_DataBinding

Q) Describe the Server Control Events of ASP.NET.

Answer: ASP.NET offers many server controls like button, textbox, DropDownList etc. Each control can respond to the user's actions using events and event handler mechanism.

There are three types of server control events:

Postback events
This events sends the web page to the server for processing. Web page sends data back to the same page on the server.

Cached events
These events are processed when a postback event occurs.

Validation events
These events occur just before a page is posted back to the server.

Q) How do you change the session time-out value?

Answer: The session time-out value is specified in the web.config file within sessionstate element. You can change the session time-out setting by changing value of timeout attribute of sessionstate element in web.config file.

Q) Describe how ASP.NET maintains process isolation for each Web application

Answer: In ASP.NET, when IIS receives a request, IIS uses aspnet_isapi.dll to call the ASP.NET worker process (aspnet_wp.exe). The ASP.NET worker process loads the Web application's assembly, allocating one process space, called the application domain, for each application. This is the how ASP.NET maintains process isolation for each Web application.

Q) Define namespace.

Answer: Namespaces are the way to organize programming code. It removes the chances of name conflict. It is quite possible to have one name for an item accidentally in large projects those results into conflict. By organizing your code into namespaces, you reduce the chance of these conflicts. You can create namespaces by enclosing a class in a Namespace...End Namespace block.

You can use namespaces outside your project by referring them using References dialog box. You can use Imports or using statement to the code file to access members of the namespaces in code.

Q) What are the options in ASP.NET to maintain state?

Answer: Client-side state management
This maintains information on the client’s machine using Cookies, View State, and Query Strings.

Cookies
A cookie is a small text file on the client machine either in the client’s file system or memory of client browser session. Cookies are not good for sensitive data. Moreover, Cookies can be disabled on the browser. Thus, you can’t rely on cookies for state management.

View State
Each page and each control on the page has View State property. This property allows automatic retention of page and controls state between each trip to server. This means control value is maintained between page postbacks. Viewstate is implemented using _VIEWSTATE, a hidden form field which gets created automatically on each page. You can’t transmit data to other page using view state.

Querystring
Query strings can maintain limited state information. Data can be passed from one page to another with the URL but you can send limited size of data with the URL. Most browsers allow a limit of 255 characters on URL length.

Server-side state management
This kind of mechanism retains state in the server.

Application State
The data stored in the application object can be shared by all the sessions of the application. Application object stores data in the key value pair.

Session State
Session State stores session-specific information and the information is visible within the session only. ASP.NET creates unique sessionId for each session of the application. SessionIDs are maintained either by an HTTP cookie or a modified URL, as set in the application’s configuration settings. By default, SessionID values are stored in a cookie.

Database
Database can be used to store large state information. Database support is used in combination with cookies or session state.

Q) Explain the difference between Server control and HTML control.

Answer: Server events
Server control events are handled in the server whereas HTML control events are handled in the page.

State management
Server controls can maintain data across requests using view state whereas HTML controls have no such mechanism to store data between requests.

Browser detection
Server controls can detect browser automatically and adapt display of control accordingly whereas HTML controls can’t detect browser automatically.

Properties
Server controls contain properties whereas HTML controls have attributes only.

Q) What are the validation controls available in ASP.NET?

Answer: ASP.NET validation controls are:

RequiredFieldValidator: This validates controls if controls contain data.

CompareValidator: This allows checking if data of one control match with other control.

RangeValidator: This verifies if entered data is between two values.

RegularExpressionValidator: This checks if entered data matches a specific format.

CustomValidator: Validate the data entered using a client-side script or a server-side code.

ValidationSummary: This allows developer to display errors in one place.

Q) Define the steps to set up validation control.

Answer: Following are the steps to set up validation control

Drag a validation control on a web form.
Set the ControlToValidate property to the control to be validated.
If you are using CompareValidator, you have to specify the ControlToCompare property.
Specify the error message you want to display using ErrorMessage property.
You can use ValidationSummary control to show errors at one place.

Q) What are the navigation ways between pages available in ASP.NET?

Answer: Ways to navigate between pages are:

Hyperlink control
Response.Redirect method
Server.Transfer method
Server.Execute method
Window.Open script method

Q) How do you open a page in a new window?

Answer: To open a page in a new window, you have to use client script using onclick="window.open()" attribute of HTML control.

Q) Define authentication and authorization.

Answer: Authorization: The process of granting access privileges to resources or tasks within an application.

Authentication: The process of validating the identity of a user.

Q) Define caching.

Answer: Caching is the technique of storing frequently used items in memory so that they can be accessed more quickly. Caching technique allows to store/cache page output or application data on the client on the server. The cached information is used to serve subsequent requests that avoid the overhead of recreating the same information. This enhances performance when same information is requested many times by the user.

Q) Define cookie.

Answer: A cookie is a small file on the client computer that a web application uses to maintain current session information. Cookies are used to identity a user in a future session.

Q) What is delegate?

Answer: A delegate acts like a strongly type function pointer. Delegates can invoke the methods that they reference without making explicit calls to those methods. It is type safe since it holds reference of only those methods that match its signature. Unlike other classes, the delegate class has a signature. Delegates are used to implement event programming model in .NET application. Delegates enable the methods that listen for an event, to be abstract.

Q) Explain Exception handling in .Net.

Answer: Exceptions or errors are unusual occurrences that happen within the logic of an application. The CLR has provided structured way to deal with exceptions using Try/Catch block. ASP.NET supports some facilities to handling exceptions using events suck as Page_Error and Application_Error.

Q) What is impersonation?

Answer: Impersonation means delegating one user identity to another user. In ASP.NET, the anonymous users impersonate the ASPNET user account by default. You can use <identity> element of web.config file to impersonate user. E.g. <identity impersonate="true"/>

Q) What is managed code in .Net?

Answer: The code that runs under the guidance of common language runtime (CLR) is called managed code. The versioning and registration problem which are formally handled by the windows programming are solved in .Net with the introduction of managed code. The managed code contains all the versioning and type information that the CLR use to run the application.

Q) What are Merge modules?

Answer: Merge modules are the deployment projects for the shared components. If the components are already installed, the modules merge the changes rather than unnecessarily overwrite them. When the components are no longer in use, they are removed safely from the server using Merge modules facility.

Q) What is Satellite assembly?

Answer: Satellite assembly is a kind of assembly that includes localized resources for an application. Each satellite assembly contains the resources for one culture.

 

Q) Define secured sockets layer.

Answer: Secured Socket Layer (SSL) ensures a secured web application by encrypting the data sent over internet. When an application is using SSL facility, the server generates an encryption key for the session and page is encrypted before it sent. The client browse uses this encryption key to decrypt the requested Web page.

Q) Define session in ASP.NET.

Answer: A session starts when the browser first request a resources from within the application. The session gets terminated when either browser closed down or session time out has been attained. The default time out for the session is 20 minutes.

Q) Define Tracing.

Answer: Tracing is the way to maintain events in an application. It is useful while the application is in debugging or in the testing phase. The trace class in the code is used to diagnose problem. You can use trace messages to your project to monitor events in the released version of the application. The trace class is found in the System.Diagnostics namespace. ASP.NET introduces tracing that enables you to write debug statements in your code, which still remain in the code even after when it is deployed to production servers.

Q) Define View State.

Answer: ASP.NET preserves data between postback events using view state. You can save a lot of coding using view state in the web form. ViewState serialize the state of objects and store in a hidden field on the page. It retains the state of server-side objects between postbacks. It represents the status of the page when submitted to the server. By default, view state is maintained for each page. If you do not want to maintain the ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control. ViewState exist for the life of the current page.

Q) What is application domain?

Answer: It is the process space within which ASP.NET application runs. Every application has its own process space which isolates it from other application. If one of the application domains throws error it does not affect the other application domains.

Q) List down the sequence of methods called during the page load.

Answer: Init() - Initializes the page.
Load() - Loads the page in the server memory.
PreRender() - the brief moment before the page is displayed to the user as HTML
Unload() - runs just after page finishes loading.

Q) What is the importance of Global.asax in ASP.NET?

Answer: The Global.asax is used to implement application and session level events.

Q) Define MSIL.

Answer: MSIL is the Microsoft Intermediate Language. All .Net languages' executable exists as MSIL which gets converted into machine specific language using JIT compiler just before execution.

Q) Response.Redirect vs Server.Transfer

Answer: Server.Transfer is only applicable for aspx files. It transfers page processing to another page without making round-trip back to the client's browser. Since no round trips, it offers faster response and doesn't update client url history list.

Response.Redirect is used to redirect to another page or site. This performs a trip back to the client where the client’s browser is redirected to the new page.

Q) Explain Session state management options in ASP.NET.

Answer: ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. Out-of-Process Session state management stores data in an external data source such as SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.

Q) How to turn off cookies for a page?

Answer: Cookie.Discard Property when true, instructs the client application not to save the Cookie on the user's hard disk when a session ends.

Q) How can you ensure a permanent cookie?

Answer: Setting Expires property to MinValue and restrict cookie to get expired.

Q) What is AutoPostback?

Answer: AutoPostBack automatically posts the page back to the server when state of the control is changed.

Q) Explain login control and form authentication.

Answer: Login controls encapsulate all the features offered by Forms authentication. Login controls internally use FormsAuthentication class to implement security by prompting for user credentials validating them.

Q) What is the use of Web.config file?

Answer: Following are the setting you can incorporate in web.config file.

Database connections
Error Page setting
Session States
Error Handling
Security
Trace setting
Culture specific setting

Q) Explain in what order a destructors is called.

Answer: Destructors are called in reverse order of constructors. Destructor of most derived class is called followed by its parent's destructor and so on till the topmost class in the hierarchy.

Q) What is break mode? What are the options to step through code?

Answer: Break mode lets you to observe code line to line in order to locate error. VS.NET provides following option to step through code.

Step Into
Step Over
Step Out
Run To Cursor
Set Next Statement

Q) Explain how to retrieve property settings from XML .config file.

Answer: Create an instance of AppSettingsReader class, use GetValue method by passing the name of the property and the type expected. Assign the result to the appropriate variable.

Q) Explain Global Assembly Cache.

Answer: Global Assembly Cache is the place holder for shared assembly. If an assembly is installed to the Global Assembly Cache, the assembly can be accessed by multiple applications. In order to install an assembly to the GAC, the assembly must have to be signed with strong name.

Q) Explain Managed code an Un-managed code.

Answer: Managed code runs under the safe supervision of common language runtime. Managed code carries metadata that is used by common language runtime to offer service like memory management, code access security, and cross-language accessibility.

Unmanaged code doesn't follow CLR conventions and thus, can't take the advantages of .Framework.

 

 

 

Q) What is side-by-side execution?

Answer: This means multiple version of same assembly to run on the same computer. This feature enables to deploy multiple versions of the component.

Q) Define Resource Files.

Answer: Resource files contains non-executable data like strings, images etc that are used by an application and deployed along with it. You can changes these data without recompiling the whole application.

Q) Define Globalization and Localization.

Answer: Globalization is the process of creating multilingual application by defining culture specific features like currency, date and time format, calendar and other issues. Localization is the process of accommodating cultural differences in an application.

Q) What is reflection?

Answer: Reflection is a mechanism through which types defined in the metadata of each module can be accessed. The System.Reflection namespaces contains classes that can be used to define the types for an assembly.

Q) Define Satellite Assemblies.

Answer: Satellite Assemblies are the special kinds of assemblies that exist as DLL and contain culture specific resources in a binary format. They store compiled localized application resources. They can be created using the AL utility and can be deployed even after deployment of the application. Satellite Assemblies encapsulate resources into binary format and thus makes resources lighter and consume lesser space on the disk.

Q) What is CAS?

Answer: CAS is very important part of .Net security system which verifies if particular piece of code is allowed to run. It also determines if piece of code have access rights to run particular resource. .NET security system applies these features using code groups and permissions. Each assembly of an application is the part of code group with associated permissions.

Q) Explain Automatic Memory Management in .NET.

Answer: Automatic memory management in .Net is through garbage collector which is incredibly efficient in releasing resources when no longer in use.

Q) Describe state management in ASP.NET.

Answer: State management is a technique to manage a state of an object on different request.
The HTTP protocol is the fundamental protocol of the World Wide Web. HTTP is a stateless protocol means every request is from new user with respect to web server. HTTP protocol does not provide you with any method of determining whether any two requests are made by the same person.
Maintaining state is important in any web application. There are two types of state management system in ASP.NET.
- Client-side state management
- Server-side state management

Q) Explain client side state management system.

Answer:  ASP.NET provides several techniques for storing state information on the client. These include the following:
- view state ASP.NET uses view state to track values in controls between page requests. It works within the page only. You cannot use view state value in next page.
- control state: You can persist information about a control that is not part of the view state. If view state is disabled for a control or the page, the control state will still work.
- hidden fields: It stores data without displaying that control and data to the user’s browser. This data is presented back to the server and is available when the form is processed. Hidden fields data is available within the page only (page-scoped data).
- Cookies: Cookies are small piece of information that server creates on the browser. Cookies store a value in the user’s browser that the browser sends with every page request to the web server.
- Query strings: In query strings, values are stored at the end of the URL. These values are visible to the user through his or her browser’s address bar. Query strings are not secure. You should not send secret information through the query string.

Q) Explain server side state management system.

Answer: The following objects are used to store the information on the server:
- Application State:
This object stores the data that is accessible to all pages in a given Web application. The Application object contains global variables for your ASP.NET application.
- Cache Object: Caching is the process of storing data that is used frequently by the user. Caching increases your application’s performance, scalability, and availability. You can catch the data on the server or client.
- Session State: Session object stores user-specific data between individual requests. This object is same as application object but it stores the data about particular user.

Q) Explain cookies with example.

Answer: A cookie is a small amount of data that server creates on the client. When a web server creates a cookie, an additional HTTP header is sent to the browser when a page is served to the browser. The HTTP header looks like this:
Set-Cookie: message=Hello. After a cookie has been created on a browser, whenever the browser requests a page from the same application in the future, the browser sends a header that looks like this:
Cookie: message=Hello
Cookie is little bit of text information. You can store only string values when using a cookie. There are two types of cookies:
- Session cookies 
- Persistent cookies.
A session cookie exists only in memory. If a user closes the web browser, the session cookie delete permanently.
A persistent cookie, on the other hand, can available for months or even years. When you create a persistent cookie, the cookie is stored permanently by the user’s browser on the user’s computer.
Creating cookie
protected void btnAdd_Click(object sender, EventArgs e) 
{
    Response.Cookies[“message”].Value = txtMsgCookie.Text; 
}
// Here txtMsgCookie is the ID of TextBox. 
// cookie names are case sensitive. Cookie named message is different from setting a cookie named Message.
The above example creates a session cookie. The cookie disappears when you close your web browser. If you want to create a persistent cookie, then you need to specify an expiration date for the cookie.
Response.Cookies[“message”].Expires = DateTime.Now.AddYears(1);
Reading Cookies
void Page_Load() 
{
if (Request.Cookies[“message”] != null) 
lblCookieValue.Text = Request.Cookies[“message”].Value; 
}
// Here lblCookieValue is the ID of Label Control.

65. Describe the disadvantage of cookies.

- Cookie can store only string value.
- Cookies are browser dependent.
- Cookies are not secure.
- Cookies can store small amount of data.

 

Q) What is Session object? Describe in detail.

Answer: HTTP is a stateless protocol; it can't hold the user information on web page. If user inserts some information, and move to the next page, that data will be lost and user would not able to retrieve the information. For accessing that information we have to store information. Session provides that facility to store information on server memory. It can support any type of object to store. For every user Session data store separately means session is user specific.
http://www.careerride.com/images/asp.net-interview-1.png
Storing the data in Session object.
Session [“message”] = “Hello World!”;
Retreving the data from Session object.
Label1.Text = Session[“message”].ToString();

Q) What are the Advantages and Disadvantages of Session?

Answer: Following are the basic advantages and disadvantages of using session.
Advantages:
·       It stores user states and data to all over the application.
·       Easy mechanism to implement and we can store any kind of object.
·       Stores every user data separately.
·       Session is secure and transparent from user because session object is stored on the server.
Disadvantages:
·       Performance overhead in case of large number of user, because of session data stored in server memory.
·       Overhead involved in serializing and De-Serializing session Data. Because In case of StateServer and SQLServer session mode we need to serialize the object before store.

Q) Describe the Master Page.

Answer: Master pages in ASP.NET works as a template that you can reference this page in all other content pages. Master pages enable you to define the look and feel of all the pages in your site in a single location. If you have done changes in master page, then the changes will reflect in all the web pages that reference master pages. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.
http://www.careerride.com/images/asp.net-interview-2.png
ContentPlaceHolder control is available only on master page. You can use more than one ContentPlaceHolder control in master page. To create regions that content pages can fill in, you need to define ContentPlaceHolder controls in master page as follows:
<asp:ContentPlaceHolder ID=”ContentPlaceHolder1” runat=”server”>
</asp:ContentPlaceHolder>
The page-specific content is then put inside a Content control that points to the relevant
ContentPlaceHolder:
<asp:Content ID=”Content1” ContentPlaceHolderID=”ContentPlaceHolder1” Runat=”Server”>
</asp:Content>


Note that the ContentPlaceHolderID attribute of the Content control points to the ContentPlaceHolder that is defined in the master page.
The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary .aspx pages.
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="CareerRide.master.cs" Inherits="CareerRide" %>

Q) How you can access the Properties and Controls of Master Pages from content pages?

Answer: You can access the Properties and Controls of Master Pages from content pages. In many situations you need User’s Name in different content pages. You can set this value inside the master page and then make it available to content pages as a property of the master page.
We will follow the following steps to reference the properties of master page from content pages.
Step: 1
Create a property in the master page code-behind file.
public String UserName 
{
get {
    return (String)Session["Name"];
}
set {
Session ["Name"] = value;
}
}
Step: 2
Add the @ MasterTypedeclaration to the .aspx content page to reference master properties in a content page. This declaration is added just below the @ Page declaration as follows:
<%@ Page Title=" TEST" Language="C#" MasterPageFile="~/CareerRide.master" AutoEventWireup="true" CodeFile="CareerRideWelcome.aspx.cs" Inherits="CareerRideWelcome" %>
<%@ MasterTypeVirtualPath="~/CareerRide.master" %>
Step: 3
Once you add the @ MasterType declaration, you can reference properties in the master page using the Master class. For example take a label control that id is ID="Label1"
Label1.Text= Master.UserName ;
For referencing controls in the Master Page we will write the following code.
Content Page Code.
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txtName= (TextBox)Master.FindControl("TextBox1");
Label1.Text=txtName.Text; 
}
To reference controls in a master page, call Master.FindControl from the content page.

Q) What are the different method of navigation in ASP.NET?

Answer: Page navigation means moving from one page to another page in your web site and another. There are many ways to navigate from one page to another in ASP.NET.
- Client-side navigation
- Cross-page posting
- Client-side browser redirect
- Client-Side Navigation
Client-side navigation:
Client-side navigation allows the user to navigate from one page to another by using client side code or HTML. It requests a new Web page in response to a client-side event, such as clicking a hyperlink or executing JavaScript as part of a button click.
Example:
Drag a HyperLink control on the form and set the NavigateUrl property to the desired destination page.
HyperLinkControl: Source
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Welcome.aspx"> Take a test from CareerRide </asp:HyperLink>
Suppose that, this control is placed on a Web page called CareerRide.aspx, and the HyperLink control is clicked, the browser simply requests the Welcome.aspx page.
Second method of client-side navigation is through JavaScript.
Example:
Take an HTML button control on web page. Following is the HTML code for the input button.
<input id="Button1" type="button" value="Go to next page" onclick="return Button1_onclick()" />
When the Button1 is clicked, the client-side method, Button1_onclick will be called. The JavaScript source for the Button1_onclick method is as follows:
<script language="javascript" type="text/javascript">
function Button1_onclick() 
{
document.location="NavigateTest2.aspx";
}
</script>
Cross-page posting:
Example:
Suppose that we have two pages, the first page is FirstPage.aspx and Second page is SecondPage.aspx. The First Page has a Button and TextBox control and its ID is Button1 and TextBox1 respectively. A Button control has its PostBackUrl property. Set this property to “~/SecondPage.aspx”. When the user clicks on Button, the data will send to SecondPage for processing. The code for SecondPage is as follows:
protected void Page_Load(object sender, EventArgs e)
{
if(Page.PreviousPage == null)
{
Label1.Text = "No previous page in post"; 
} 
else
{
Label1.Text = ((TextBox)PreviousPage.FindControl("TextBox1")).Text;
}
}
The second page contains a Label control and its ID is Label1.
The page that receives the PostBack receives the posted data from the firstpage for processing. We can consider this page as the processing page.The processing page often needs to access data that was contained inside the initial page that collected the data and delivered the PostBack. The previous page’s data is available inside the Page.PreviousPage property. This property is only set if a cross-page post occurs.
Client-side browser redirect:
The Page.Response object contains the Redirect method that can be used in your server-side code to instruct the browser to initiate a request for another Web page. The redirect is not a PostBack. It is similar to the user clicking a hyperlink on a Web page.
Example:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect ("Welcome.aspx"); 
}
In client-side browser redirect method an extra round trip to the server is happened.
Server-side transfer:
In this technique Server.Transfer method is used. The Transfer method transfers the entire context of a Web page over to another page. The page that receives the transfer generates the response back to the user’s browser. In this mechanism the user’s Internet address in his browser does not show the result of the transfer. The user’s address bar still reflects the name of the originally requested page.
protected void Button1_Click(object sender, EventArgs e) 
{ 
Server.Transfer("MyPage.aspx", false); 
}
The Transfer method has an overload that accepts a Boolean parameter called preserve-Form. You set this parameter to indicate if you want to keep the form and query string data.
Q) What does the Orientation property do in a Menu control?

Answer: Orientation property of the Menu control sets the display of menu on a Web page to vertical or horizontal.
Originally the orientation is set to vertical.

Q) Differentiate between: a.)Client-side and server-side validations in Web pages. And
b.)Authentication and authorization.

Answer:  a.)Client-side and server-side validations in Web pages.
- Client-side validations happends at the client's side with the help of JavaScript and VBScript. This happens before the Web page is sent to the server.
- Server-side validations occurs place at the server side.
b.)Authentication and authorization.
- Authentication is the process of verifyng the identity of a user using some credentials like username and password while authorization determines the parts of the system to which a particular identity has access.
- Authentication is required before authorization.

For e.g. If an employee authenticates himself with his credentials on a system, authorization will determine if he has the control over just publishing the content or also editing it.

 Q)a.) What does the .WebPart file do?

Answer:  It explains the settings of a Web Parts control that can be included to a specified zone on a Web page.
b.) How would you enable impersonation in the web.config file?
In order to enable the impersonation in the web.confing file, take the following steps:
- Include the <identity> element in the web.config file.
- Set the impersonate attribute to true as shown below:
<identity impersonate = "true" />

Q) a.) Differentiate between a.)File-based dependency and key-based dependency and
b.) Globalization and localization.?

Answer: a.)File-based dependency and key-based dependency.
- In file-based dependency, the dependency is on a file saved in a disk while in key-based dependency, you depend on another cached item.
b.) Globalization and localization.
- Globalization is a technique to identify the part of a Web application that is different for different languages and separate it out from the web application while in localization you try to configure a Web application so that it can be supported for a specific language or locale.

Q) a.)Differentiate between a page theme and a global theme?

Answer: - Page theme applies to a particular web pages of the project. It is stored inside a subfolder of the App_Themes folder.
- Global theme applies to all the web applications on the web server. It is stored inside the Themes folder on a Web server.
b.)What are Web server controls in ASP.NET?
- These are the objects on ASP.NET pages that run when the Web page is requested.
- Some of these Web server controls, like button and text box, are similar to the HTML controls.
- Some controls exhibit complex behavior like the controls used to connect to data sources and display data.

Q) a.) Differentiate between a HyperLink control and a LinkButton control.

Answer: - A HyperLink control does not have the Click and Command events while the LinkButton control has them, which can be handled in the code-behind file of the Web page.
b.) How do Cookies work? Give an example of their abuse.
- The server directs the browser to put some files in a cookie. All the cookies are then sent for the domain in each request.
- An example of cookie abuse could be a case where a large cookie is stored affecting the network traffic.

Q) a.) What are Custom User Controls in ASP.NET?

Answer: - These are the controls defined by developers and work similart to other web server controls.
- They are a mixture of custom behavior and predefined behavior.
b.) What is Role-based security?
- Used in almost all organization, the Role-based security assign certain privileges to each role.
- Each user is assigned a particular role from the list.
- Privileges as per role restrict the user's actions on the system and ensure that a user is able to do only what he is permitted to do on the system.

Q) What are the HTML server controls in ASP.NET?

Answer: - HTML server controls are similar to the standard HTML elements like those used in HTML pages.
- They expose properties and events for programatical use.
- To make these controls programmatically accessible, we specify that the HTML controls act as a server control by adding the runat="server" attribute.

Q) a.) What are the various types of Cookies in ASP.NET?

Answer: There exist two types of cookies in ASP.NET

- Session Cookie - It resides on the machine of the client for a single session and works until the user logs out of the session.
- Persistent Cookie - It resides on the machine of a user for a specified period. This period can be set up manually by the user.
b.) How would you turn off cookies on one page of your website?
- This can be done by using the Cookie.Discard property.
- It Gets or sets the discard flag set by the server.
- When set to true, this property instructs the client application not to save the Cookie on the hard disk of the user at the end of the session.
c.) How would you create a permanent cookie?
- Permanent cookies are stored on the hard disk and are available until a specified expiration date is reached.
- To create a cookie that never expires set its Expires property equal to DateTime.maxValue.

Q) a.) Explain Culture and UICulture values.

Answer: - Culture value determines the functions like Date and Currency used to format data and numbers in a Web page.
- UICulture value determines the resources like strings or images loaded in a Web application for a Web page.
b.) What is Global.asax file used for?
It executes application-level events and sets application-level variables.

Q) a.) Explain ASP.NET Web Forms.

Answer: - Web Forms are an extremely important part of ASP.NET.
- They are the User Interface (UI) elements which provide the desired look and feel to your web applications.
- Web Forms provide properties, methods, and events for the controls that are placed onto them.
b.) What is event bubbling?
- When child control send events to parent it is termed as event bubbling.
- Server controls like Data grid, Data List, and Repeater can have other child controls inside them.

Q) What are the various types of validation controls provided by ASP.NET?

Answer: ASP.NET provides 6 types of validation controls as listed below:

i.) RequiredFieldValidator - It is used when you do not want the container to be empty. It checks if the control has any value or not.

ii.) RangeValidator - It checks if the value in validated control is within the specified range or not.

iii.) CompareValidator - Checks if the value in controls matches some specific values or not.

iv.) RegularExpressionValidator - Checks if the value matches a specific regular expression or not.

v.) CustomValidator - Used to define User Defined validation.

vi.) Validation Summary -Displays summary of all current validation errors on an ASP.NET page.

Q) Differentiate between:

Answer: a.) Namespace and Assembly.
- Namespace is a naming convenience for logical design-time while an assembly establishes the name scope for types at run time.
b.) Early binding and late binding.
Early binding means calling a non-virtual method that is decided at a compile time while Late binding refers to calling a virtual method that is decided at a runtime.

Q) What are the different kinds of assemblies?

Answer: There can be two types of assemblies.

i.) Static assemblies -

- They are stored on disk in portable executable files.
- It includes .NET Framework types like interfaces and classes, resources for the assembly (bitmaps, JPEG files, resource files etc.).

ii.) Dynamic assemblies -

- They are not saved on disk before execution rather they run directly from memory.
- They can be saved to disk after they have been executed.



Q) Differentiate between Structure and Class.

Answer: - Structures are value type while Classes are reference type.
- Structures can not have constructor or destructors while Classes can have them.
- Structures do not support Inheritance while Classes do support Inheritance.

Q) Explain ViewState.

Answer: - It is a .Net mechanism to store the posted data among post backs.
- It allows the state of objects to be stored in a hidden field on the page, saved on client side and transported back to server whenever required.


Q) What are the various types of Authentication?

Answer: There are 3 types of Authentication namely Windows, Forms and Passport Authentication.

- Windows authentication - It uses the security features integrated in Windows NT and Windows XP OS to authenticate and authorize Web application users.

- Forms authentication - It allows you to create your own list of users and validate their identity when they visit the Web site.

- Passport authentication - It uses the Microsoft centralized authentication provider to identify users. Passport allows users to use a single identity across multiple Web applications. Passport SDK needs to be installed to use Passport authentication in your Web application.

Q) Explain Server-side scripting and Client-side scripting.

Answer: - Server side scripting - All the script are executed by the server and interpreted as needed.
- Client side scripting means that the script will be executed immediately in the browser such as form field validation, email validation, etc. It is usaullay carrried out in VBScript or JavaScript.

Q) a.) What is garbage collection?

Answer: It is a system where a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy.
b.) Explain serialization and deserialization.
- Serialization is the process of converting an object into a stream of bytes.
- Deserialization is the process of creating an object from a stream of bytes.

Both these processes are usually used to transport objects.

Q) What are the various session state management options provided by ASP.NET?

Answer:  - ASP.NET provides two session state management options - In-Process and Out-of-Process state management.
- In-Process stores the session in memory on the web server.
- Out-of-Process stores data in an external data source. This data source may be a SQL Server or a State Server service. Out-of-Process state management needs all objects stored in session to be serializable.

Q) Describe how Passport authentication works.

Answer: ASP.NET application with Passport authentication implemented checks the user’s machine for a current passport authentication cookie. If it is not available, ASP.NET directs the user to a Passport sign-on page. The Passport service authenticates the user, stores an authentication cookie on the user’s computer and direct the user to the requested page.  

Q)
Explain the steps to be followed to use Passport authentication.

Answer: 1. Install the Passport SDK.
2. Set the application’s authentication mode to Passport in Web.config.
3. Set authorization to deny unauthenticated users.
3. Use the PassportAuthentication_OnAuthenticate event to access the user’s Passport profile to identify and authorize the user.
4. Implement a sign-out procedure to remove Passport cookies from the user’s machine.

Q)
Explain the advantages of Passport authentication.

Answer:  User doesn’t have to remember separate user names and passwords for various Web sites
User can maintain his or her profile information in a single location.
Passport authentication also avail access to various Microsoft services, such as Passport Express Purchase.

Q) What is caching?

Answer:  Caching is the technique of storing frequently used items in memory so that they can be accessed more quickly.
By caching the response, the request is served from the response already stored in memory.
It’s important to choose the items to cache wisely as Caching incurs overhead.
A Web form that is frequently used and does not contain data that frequently changes is good for caching.
A cached web form freezes form’s server-side content and changes to that content do not appear until the cache is refreshed.

Q)
Explain the use of duration attribute of @OutputCache page directive.

Answer:  The @OutputCache directive’s Duration attribute determines how long the page is cached.
If the duration attribute is set to 60 seconds, the Web form is cached for 60 seconds; the server loads the response in memory and retains that response for 60 seconds.
Any requests during that time receive the cached response.
Once the cache duration has expired, the next request generates a new response and cached for another 60 seconds.



No comments:

Post a Comment