Get Paid By Click

Mginger Mobile Money

Jul 1, 2010

C#.Net Interview Questions and Answers

Which of the following causes theapplication Run method to end 
    a.A method
    b.An event
    c.The last line of code in the programe is reached
    d.It never ends
Ans: b
Which are the two different types of Exception classes supported in Winforms?
    a. System Exception
    b.Application Exception
    c.Answer a&b
    d :NoneOfAbnove
Ans: c
Is it possible to pass methods as arguments for other methods without modification.
     a false
     b true
     c mayb
 Ans:a
How do you prevent a class from being inherited in .NET?
     a Mark it as private internal.
     b Mark it as public.
     c Mark it as private.
     d Mark it as sealed.
     e Mark it as virtual.
 Ans:d
What is the base class for the system element hierarchy ?
    a CIM_LogicalElement
    b CIM_ManagedSystemElement
    c Win32_Process
    d Win32_NetworkAdapter
 Ans:b
Syntax for manual Garbage collector
    a gc.collect();
    b garbage.collect();
    c garbage();
    d none of the above
Ans:a
What’s the .NET datatype that allows the retrieval of data by a unique key?
    a.Heap
    b.Hash
    c.None of the above
Ans:b
Types of assembly
    a Private
    b Public/Shared
    c Satellite
    d All the above
 Ans:d
Can you have two files with the same file name in GAC?
    a Yes
    b  No
    c Can't Say
Ans:a
What’s an abstract class?
    a A class that cannot be instantiated
    b Is a class for which entities (instances) may be created
    c it can not be override
Ans:a
    Can you allow class to be inherited, but prevent the method from being over-ridden?
    a Yes
    b No
    c Never
Ans:a
just leave the class public and make the method sealed.
Can you prevent your class from being inherited and becoming a base class for some other classes?
    a Yes
    b No
    c Certain Condition
Ans:a
We have to use sealed keyword in the class definition
Which of the following is not a reference type?
     a class types
     b struct types
     c interface types
    d delegate types
Ans:b
Using which keyword we will be able to call base class functionality?
     a this
     b new
     c base
     d none
ans:c
What is boxing?
     a Encapsulating an object in a value type.
     b Encapsulating a copy of an object in a value type.
     c Encapsulating a value type in an object.
     d Encapsulating a copy of a value type in an object.
Ans:d
We have to use sealed keyword in the class definition
What’s the difference between and XML documentation tag?
     a.line code example and multiple-line code example
     b.line code example
     c.multiple-line code example
     d.None of the above 

ans:a
What’s the data provider name to connect to Access database?
     a Microsoft.Access
     b Microsoft.Office
     c Microsoft.Data
    d None of the above
Ans:a
Which of the following statement is tru about garbage collection?
    a In garbage collection the objects are not destroyed
    b In garbage collection the objects are destroyed every time
    c In garbage collection only unreferenced objects are destroyed
 Ans:c
Reference types are stored in
     a Heap
     b Stack
     c Both
     d None of above
Ans:a
Which class use to Read/Write data to memory
     a FileStream (Your selection was wrong)
     b NetworkStream
     c MemoryStream
 Ans:c
what is the default access modifier in c#?
     a public
     b private
     c internal
     d protected
Ans b
Which controls do not have events?
     a TextBox
     b ListBox
     c Treeview 

    d TimerControl
 Ans:d
Is String is Value Type or Reference Type in C#?
   a Value Type
   b Reference Type
   c Data Type
   d Value /Reference Type
Which of the following is not C# Keyword?
    a if
    b delegate
    c private
    d implements
ans:d
combobox also called as
     a dropdownlist
     b listbox
     c both1@2
     d none
What’s the top .NET class that everything is derived from?
    a System  b System.Object
    c System.Collections
    d System.Resources
   Ans:b
"System.Object" supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.
Which variable to access entire application to all users?
    a Session
    b ViewState
    c Application
   d Cookie
Ans:c
You need to create a simple class or structure that contains only value types. You must create the class or structure so that it runs as efficiently as possible. You must be able to pass the class or structure to a procedure without concern that the procedure will modify it. Which of the following should you create?
    a
A reference class
    b A reference structure
    c A value class  d A value structure
What is the correct order for Catch clauses when handling different exception types?
   a Order from most general to most specific.
   b Order from most likely to least likely to occur. (Your selection was wrong)
   c Order from most specific to most general.
   d Order from least likely to most likely to occur.
Ans:d
Which type of variable is not accesible in the derived class of same assembly?
   a internal
   b Public
   c Private
   d Protected
Ans:c
Which of the following type on inheritance C# will not support?
   a Multiple Inheritance
   b Multilevel Inheritance
   c Single Inheritance
   d Hierarchical Inheritance
Ans:a
bool data type in C# is
  a reference type
  b value type
  c Both A &amp  d None of the above
Ans:b
Defining two methods with the same name but with different parameters is called.
    a Loading
    b Multiplexing
    c Duplexing
    d Overloading
Ans:d

Attributes are
    a Used to provide extra information for the compiler
    b Return types
    c data types
Ans:a
Adatatype int in C# corresponds to a CTS type of
    a System.in
    b System.Long
    c System.int16
    d System.int32
 Ans:d
How can we define a two-dimensional array in  C#?
   a int [ , ] arrayObject;
   b int [ ] [ ] arrayObject;
   c int [ ] arrayObject
Ans:a
Which OOPS concept allows to extend the behaviour of base class?
  a Encapsulation
  b Polymorphism
  c Inheritance
 What is the function of a data adapter
  a Data Adapter is integral to the working of ADO.NET since data is transferred to and from a

  database through a data adapter
  b Its an object
  c Its a class
  d Interface
  e None
Ans:b
Which method is used to force the garbage collector?
  a System.GC.Collect()
  b Garbage.Collect
  c Gc.Clea.Up()
  d All of the above
Ans a
A structure in C# can be derived from one or more
  a class
  b interface
  c both
  d None
Ans:b
If a method is marked as "protected internal" then?
  a It can by accessable by Classes that are both in the same assembly and derived from the

  declaring class. (Your selection was wrong)
  b Accessable by Only methods that are in the same class as the method in question.
  c Accessable by Classes within the same assembly, and classes derived from the declaring

 Ans:c
What will be the output for the following: String str1="Hello";
String str2=str1;
str1=str1+"C#";
Console.WriteLine(str2);
  a Hello
  b HelloC#
  c Hello C#
  d HelloHelloC#
Ans: a
The classes related to ADO.NET are encapsulated in the namespace
  a System.Collections
  b System.Data
  c System.Type
  d System.IO
Ans:b
What happens when you include a Throw statement in the catch block?
  a Compilation Error
  b Current Exception is re-thrown
  c Runtime Error
  d Execution is abandoned
GetCustomAttributes method is available in which class?
  a MemberInfo
  b Attribute
  c Object
  d Type
Ans:a
which of the following c#.NET support
  a multiple Iplementation Iheritence
  b multiple Iterface Ineritence
  c Both
If I return out of a try/finally in C#, does the code in the finally-clause run?
  a Yes
  b No
  c Can't say
Ans:a
Integer i;
What will be the outcome of this declaration in C# ?
  a Syntax Error (Your selection was wrong)
  b Compilation Error
  c Both Syntax Error And Compilation Error
  d Run Time Error
  e None of these
Which one is correct to sort the elements of the array in descending order?
  a By calling Sort() and then Reverse() methods.
  b By Reverse() and then Sort() methods.
  c By calling Reverse() methods only.
  d None of the above
Object Oriented Programming (OOP) is a style of programming in which your code is broken

up into units, known as
  a objects
  b classes (Your selection was wrong)
  c objects or classes
  d objects and classes
What is CLR ?
  a Conventional Language Runtime
  b Clarified Language Runtime
  c Common Language Runtime
  d Colloquial Language Runtime
Ans:c
Which one performs a deep copy of the array?
  a System.Array.CopyTo()
  b System.Array.Clone()
  c Both
  d None of these
Ans:a
What is expansion of DLL?
  a Dynamic Link Library
  b Dynamic Linking Library
  c Data Linking Library
  d Data Link Library
Ans:a
Which namespace is used for event log support?
  a System.Diagnostics
  b System.IO
  c System.Net
  d System.Web
Ans:a
How does VB.NET/C# achieve polymorphism?
  a By using Interface classes. (Your selection was wrong)
  b By using struct.
  c By using Abstract classes/functions.
  d C#/VB.NET does not support polymorphism.
Ans:c
Is it possible to debug application from command line?
  a Yes (Your selection was wrong)
  b No
  c Yes, use cordbg .exe for that
  d Yes, use /debug option
private :
usable only by the class itself

public :
is visible to everyone. A public member can be accessed using an instance of a class

protected:
similar to private ones in that they are accessible only by the containing class. However,

protected members also may be used by a descendant class(same class and only derivedclass)

friend(vb)/internal(C#):
is public to the entire application but private to any outside applications. Internal is useful

when you want to allow a class to be used by other applications but reserve special

functionality for the application that contains the class(derived class for same application )

     Which OOPS concept allows to extend the behaviour of base class?
  a Encapsulation
  b Polymorphism
  c Inheritance
 What is the function of a data adapter
  a Data Adapter is integral to the working of ADO.NET since data is transferred to and from a

  database through a data adapter
  b Its an object
  c Its a class
  d Interface
  e None
Ans:b
Which method is used to force the garbage collector?
  a System.GC.Collect()
  b Garbage.Collect
  c Gc.Clea.Up()
  d All of the above
Ans a
A structure in C# can be derived from one or more
  a class
  b interface
  c both
  d None
Ans:b
If a method is marked as "protected internal" then?
  a It can by accessable by Classes that are both in the same assembly and derived from the

  declaring class. (Your selection was wrong)
  b Accessable by Only methods that are in the same class as the method in question.
  c Accessable by Classes within the same assembly, and classes derived from the declaring

 Ans:c
What will be the output for the following: String str1="Hello";
String str2=str1;
str1=str1+"C#";
Console.WriteLine(str2);
  a Hello
  b HelloC#
  c Hello C#
  d HelloHelloC#
Ans: a
The classes related to ADO.NET are encapsulated in the namespace
  a System.Collections
  b System.Data
  c System.Type
  d System.IO
Ans:b
What happens when you include a Throw statement in the catch block?
  a Compilation Error
  b Current Exception is re-thrown
  c Runtime Error
  d Execution is abandoned
GetCustomAttributes method is available in which class?
  a MemberInfo
  b Attribute
  c Object
  d Type
Ans:a
which of the following c#.NET support
  a multiple Iplementation Iheritence
  b multiple Iterface Ineritence
  c Both
If I return out of a try/finally in C#, does the code in the finally-clause run?
  a Yes
  b No
  c Can't say
Ans:a
Integer i;
What will be the outcome of this declaration in C# ?
  a Syntax Error (Your selection was wrong)
  b Compilation Error
  c Both Syntax Error And Compilation Error
  d Run Time Error
  e None of these
Which one is correct to sort the elements of the array in descending order?
  a By calling Sort() and then Reverse() methods.
  b By Reverse() and then Sort() methods.
  c By calling Reverse() methods only.
  d None of the above
Object Oriented Programming (OOP) is a style of programming in which your code is broken

up into units, known as
  a objects
  b classes (Your selection was wrong)
  c objects or classes
  d objects and classes
What is CLR ?
  a Conventional Language Runtime
  b Clarified Language Runtime
  c Common Language Runtime
  d Colloquial Language Runtime
Ans:c
Which one performs a deep copy of the array?
  a System.Array.CopyTo()
  b System.Array.Clone()
  c Both
  d None of these
Ans:a
What is expansion of DLL?
  a Dynamic Link Library
  b Dynamic Linking Library
  c Data Linking Library
  d Data Link Library
Ans:a
Which namespace is used for event log support?
  a System.Diagnostics
  b System.IO
  c System.Net
  d System.Web
Ans:a
How does VB.NET/C# achieve polymorphism?
  a By using Interface classes. (Your selection was wrong)
  b By using struct.
  c By using Abstract classes/functions.
  d C#/VB.NET does not support polymorphism.
Ans:c
Is it possible to debug application from command line?
  a Yes (Your selection was wrong)
  b No
  c Yes, use cordbg .exe for that
  d Yes, use /debug option



 AccessModifier
 private :
 usable only by the class itself
public :
is visible to everyone. A public member can be accessed using an instance of a class


protected:
similar to private ones in that they are accessible only by the containing class. However,
protected members also may be used by a descendant class(same class and only derivedclass)

friend(vb)/internal(C#):
is public to the entire application but private to any outside applications. Internal is useful
when you want to allow a class to be used by other applications but reserve special
functionality for the application that contains the class(derived class for same application )


 


what is an Interface?
·    The interface is defined as a set of methods (Sub and Function routines), properties (Property routines), events, and fields (variables or attributes) that are declared Public in scope.
·        Interface looks like a class, but has no implementation. The code inside of a method is called the implementation.
·        All the methods of Interface are public by default and no access modifiers (like private, public) are allowed with any method of Interface.
·        Interfaces may also inherit other interfaces

Which one is similar to Delegates?
         A  Interface in Java
         B  pointer in C or C++
         C  function pointer in C or C++
Ans:C
Unboxing of a null reference type will return a null.
         A true
         B false
         C an exception is thrown
Ans:C
In C# a technique used to stream the data is known as
         A Wading
         B Serialization
         C Crunching
         D Marshalling
Ans:B
In C# a technique used to stream the data is known as
        A Wading
        B Serialization
        C Crunching
        D Marshalling
Ans:B
In the following cases which is not function overloading
        A Same parameter types but different return values
        B Varying number of parameters
        C Different parameters types but different return values
        D Different parameters type but same return values
Ans:A
What is an indexer in C#
        A Special syntax for overloading [ ] operator for a class 
        B One which speeds up the function call (Your selection was wrong)
        C System.Int64
       D  Both A & B
Ans:A
The C# keyword int maps to which .NET type
       A System.Int16
       B System.Int32
       C System.Int64
Ans:B
Which of the following causes the application Run method to end
        A A method
        B An event 
        C The last line of code in the program is reached
        D It never ends
Ans:B
Which one is true?
       A  System is a class
       B  System is a data member
       C  System is a name space 
       D  System is type
Ans:C
Which of the following is not a keyword in c#
       A  protect
       B  abstract
       C  private
       D  public
Ans:A
Is delegate a type safe function pointer
       A yes 
       B no
       C Cannot say
Ans:A
can we run ASP.NET 1.1 application and ASP.NET 2.0 application on same computer
yes
can we use break statement in finally block
      A yes
      B no 
      C Can't say
Ans:B
what is the implicit name of parameter that GETS passed into class
       A Value
       B Variable
       C Constant
       D None of Above
Ans:A
In order to use String Builder in class we need to refer
       A System. String
       B System. Text
      C Both 1 & 2
      D None
What are used to store generic data types
     A BLOB
     B Collections 
     C Both a and b
Ans:B
Which statement is true
     A  Operations on String objects takes more time than String Builder objects 
     B Operations on String Builder objects takes more time than String objects
     C Both takes same time
Which of the following statements about static class is not correct?
     Static classes only contain static members.
     B Static classes cannot be instantiated.
     C Static classes are not sealed .  
Ans:C

ABSTRACT CLASS
Ø      In C#, multiple inheritances might become difficult to handle because it allows ambiguity for the compiler
Ø      An abstract class is a parent class that allows inheritance but can never be instantiated.  Abstract classes contain one or more abstract methods that do not have implementation.  Abstract class can contain abstract methods, abstract property as well as other members (just  like normal class).
Ø      An abstract class cannot be a sealed class
Ø      An abstract method cannot be private.
Ø      The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
Ø      An abstract member cannot be static.
Ø      The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.
Ø      A class can inherit one or more interfaces, but only one abstract class.
Ø      abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overridden in the child class as well, using the override keyword. Read example below
Ø      Interface can only contain abstract methods, properties.

Example: Abstract Class with Abstract method
namespace Automobiles
{
            public abstract class Vehicle
            {
                         public abstract void Speed() //No Implementation here, only definition
            }
}

Example: Abstract Class with Virtual method
namespace Automobiles
{
            public abstract class Vehicle
            {
                         public virtual void Speed() //Can have an implementation, that may be overriden in child class
                        {
                                     ...
                        }
 }

Public class Car : Vehicle
{
Public override void Speed()
//Here, we override whatever implementation is there in the abstract class
{
                                     ... //Child class implementation of the method Speed()
 }
}
}


Ø      An Interface is a collection of semantically related abstract members.
Ø      An interface expresses through the members it defines, the behaviors that a class needs to support.
Ø      An interface is defined using the keyword interface.
Ø      The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below:

Public interface IVehicle //As a convention, an interface is prefixed by letter I
{
            Boolean HasFourWheels()
}


Time to discuss the Difference between Abstract Class and Interface

·        A class may inherit only one abstract class, but may implement multiple number of Interfaces. 
·        Members of an abstract class may have any access modifier, but members of an interface are public by default, and cannot have any other access modifier.
·        Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation


Ø      The class System. Environment is used to retrieve information about the operating system. Some of the static members of this class are as follows:
Ø      Environment.OSVersion - Gets the version of the operating system
Ø      Environment.GetLogicalDrives() - method that returns the drives
Ø      Environment. Version - returns the .NET version running the application

How to declare a constant variable in C#? What is the use of the const keyword?

If a variable needs to have a fixed value, that may not be changed across the application's life, then it may be declared with the const keyword.
            The value assigned to a constant variable (using the const keyword) must be known at the time of    
            compilation.
Can multiple data types be stored in System.Array?
 No.
 It is thus, stored in the form of a heap in the memory.
C# Example
int[] testIntArray = new int[4] { 2, 3, 4, 5 };
Object[] testObjArray = new Object[5] { 32, 22, 23, 69, 75 };


Whats the use of "throw" keyword in C#?
The throw keyword is used to throw an exception programatically in C#. In .NET, there is an in-built technique to manage & throw exceptions. In C#, there are 3 keyword, that are used to implement the Exception Handling. These are the try, catch and finally keywords. In case an exception has to be implicitly thrown, then the throw keyword is used. See code example below, for throwing an exception programatically...

C# Example
class SomeClass
{
public static void Main()
{
 try
                        {
                                    throw new DivideByZeroException("Invalid Division Occured");
                        }
 catch(DivideByZeroException e)
                        {
                                      Console.WriteLine("Exception - Divide by Zero" );
 }
}
}

How to achieve polymorphism in C#?
In C#, polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types,
How to prevent a class from being inherited? Sealed in C#?

In order to prevent a class in C# from being inherited, the sealed keyword 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. Code below...

C# Example
sealed class ClassA
{
public int x;
public int y;
}

No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible...

class DerivedClass: ClassA {} // Error

What is the use of the main() function in C#?
Every executable C# application must contain a class defining a Main() method that signifies the entry point of the application. Note that the Main() method is of the access type public by nature. Moreover, it is also static. See example below:

C# Example
using System;
class Question
{
 public static int Main(string[] args)
            {
  Console.Writeline("Another Question");
  Console.Readline();
  return 0;
            }
}

A public member is accessible from other types. The main() method is set as static so that it may be invoked at class level itself, without the need of creating an instance of it. The single parameter is an array of strings. that may contain any number of incoming command line arguments.

What is a Base Class?
A Base Class is a class that is inherited by another class. In .NET, a class may inherit from only one class.

Encapsulation - is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs.

Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class.

What is inheritance?
Inheritance - is the concept of passing the traits of a class to another class.
What is the virtual keyword used for?
Virtual - If a base class method is to be overriden, it is defined using the keyword virtual
What is the difference between Shared and Static?
They both mean the same. Shared is used in VB.NET. Static is used in C#.
When the static keyword is used to declare a class, the member in context must be directly invoked from the class, rather than from the instance.
What is a constructor? Explain the New Keyword. What is a Private Constructor?
Constructor - A constructor is a function with the same name as that of the class. The Default Constructor of a class is without an argument. The default constructor ensures that every member data is initialized to a default value. Constructors provide a way for classes to initialize a state for their members. Note that constructors dont have a return type(not even void).

public SomeClass()
{
Console.Writeline("Vishal says, Default Constructor is called");
}
\
public SomeClass(string str)
{
Console.Writeline("Vishal says, Custom Constructor is called" + str);
}


When a custom constructor is defined, the Default Constructor is not called. A constructor may also be overloaded.

New - This keyword may be used as a modifier and as an operator. When used as an operator, it creates an object on a heap to invoke constructors. When used an a modifier, it hides an inherited member from the base class member.

As an operator, it can be used to create an object and then to invoke the constructor of the class. See example below.

Example
SomeClass objSomeClass = new SomeClass(); //Creating a class object and invoking its constructor

float amount = new float(); //Creating an object of the type, and invoking its constructor

As a modifier, it is used to explicitly hide a member from the base class. See example.

Example
public class MamaClass
{
public void SomeMethod() { ... }
}

public class BabyClass : MamaClass
{
new public void SomeMethod() { .... }
}

what is Static Constructors in c#
Static data members can certainly be initialized at the time of their declaration but there are times when value of one static member may depend upon the value of another static member. In such cases we definitely need some mechanism to handle conditional initialization of static members. To handlesuch situation, C# provides static constructor.
While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class

What is Serialization? What is serializable attribute used for?
Serialization - The process of converting an object into a stream of bytes.  Deserialization is an opposite process, which involves converting a stream of bytes into an object. Serialization is used usually during remoting (while transporting objects) and to persist file objecst & database objects.

.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter
What is Serialization? What is serializable attribute used for?

Serialization - The process of converting an object into a stream of bytes. This stream of bytes can be persisted. Deserialization is an opposite process, which involves converting a stream of bytes into an object. Serialization is used usually during remoting (while transporting objects) and to persist file objecst & database objects.

.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter
SoapFormatter enables us to serialize & deserialize objects to SOAP format.
The BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format

Is it possible to inline assembly or IL in C# code?
 No

 Is it possible to have a static indexer in C#? allowed in C#.
 No. Static indexers are not

 If  I return out of a try/finally in C#, does the code in the finally-clause run?
Yes. The code in the finally always runs. If you return out of the try block, or even if you do a goto out of the try, the finally block always runs:
Are private class-level variables inherited?
Yes, but they are not accessible.  Although they are not visible or accessible via the class interface, they are inherited.
Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the specified base class.

What’s the top .NET class that everything is derived from?
System.Object.

What does the term mutable mean?
The data value may not be changed.  Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable.  System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation.  Strings are immutable, so each time a string is changed, a new instance in memory is created.

Can you store multiple data types in System.Array?
No.

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array.  The CopyTo() method copies the elements into another existing array.  Both perform a shallow copy.  A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array.  A deep copy (which neither of these methods performs) would create a new instance of each element’s object, resulting in a different, yet identacle object.

How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.

What class is underneath the SortedList class?
A sorted HashTable.

Will the finally block get executed if an exception has not occurred?­
Yes.

What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception.  You can also omit the parameter data type in this case and just write catch {}.

Can multiple catch blocks be executed for a single try statement?
No.  Once the proper catch block processed, control is transferred to the finally block (if there are any).

Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).

What is the syntax to inherit from a class in C#?

Place a colon and then the name of the base class.
Example: class MyNewClass : MyBaseClass

Can you prevent your class from being inherited by another class?
Yes.  The keyword “sealed” will prevent the class from being inherited.

Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes.  Just leave the class public and make the method sealed.

What’s an abstract class?
A class that cannot be instantiated.  An abstract class is a class that must be inherited and have the methods overridden.  An abstract class is essentially a blueprint for a class without any implementation.

When do you absolutely have to declare a class as abstract?
1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
2.  When at least one of the methods in the class is abstract.

What is an interface class?
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.

Can you inherit multiple interfaces?
Yes.  .NET does support multiple interfaces.

What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
To Do: Investigate

What’s the difference between an interface and abstract class?
In an interface class, all methods are abstract – there is no implementation.  In an abstract class some methods can be concrete.  In an interface class, no accessibility modifiers are allowed.  An abstract class may have accessibility modifiers.

What is the difference between a Struct and a Class?
Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval.  Another difference is that structs cannot inherit.

Method and Property Questions

1What’s the implicit name of the parameter that gets passed into the set method/property of a class?
Value.  The data type of the value parameter is defined by whatever data type the property is declared as.

2. What does the keyword “virtual” declare for a method or property?
The method or property can be overridden.

3. How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply involves having another method with the same name within the class.

4. Can you declare an override method to be static if the original method is not static?
No.  The signature of the virtual method must remain the same.  (Note: Only the keyword virtual is changed to keyword override)

5. What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of parameters.

6. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

Events and Delegates

1. What’s a delegate?
A delegate object encapsulates a reference to a method.

2. What’s a multicast delegate?
A delegate that has multiple handlers assigned to it.  Each assigned handler (method) is called.

XML Documentation Questions

1. Is XML case-sensitive?
Yes.

2. What’s the difference between // comments, /* */ comments and /// comments?
Single-line comments, multi-line comments, and XML documentation comments.

3. How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with the /doc switch.

Debugging and Testing Questions

1. What debugging tools come with the .NET SDK?
1.   CorDBG – command-line debugger.  To use CorDbg, you must compile the original C# file using the /debug switch.
2.   DbgCLR – graphic debugger.  Visual Studio .NET uses the DbgCLR.

2. What does assert() method do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false.  The program proceeds without any interruption if the condition is true.

3. What’s the difference between the Debug class and Trace class?
Documentation looks the same.  Use Debug class for debug builds, use Trace class for both debug and release builds.

4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose.  For applications that are constantly running you run the risk of overloading the machine and the hard drive.  Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.

5. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.

6. How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.

7. What are three test cases you should go through in unit testing?
1.       Positive test cases (correct data, correct output).
2.       Negative test cases (broken or missing data, proper handling).
3.       Exception test cases (exceptions are thrown and caught properly).

8. Can you change the value of a variable while debugging a C# application?
Yes.  If you are debugging via Visual Studio.NET, just go to Immediate window.

ADO.NET and Database Questions

1. What is the role of the DataReader class in ADO.NET connections?
It returns a read-only, forward-only rowset from the data source.  A DataReader provides fast access when a forward-only sequential read is needed.

2.   What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix.  OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.

3. What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

4. Explain ACID rule of thumb for transactions.
A transaction must be:
1.       Atomic – it is one unit of work and does not dependent on previous and following transactions.
2.       Consistent – data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.
3.       Isolated – no transaction sees the intermediate results of the current transaction).
4.       Durable – the values persist if the data had been committed even if the system crashes right after.

5. What connections does Microsoft SQL Server support?
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).

6. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

7. What does the Initial Catalog parameter define in the connection string?
The database name to connect to.

8. What does the Dispose method do with the connection object?
Deletes it from the memory.
To Do: answer better.  The current answer is not entirely correct.

9. What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.  The connection string must be identical.

Assembly Questions

1. How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

2. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.


3. What is a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

4. What namespaces are necessary to create a localized application?
System.Globalization and System.Resources.

5. What is the smallest unit of execution in .NET?
an Assembly.

6. When should you call the garbage collector in .NET?
As a good rule, you should not call the garbage collector.  However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory.  However, this is usually not a good practice.

7. How do you convert a value-type to a reference-type?
Use Boxing.

8. What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the heap.  Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its super classes.

If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package access. This means that the class can only be accesse
 Prefix and Postfix notation
Both the ++ and -. operators can be used as prefix or postfix operators. In prefix form:
num1 = 3;
num2 = ++num1; // num1 = 4, num2 = 4
The compiler will first increment num1 by 1 and then will assign it to num2. While in postfix form:
num2 = num1++; // num1 = 4, num2 = 3
The compiler will first assign num1 to num2 and then increment num1 by 1.
There is a concept of "operator precedence" in C#. For example:
int i = 2 + 3 * 6;
// i would be 20 not 30
3 will be multiplied by 6 first then the result will be added to 2
d by other classes and interfaces that are defined within the same package.


3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer (BAL) or Business Logic Layer and Data Access Layer (DAL).

Presentation Layer (UI)
Presentation layer cotains pages like .aspx or windows form where data is presented to the user or input is taken from the user.

Business Access Layer (BAL) or Business Logic Layer
BAL contains business logic, validations or calculations related with the data
Data Access Layer (DAL)
DAL contains methods that helps business layer to connect the data and perform required action, might be returning data or manipulating data (insert, update, delete etc).

Data Access Layer (DAL)

Code for Data Access Layer

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

    public class PersonDAL3
    {
 string connStr = ConfigurationManager.ConnectionStrings["TutTestConn"].ToString();
        public PersonDAL3()
        {


        }
        /// Used to insert records into database

        public int Insert(string firstName, string lastName, int age)
        {

            SqlConnection conn = new SqlConnection(connStr);

            conn.Open();

            SqlCommand dCmd = new SqlCommand("InsertData", conn);

            dCmd.CommandType = CommandType.StoredProcedure;

            try

            {

                dCmd.Parameters.AddWithValue("@firstName", firstName);

                dCmd.Parameters.AddWithValue("@lastName", lastName);

                dCmd.Parameters.AddWithValue("@age", age);

                return dCmd.ExecuteNonQuery();

            }
            catch
            {

                throw;

            }
            finally
            {

                dCmd.Dispose();

                conn.Close();

                conn.Dispose();
            }

        }
        public int Update(int personID, string firstName, string lastName, int age)

        {

            SqlConnection conn = new SqlConnection(connStr);

            conn.Open();

            SqlCommand dCmd = new SqlCommand("UpdateData", conn);

            dCmd.CommandType = CommandType.StoredProcedure;

            try

            {

                dCmd.Parameters.AddWithValue("@firstName", firstName);

                dCmd.Parameters.AddWithValue("@lastName", lastName);

                dCmd.Parameters.AddWithValue("@age", age);

                dCmd.Parameters.AddWithValue("@personID", personID);

                return dCmd.ExecuteNonQuery();

            }

            catch

            {

                throw;

            }

            finally

            {

                dCmd.Dispose();

                conn.Close();

                conn.Dispose();

            }

        }
        /// Load all records from database

        ///

        public DataTable Load()

        {

            SqlConnection conn = new SqlConnection(connStr);

            SqlDataAdapter dAd = new SqlDataAdapter("LoadAll", conn);

            dAd.SelectCommand.CommandType = CommandType.StoredProcedure;

            DataSet dSet = new DataSet();

            try

            {

                dAd.Fill(dSet, "PersonTable");

                return dSet.Tables["PersonTable"];

            }

            catch

            {

                throw;

            }

            finally

            {

                dSet.Dispose();

                dAd.Dispose();

                conn.Close();

                conn.Dispose();

            }

        }




        /// Delete record from database

        public int Delete(int personID)
        {

            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();
            SqlCommand dCmd = new SqlCommand("DeleteData", conn);
           dCmd.CommandType = CommandType.StoredProcedure;

            try

            {
                dCmd.Parameters.AddWithValue("@personID", personID);

                return dCmd.ExecuteNonQuery();
            }
            catch

            {
                throw;
            }
            finally

            {
                dCmd.Dispose();
                conn.Close();
                conn.Dispose();

            }

        }



    }

Now, create a class named PersonBAL3 into App_Code folder by right clicking it and write respective methods for calling Insert, Delete, Update and Load methods of Data Access Layer class file (PersonDAL3) (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for BAL and add reference of this project into your Presentation Layer). As we don't have any business logic here so simply instantiate the PersonDAL3 class of DAL and call methods. Below is the code for BAL (Your can overwrite your default written code for the class file by pasting this code).

Code for Business Access Layer

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;



    ///

    /// Summary description for PersonBAL3

    ///

    public class PersonBAL3

    {

        public PersonBAL3()

        {



       }




        /// insert records into database

        ///

        ///

        ///

        ///

        ///

        public int Insert(string firstName, string lastName, int age)

        {

            PersonDAL3 pDAL = new PersonDAL3();

            try

            {

                return pDAL.Insert(firstName, lastName, age);

            }

            catch

            {

                throw;

            }

            finally

            {

                pDAL = null;

            }

        }



        ///

        /// Update records into database

        ///

        ///

        ///

        ///

        ///

        ///

        public int Update(int personID, string firstName, string lastName, int age)

        {

            PersonDAL3 pDAL = new PersonDAL3();

            try

            {

                return pDAL.Update(personID, firstName, lastName, age);

            }

            catch

            {

                throw;

            }

            finally

            {

                pDAL = null;

            }

        }



        ///

        /// Load records from database

        ///

        ///

        public DataTable Load()

        {

            PersonDAL3 pDAL = new PersonDAL3();

            try

            {

                return pDAL.Load();

            }

            catch

            {

                throw;

            }

            finally

            {

                pDAL = null;

            }

        }



        ///

        /// Delete record from database

        ///

        ///

        ///

        public int Delete(int personID)

        {

            PersonDAL3 pDAL = new PersonDAL3();

            try

            {

                return pDAL.Delete(personID);

            }

            catch

            {

                throw;

            }

            finally

            {

                pDAL = null;

            }

        }



    }


Till now we haev our Business Access Layer and Database Access Layer ready. Now we have to write our Presentation Layer that will use our Business Access Layer methods. Lets create a form that will have three textboxes for FirstName, LastName and Age.

Presentation Layer




Create an Insert.aspx page (make is as Startup page) and copy paste following code to bring the insert form something like displaying in the picture.
Code for Insert Record form

Now, lets write method that will fire when Submit button will be clicked on the from.
Code for AddRecords method

protected void AddRecords(object sender, EventArgs e)

    {

        //Lets validate the page first

        if (!Page.IsValid)

            return;



        int intResult = 0;

        // Page is valid, lets go ahead and insert records

        // Instantiate BAL object

        PersonBAL3 pBAL = new PersonBAL3();

        // Instantiate the object we have to deal with

        string firstName = txtFirstName.Text;

        string lastName = txtLastName.Text;

        int age = Int32.Parse(txtAge.Text);

       

        try

        {

            intResult = pBAL.Insert(firstName, lastName, age);

            if (intResult > 0)

                lblMessage.Text = "New record inserted successfully.";

            else

                lblMessage.Text = "FirstName ["+ txtFirstName.Text +"] alredy exists, try another name";



        }

        catch (Exception ee)

        {

            lblMessage.Text = ee.Message.ToString();

        }

        finally

        {

            pBAL = null;

        }       

    }

By using 3-Tier architecture in your project you can achive

1. Seperation - the functionality is seperated from the data access and presentation so that it is more maintainable
2. Independence - layers are established so that if one is modified (to some extent) it will not affect other layers.
3. Reusability - As the layers are seperated, it can exist as a module that can be reused by other application by referencing it.

‘Namespace’ – a keyword in .NET is used to avoid name collisions i.e. For example, you
develop a library which has a class named “File” and you use some other library which
also has a class named “File”, in those cases there are chances of name collision. To
avoid this you can give a namespace name for your class, which should be meaningful. It
is always better to follow the syntax (MS Recommended) given below while giving
names for your namespaces

When you execute your Application "Main" method is called first automatically.

Assembly
An assembly is a grouping of files deployed as a single file. An assembly almost always
consists of at least two files: the executable and the manifest. The manifest is a list of all
the files that exist inside the assembly. The executable content inside the assembly is
referred to individually as a module. Conceptually, modules correspond to DLLs or
EXEs; each module contains metadata, in addition to the metadata of its parent assembly.
The assembly format is an enhanced version of the current Portable Executable (PE)
format (your normal Windows .EXE file format).

The .NET Runtime ships with a Just-In-Time (JIT or JITter) compiler, which will convert
the MSIL code in to the native code (CPU Specific executable code.

Simple or value type variables are those, which are assigned space in the stackt.All the primitive types such as int, double etc are value type variables
The first rule of value types is that they cannot be null. you declare a variable of
value type, you have allocated the number of bytes associated with that type on the stack
and are working directly with that allocated array of bits
Object Type
Object type or reference type variables are those, which are allocated storage space in the
heap. Reference type objects can be null. When a reference type is allocated under the
covers a value is allocated on the heap and a reference to that value is returned. There are
basically four reference types: classes, interfaces, delegates and arrays.
Class Type
Custom data types are available in .NET framework in the form of classes or class type. It
is nothing but a set of data and related behavior that is defined by the developer.
Object type and class type are both reference type variables. The only difference comes
from the fact that object type consists of objects predefined and available with the .NET
framework such as string whereas class type consists of custom user defined data types
such as the class employee

Overloading
Overloading provides the ability to create multiple methods or properties with the same
name, but with different parameters lists.

Overriding
Class inheritance causes the methods and properties present in the base class also to be
derived into the derived class. A situation may arise wherein you would like to change
the functionality of an inherited method or property. In such cases we can override the
method or property of the base class. This is another feature of polymorphism.

Properties
Properties are named members of classes, structs, and interfaces. They provide a flexible
mechanism to read, write, or compute the values of private fields through accessors.
Properties are an extension of fields and are accessed using the same syntax. Unlike
fields, properties do not designate storage locations. Instead, properties have accessors
that read, write, or compute their values.

Structures
v      A structure allows you to create your own custom data types and it contains one or more
v      members that can be of different data types. It can contain fields, methods, etc.
v      cannot initialize structure members.
v      cannot inherit a structure whereas classes can be inherited.
v      structures differentiating it from classes is that a structure can't have a default parameter-less constructor or a destructor.
v      A structure is created on the stack .
v      most important differences between structures and classes is that structures are referenced by value and classes by reference
v      As a value type, allocated on the stack, structs provide a significant opportunity to increase program efficiency.
v      Objects on the stack are faster to allocate and de-allocate
v      A struct is a good choice for data-bound objects, which don’t require too much memory.
v      the size of memory available on the stack is limited than the memory available on the heap.
v      Thus we must use classes in situations where large objects with lots of logic are required.

A class can also be
defined as a programmatic representation of an entity and the behavior of that
entity can be represented by the functions in the class

Encapsulation directly leads to two main advantages:
Data Hiding: -- The user of the class does not come to know about the internals
of the class. Hence, the user never comes to know about the exact data
members in the class. The user interacts with the data members only through the
various member functions provided by the class.
Data Security: - Since the data, members are not directly available to the user
directly but are available only through the member functions a validity check can
always be imposed to ensure that only valid data is been inserted into the class.
So a Date class, which contains individual data members for storing date, month
and year, will have it ensured the month is never 13 or the date is never
exceeding 31.

Early Vs Late Binding
In case of early binding, the compiler knows the object's data type at compile time and
hence can directly compile code to invoke the methods on the object. This enables the
compiler to discover the appropriate method and ensure that the referenced method does
exist and the parameters provided are in sync with that of the referenced method.
In case of late binding, the compiler cannot determine the object's data type and thus the
code interacts with the object dynamically at runtime. To make an object late-bound, it is
defined as a variable of type Object.

Inheritance
directly results in the following benefits: --
Reusability: -- Inheritance results in functionalities defined in one class being
reused in the derived classes. So the efforts of rewriting the same functionality
for every derived class is being saved. This definitely saves a lot of development
time.
Enhancement and Specification: -- Due to the characteristic of inheritance, we can club the common functionalities in the base class and have the specific functionalities in the derived class.
This feature can be used to have a functionality defined in the base class to be further modified for betterment or specification by the derived class.
This mechanism of redefining the functionality of the base class in the derived class is termed as “overriding”

Difference between Module and Assembly
A module is a .exe or .dll file. An assembly is a set of one or more modules that together make up an application.

Static members                                     Non static members
Do not require an object instance              Require an object instance

Are termed as class level                               Are termed as object level
Members                                                          members


Static functions do not receive                    Non static functions do receive
the “this” pointer as an implicit                     the “this” pointer as an implicit
argument                                                        member


Can access only other static and                Can access both static as well as
not the non static members              non static members

System.Object:- This is the root class for all the objects in the .NET framework,
from which all the other classes are derived. It contains some basic methods and
properties, which can be accessed from all the object instances of the .NET
framework.


In Microsoft .NET, when an application is compiled, the output of the compilation
produces what is known as an Assembly. Two types of assemblies can be produced by the
compilation procedure. One is the executable file (*.exe) and the other is a dynamic link
library file (*.dll). Basically the assembly is the unit of deployment in Microsoft .NET
and it can be thought of as a collection of types and resources that form a logical unit of
functionality.
An assembly is a self-describing entity. It contains all information about the types
(classes) contained in the assembly, all external references needed for executing the
assembly and so on. This is possible with an assembly manifest. The manifest contains
assembly’s identity and version information, a file table containing all files that make up
the assembly and the assembly reference list for all external dependencies. Thus
assemblies do not need to depend on the registry values for compilation or execution.

Private Assemblies
A private assembly is an assembly that is deployed with an application and is available
only for that application. That is, other applications do not share the private assembly.
Private assemblies are installed in a folder of the application's directory structure.
Typically, this is the folder containing the application's executable file.

A shared assembly is an assembly available for use by multiple applications on the
computer. To make the assembly global, it has to be put into the Global Assembly Cache.
Each computer where the common language runtime is installed has a machine-wide
code cache called the global assembly cache. The global assembly cache stores
assemblies specifically for sharing by several applications on the computer.
You should share assemblies by installing them into the global assembly cache only
when you need to. As a general guideline, keep assembly dependencies private and locate
assemblies in the application directory unless sharing an assembly is explicitly required.
This is achieved with the help of a global assembly cache tool (gacutil.exe) provided by
the .NET Framework. One can also drag & drop the assemblies into the Global Assembly
Cache directory.

 However, when an assembly has to be put into the Global Assembly Cache it needs to be
signed with a strong name. A strong name contains the assembly's identity i.e. it’s text
name, version number, and culture information strengthened by a public key and a digital
signature generated over the assembly. This is because the CLR verifies the strong name
signature when the assembly is placed in the Global Assembly Cache.















































Easy Way To Pay

Sign up for PayPal and start accepting credit card payments instantly.

Earn While Searching