.NET Framework faqs

Q - What is the .NET Framework?
The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class libraries, and unifying components.
The CLR is the module that actually runs your .NET applications. When you create a .NET application, what really happens is that your code is compiled into the CLR’s Intermediate Language (named MSIL, or IL in short). When you run application, that IL code is translated into the binary code your computer can understand by some compilers built into the CLR. Compilers translate your code into something that your machine’s hardware or other software can deal with directly.
The .NET Class Library is a collection of hundreds of classes and objects that can be used from any .NET programming language. The .NET Class Library models the services that the .NET Framework and underlying operating system provide, establishing an easy to understand and consistent approach to taking advantage of system services regardless of what programming language you use. Some examples of the tasks you can perform using the .NET Class Library include: creating applications with a graphical interface, processing files, working with XML, debugging, working with security sub-systems, and more.
The unifying components of the .NET Framework bring the other key elements of the .NET Framework together based on two distinct applications models:
 Windows Forms

ASP.NET provides a Web-based application model in the form of components and controls that make it easy to build Web applications and Web Services. ASP.NET exposes a common set of controls to developers including buttons, text boxes, and other controls. ASP.NET controls reside on the server and enable developers to work with them without regard to where the controls get rendered (delivered) - making developing Web-based applications much easier. ASP.NET controls render themselves based on the capabilities of the browser that's accessing an ASP.NET page.

Windows Forms provide a rich user experience by exposing a common set of controls to all .NET programming languages making it easy to build "traditional" windows applications (applications that, in large part, execute on a user's system and have a graphical interface).

Q - What is the common language runtime (CLR)?
The common language runtime is the execution engine for .NET Framework applications. It provides a number of services, including the following:
 Code management (loading and execution)
 Application memory isolation
 Verification of type safety
 Conversion of IL to native code
 Access to metadata (enhanced type information)
 Managing memory for managed objects
 Enforcement of code access security
 Exception handling, including cross-language exceptions
 Interoperation between managed code, COM objects, and pre-existing DLLs (unmanaged code and data)
 Automation of object layout
 Support for developer services (profiling, debugging, and so on)

Q - What is the common type system (CTS)?
The common type system is a rich type system, built into the common language runtime that supports the types and operations found in most programming languages. The common type system supports the complete implementation of a wide range of programming languages.

Q - What is the Common Language Specification (CLS)?
The Common Language Specification is a set of constructs and constraints that serves as a guide for library writers and compiler writers. It allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The Common Language Specification is a subset of the common type system. The Common Language Specification is also important to application developers who are writing code that will be used by other developers. When developers design publicly accessible APIs following the rules of the CLS, those APIs are easily used from all other programming languages that target the common language runtime.

Q - What is the Microsoft Intermediate Language (MSIL)?
MSIL is the CPU-independent instruction set into which .NET Framework programs are compiled. It contains instructions for loading, storing, initializing, and calling methods on objects. Combined with metadata and the common type system, MSIL allows for true cross-language integration. Prior to execution, MSIL is converted to machine code. It is not interpreted.

Q - What is Metadata used for?
A - Metadata is used to represent information to locate and load classes, to lay out instances of these classes in memory, to resolve method invocations, to translate IL code to native code, to enforce security and to setup runtime context boundaries. Metadata is done by C#'s code-to-IL compiler (not JIT compiler)

Q - What is managed code and managed data?
Managed code is code that is written to target the services of the common language runtime. In order to target these services, the code must provide a minimum level of information (metadata) to the runtime. All C#, VB.NET, and JScript.NET code is managed by default. C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/CLR).
Closely related to managed code is managed data—data that is allocated and de-allocated by the common language runtime's garbage collector. C#, VB.NET, and JScript.NET data is managed by default. C# data can, however, be marked as unmanaged through the use of special keywords. C++ data is unmanaged by default (even when using the /CLR switch), but when using Managed Extensions for C++, a class can be marked as managed by using the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector. In addition, the class becomes a full participating member of the .NET Framework community, with the benefits and restrictions that brings. An example of a benefit is proper interoperability with classes written in other languages (for example, a managed C++ class can inherit from a Visual Basic class). An example of a restriction is that a managed class can only inherit from one base class.

Q - What is an application domain?
An application domain (often AppDomain) is a virtual process that serves to isolate an application. All objects created within the same application scope (in other words, anywhere along the sequence of object activations beginning with the application entry point) are created within the same application domain. Multiple application domains can exist in a single operating system process, making them a lightweight means of application isolation.
An OS process provides isolation by having a distinct memory address space. While this is effective, it is also expensive, and does not scale to the numbers required for large web servers. The Common Language Runtime, on the other hand, enforces application isolation by managing the memory use of code running within the application domain. This ensures that it does not access memory outside the boundaries of the domain. It is important to note that only type-safe code can be managed in this way (the runtime cannot guarantee isolation when unsafe code is loaded in an application domain).

Q – What is a Process?
A - Each application that is executed has its own 'process space' in the operating system. A Process is an isolated area of memory specifically set aside for that application to be executed in. A Thread on the other hand is a single unit that executes within a process and more specifically by which the operating system allocates processor time. A process will always have at least one thread running in it but it is possible for a process to contain multiple threads that execute simultaneously.

Q - What is garbage collection?
Garbage collection is a mechanism that allows the computer to detect when an object can no longer be accessed. It then automatically releases the memory used by that object (as well as calling a clean-up routine, called a "finalizer," which is written by the user). Some garbage collectors like the one used by .NET, compact memory and therefore decrease your program's working set.

Q - Can I use COM objects from a .NET Framework program?
A - Yes. Any COM component you have deployed today can be used from managed code, and in common cases the adaptation is totally automatic.
Specifically, COM components are accessed from the .NET Framework by use of a runtime callable wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET Framework-compatible interfaces. For OLE automation interfaces, the RCW can be generated automatically from a type library. For non-OLE automation interfaces, a developer may write a custom RCW and manually map the types exposed by the COM interface to .NET Framework-compatible types. (Use tlbimp.exe)

Q - Can .NET Framework components be used from a COM program?
A - Yes. Managed types you build today can be made accessible from COM, and in the common case the configuration is totally automatic. There are certain new features of the managed development environment that are not accessible from COM. For example, static methods and parameterized constructors cannot be used from COM. In general, it is a good idea to decide in advance who the intended user of a given type will be. If the type is to be used from COM, you may be restricted to using those features that are COM accessible. Depending on the language used to write the managed type, it may or may not be visible by default.
Specifically, .NET Framework components are accessed from COM by using a COM callable wrapper (CCW). This is similar to an RCW, but works in the opposite direction. Again, if the .NET Framework development tools cannot automatically generate the wrapper, or if the automatic behavior is not what you want, a custom CCW can be developed. (Use regasm.exe or tlbexp.exe)

Q - Can I use the Win32 API from a .NET Framework program?
A - Yes. Using platform invoke, .NET Framework programs can access native code libraries by means of static DLL entry points. Here is an example of C# calling the Win32 MessageBox function:
using System;
using System.Runtime.InteropServices;

class MainApp
[DllImport("user32.dll", EntryPoint="MessageBox")]
public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType);

public static void Main()
MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 );

Q – What are Configuration Files?
A - The .Net Framework provides a very convenient and flexible way to configure applications at run time. Using Configuration files developers and administrators can modify settings for applications without having to recompile the application, avoiding many of the redistribution /re-deployment hassles. For example, if you specify the connection string to be used for database connectivity to an application in the configuration files or an update path for the latest version, you will find configuration files make your application more adaptable. Configuration files contain settings for ASP.Net, built-in remoting channels, assembly binding, custom settings for applications, etc.
Configuration files are XML files that contain the configuration settings. There are three types of configuration files as described below

1. Machine configuration file: The machine.config file contains settings that apply to the entire computer. This file is located in the %runtime install path%\Config directory. There is only one machine.config file on a computer.

2. Application Configuration file: The name of this file depends on the application’s host. For ASP.Net applications, this file is called web.config and is located in application root. An ASP.Net application can contain more than one web.config files at sub-directory level.
For applications hosted by the executable host, the config file has the same name as the application, with a .config extension and is located in the same directory as the application. Internet Explorer hosted applications specify the name and location of the config file in a link tag.

3. Security Configuration file: These configuration files contain information about the code group hierarchy and permission sets for policy levels. There are three levels of security configuration files: Enterprise policy configuration file (Enterprisesec.config), Machine policy configuration file (Security.config) and User policy configuration file (Security.config). Note that you have to be extra careful while editing these files as changes might corrupt the security configurations.


Q - Is C# an object-oriented language?
A - Yes. C# provides language support for the so-called "Three Pillars of Object Oriented Programming": encapsulation, polymorphism, and inheritance (or reusability). OOP is a way of modeling software that maps your code to the real world. Instead of creating programs with global data and modular functions, you create programs with “classes”. A class is a software construct that maps to real world things and ideas. An object is an instance of a class.

Q – Why is System.Object class - the base of all classes?
A - In C# (and the .NET framework) all the types (classes, structures and interfaces) are implicitly inherited from the Object class defined in the System namespace. This class provides the low-level services and general functionality to each and every class in the .NET framework. The Object class is extremely useful when it comes to polymorphism, as a reference of type Object can hold any type of object.

Q -How many classes can a single .NET DLL contain?
A - Many. Yes an assembly can contain one or more classes and an assembly can be contained in one dll or could spread across multiple dlls too. Take System.dll, it is collections of many classes.

Q - How does C# achieve polymorphism?
A - Polymorphism is achieved through virtual, overloaded, overridden methods in C#.

Q – What are the different types of overloading possible in C#?
A –
modifier returntype methodname(int a, int b)
modifier returntype methodname(int a, string b)
modifier returntype methodname(string a, int b)
modifier returntype methodname(string a, int b, int c)

Overloading cannot be achieved by different return types. It is not sufficient for two methods to differ only by virtue of a parameter having been declared as ref or out.

Q – What do you mean by Runtime Polymorphism?
A - Methods are invoked on references to objects. Typically, those references are stored in reference variables, or in the elements of a collection such as an array or a hashtable. With runtime polymorphism based on method overriding, the decision as to which version of a method will be executed is based on the actual type of the object whose reference is stored in the reference variable or element, and not on the type of the reference variable or element on which the method is invoked. Here is an operational description of runtime polymorphism as implemented in C# through inheritance and method overriding:
 Assume that a class named SuperClass defines a method named method.
 Assume that a class named SubClass extends SuperClass and overrides the method named method.
 Assume that a reference to an object of the class named SubClass is assigned to a reference variable named ref of type SuperClass.
 Assume that the method named method is then invoked on the reference variable using the following syntax: ref.method()
 Result: The version of the method named method that will actually be executed is the overridden version in the class named SubClass, and is not the version that is defined in the class named SuperClass.
This is runtime polymorphism.

Q - What's the difference between a structure and a class?
A - Structs may seem similar to classes, but there are important differences that you should be aware of.
 First of all, classes are reference types and structs are value types.
 Structs do not support inheritance for structs. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherits from the base class “object”. A struct can implement interfaces, and it does that exactly as classes do.
 Structs can declare constructors, but they must take parameters. It is an error to declare a default (parameterless) constructor for a struct. Struct members cannot have initializers. A default constructor is always provided to initialize the struct members to their default values.
 When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator. If you do not use New, the fields will remain unassigned and the object cannot be used until all the fields are initialized.

Q – List the different types of class constructors in C#
A – There are three types of class constructors as discussed:
Type of class constructor Comments
Instance Used to create and initialize instances of the class.
Private A special type of instance constructor that is not accessible outside the class. A class cannot be instantiated using a private constructor.
Static Called automatically to initialize the class before the first instance is created or any static members are referenced. The constructor cannot be called directly.
A static constructor does not take access modifiers or have parameters. The user has no control on when the static constructor is executed in the program. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Q – What are the different Data Types supported by C#?
A - Data Types can be of two different types – value types and reference types. Value Types are used to address primitive or basic data types, such as char, int, float, and so on. Reference types encompass all other items like class, interfaces, delegates, and arrays. The main difference between the value-type and the reference-type is that of the manner in which these data-types are stored in the memory, and later used in the program. The value-types are stored on the Stack (first-in, Last-out), instead reference-types (object) are stored on the Heap, but their reference (object reference) is stored on the Stack. The value-type are passed by the copy of their value, so any change in the copy of value does not effect the original value, instead reference-types are passed by the copy of reference, so any change will effect the original object.

Q - Can we override properties and apply polymorphism on these?
A - No! We can't. Properties are just accessors to fields and as we can't apply polymorphism on fields we also can't apply polymorphism on properties.

Q - How is a property designated as read-only?
A - If it has only get accessor.
public class abc
private string stringIt="This is the string";
public string StringIt
get{return stringIt;}
But you could set an attribute prior to the property name with [ReadOnly="true"], if that property defined an attribute.

Q - We saw that constructors are called in the order from the top to the bottom (parent to child class) in inheritance hierarchy. In which order are the destructors called during inheritance?
A - The destructors are called in the reverse order, i.e., from the bottom to the top (child to parent class) in the inheritance hierarchy.

Q - What is the difference between const and static readonly?
A - The difference is that static readonly can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static readonly case a bit, the containing class can only modify it:
 in the variable declaration (through a variable initializer)
 in the static constructor (instance constructors if it's not static)

Q - What is a Static Field or Method?
A - Declaring a field or method with the static key word associates it with the class itself, not with instances of the class (object). In a sense, static or "class" fields and methods are global variables and methods that you can touch using the class name. There is only one copy of the static fields and methods in memory, shared by all instances of the class.
Static fields are useful when you want to store state related to all instances of a class. A counter is a good example of a static field. In fact, you can use a static field to keep track of how many objects have been created from a particular class
Static methods are useful when you have behavior that is global to the class and not specific to an instance of a class. It's important to know that static methods cannot directly access non-static members (you cannot call a non-static method from a static method). Instead, they must instantiate an object and use the members of that object to access non-static members.

Q - What's the difference between an abstract method and a virtual method?
A - A class can declare a method as abstract method - this way it does not need to provide an implementation of that method. An abstract method is implicitly also a virtual method, though it cannot have the modifier virtual. Virtual method has a definition in the base class, but this implementation can be superseded by derived classes by overriding the method.

Q – What do you mean by Boxing and Unboxing?
A - Boxing means converting value types to reference types, and unboxing goes vice versa i.e. from boxed reference type to value type.
Boxing is done implicitly by the CLR that is a conversion from value type to reference type. This is done where a reference type data is required and we pass a value type data. When this is a case, value type data is associated with a reference and that reference is copied to the Heap. A typical example is Console.WriteLine() that expects a reference type as a parameter. When we pass a value type to this method, that value type is boxed into object type automatically by calling appropriate ToString() method. Example: -
int i = 5;
// boxing into object
object obj = i; // implicit

Unboxing is done explicitly. CLR required explicit coding for unboxing. There are two things specially care for: -
 Make sure object instance is a boxed value
 Copy value to the value type explicitly
int i = 5;
object obj = i; // implicit boxing
// unboxing
int k = (int) obj; // explicit unboxing

Q – What is a Heap?
A – A heap is an area of memory used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order and the pattern of allocation and size of blocks is not known until run time. Typically, a program has one heap which it may use for several different purposes.

Q - Abstract classes may contain constructors. When we can't instantiate the abstract classes, what is the use of these constructors?
A - A constructor of a class is not only called when its object is instantiated; it also gets called when an object of its subclass is created. So, an abstract class may contain a constructor to be called when it subclass is instantiated.

Q - I've heard that Finalize methods should be avoided. Should I implement Finalize on my class?
A - An object with a Finalize method is more work for the garbage collector than an object without one. Also there are no guarantees about the order in which objects are Finalized, so there are issues surrounding access to other objects from the Finalize method. Finally, there is no guarantee that a Finalize method will get called on an object, so it should never be relied upon to do clean-up of an object's resources. Microsoft recommends the following pattern:
public class CTest : IDisposable
public void Dispose()
... // Cleanup activities

~CTest() // C# syntax hiding the Finalize() method

In the normal case the client calls Dispose(), the object's resources are freed, and the garbage collector is relieved of its Finalizing duties by the call to SuppressFinalize(). In the worst case, i.e. the client forgets to call Dispose(), there is a reasonable chance that the object's resources will eventually get freed by the garbage collector calling Finalize(). Given the limitations of the garbage collection algorithm this seems like a pretty reasonable approach.

Q - What is the difference between Dispose and Finalize?
A - The Dispose() method should be called by the consumer as soon as the resources used by the object are no longer required. The Garbage Collector automatically calls the Finalize method and we cannot predict when it will be called.

Q - Is there a way to force garbage collection?
A - Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed and System.GC.Collect() doesn't seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().

Q – What do you mean by Reflection?
A – Reflection is a runtime process by which information can be determined about assemblies and the types of objects they contain.

Q – What do you mean by Globalization?
A - The process of creating software that can be used by multiple locales.

Q – What do you mean by Delegates?
A - A delegate is a reference type that refers to a Shared method of a type or to an instance method of an object. The closest equivalent of a delegate in other languages is a function pointer, but whereas a function pointer can only reference Shared functions, a delegate can reference both Shared and instance methods. In the latter case, the delegate stores not only a reference to the method's entry point, but also a reference to the object instance with which to invoke the method.

Q – What is the difference between Delegates and Interfaces?
A - Delegates and interfaces are similar in that they enable the separation of specification and implementation. Multiple independent authors can produce implementations that are compatible with an interface specification. Similarly, a delegate specifies the signature of a method, and authors can write methods that are compatible with the delegate specification.
Delegates are useful when:
 A single method is being called.
 A class may want to have multiple implementations of the method specification.
 It is desirable to allow using a static method to implement the specification.
 An event-like design pattern is desired (for more information, see the Events Tutorial).
 The caller has no need to know or obtain the object that the method is defined on.
 The provider of the implementation wants to "hand out" the implementation of the specification to only a few select components.
 Easy composition is desired.

Interfaces are useful when:
 The specification defines a set of related methods that will be called.
 A class typically implements the specification only once.
 The caller of the interface wants to cast to or from the interface type to obtain other interfaces or classes.

Q - What do U mean by Side-by-Side execution of DLL in .NET?
A - Side-by-side execution is the ability to run multiple versions of the same assembly simultaneously.

Q - How do U use VB.NET DLL file in C#?
A - Directly. Use reference

Q - Can U inherit 2 classes in C#?
A - No. C# does not support multiple inheritances.

Q - What does tlbimp.exe create?
A - Metadata of DLL.

Q - How do you use COM in Managed code?
A - Using Runtime Callable Wrapper (RCW)

Q - What class is used to create COM+ component?
A - System.EnterpriseService

Q – What do you mean by Incompatibility in Assembly?
A - Difference in either major or minor number indicates incompatibility.

Q - State which is true
A - A single assembly may contain types whose hierarchical names have different namespace roots, and a logical namespace root may span multiple assemblies

Q - What is the name of destructor in .NET?
A – Finalizer.

Q - How do U declare event?
A - public static event EName;

Q - Let's say I have an existing application written using Visual Studio 6 and this application utilizes Windows 2000 COM+ transaction services. How would you approach migrating this application to .NET?
A. You have to use System.EnterpriseServices namespace and also COMInterop the existing application.

Q - What are attributes?
A - An attribute is a powerful feature that is attached to a target programming element (e.g., a class, method, assembly, interface, etc.) to customize behaviors or extract organizational information of the target at design, compile, or runtime. An attribute is applied to the target by specifying the attribute name in brackets as shown below.
This attribute is applied to a class stating that objects of this class can be serialized. When the compiler encounters this attribute, it adds suitable instructions in the metadata.
There are thousands of pre-defined attributes in FCL. In addition to them .NET allows us to define our own attributes, called ‘custom attributes’.

Q - Can I create my own metadata attributes?
A - Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example:
public class InspiredByAttribute : System.Attribute
public string InspiredBy;

public InspiredByAttribute( string inspiredBy )
InspiredBy = inspiredBy;

[InspiredBy(".NET FAQ")]
class CTest{}

class CApp
public static void Main()
object[] atts = typeof(CTest).GetCustomAttributes(true);
foreach( object att in atts )
if( att is InspiredByAttribute )
Console.WriteLine( "Class CTest was inspired by {0}", ((InspiredByAttribute)att).InspiredBy);

Q - How do I stop a thread in C#?
A - There are several options. First, you can use your own communication mechanism to tell the ThreadStart method to finish. Alternatively the Thread class has in-built support for instructing the thread to stop. The two principle methods are Thread.Interrupt() and Thread.Abort(). The former will cause a ThreadInterruptedException to be thrown on the thread when it next goes into a WaitJoinSleep state. In other words, Thread.Interrupt is a polite way of asking the thread to stop when it is no longer doing any useful work. In contrast, Thread.Abort() throws a ThreadAbortException regardless of what the thread is doing. Furthermore, the ThreadAbortException cannot normally be caught (though the ThreadStart's finally method will be executed). Thread.Abort() is a heavy-handed mechanism which should not normally be required.

Q - How do I use the thread pool?
A - By passing an instance of a WaitCallback delegate to the ThreadPool.QueueUserWorkItem() method:
class CApp
static void Main()
string s = "Hello, World";
ThreadPool.QueueUserWorkItem( new WaitCallback( DoWork ), s );
Thread.Sleep( 1000 ); // Give time for work item to be executed

// DoWork is executed on a thread from the thread pool.
static void DoWork( object state )
Console.WriteLine( state );

Q - How do I know when my thread pool work item has completed?
A - There is no way to query the thread pool for this information. You must put code into the WaitCallback method to signal that it has completed. Events are useful for this.

Q – What do you mean by XMLDataDocument?
A - XMLDataDocument is based on the standard Document Object Model (DOM) that gives you the power to load, manipulate, and save XML documents through code. The XMLDataDocument object can be used to represent the same data as the DataSet can. The difference between the two representations is the structure; a DataSet is represented as a relational structure, while the XMLDataDocument represents data as a hierarchical structure.

Q - When you inherit a protected class-level variable, who is it available to?
A - Classes in the same namespace.

Q - Are private class-level variables inherited?
A - Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

Q - Describe the accessibility modifier protected internal.
A - It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).

Q - C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?
A - Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

Q - Can you declare the override method static while the original method is non-static?
A - No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

Q - Can you override private virtual methods?
A - No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

Q - Can you prevent your class from being inherited and becoming a base class for some other classes?
A - Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName.

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

Q - What if the class implementing multiple interfaces they have conflicting method names?
A - 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.

Q - What is the difference between the value-type variables and reference-type variables in terms of garbage collection?
A - The value-type variables are not garbage-collected, they just fall off the stack when they fall out of scope, the reference-type objects are picked up by GC when their references go null.

Q – Does the following code execute successfully?
using System;
namespace Polymorphism
class A
public void Foo() { Console.WriteLine("A::Foo()"); }

class B : A
public void Foo() { Console.WriteLine("B::Foo()"); }

class Test
static void Main(string[] args)
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "A::Foo()"
A - Although the code compiles and runs, the compiler produces a warning:
...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()

# Any delegate that is declared as public void is a multicast delegate.
# The immediate window will allow you to set the value of a variable during execution
# IComparer supports sorting
# IDictionary supports key/value
# IEnumerable supports foreach
# IDictionary Enumerator supports foreach with dictionary

## When a class implements an interface, subclasses of that class can override the methods to provide different implementations. In other way, when an interface method is mapped onto a virtual method in a class, it is possible for derived classes to override the virtual method and alter the implementation of the interface.
interface IControl
void Paint();
class Control: IControl
public virtual void Paint() {...}
class TextBox: Control
public override void Paint() {...}

## A class that inherits an interface implementation is permitted to re-implement the interface by including it in the base class list. A re-implementation of an interface follows exactly the same interface mapping rules as an initial implementation of an interface. For example, in the declarations
interface IControl
void Paint();
class Control: IControl
void IControl.Paint() {...}
class MyControl: Control, IControl
public void Paint() {}
the fact that Control maps IControl.Paint onto Control.IControl.Paint doesn't affect the re-implementation in MyControl, which maps IControl.Paint onto MyControl.Paint.


Q - What is the difference between ASP and ASP.NET?
A - The Runtime
ASP.NET works through the .NET runtime. ASP runs through a special DLL designed to interpret VB script for IIS. ASP.NET, on the other hand, works through IL code and the .NET framework. In practical terms, this means that ASP.NET can interact with a far larger variety of programs in a much simpler and more reliable fashion. For example, you don't have to reboot IIS every time you recompile your ActiveX objects. In fact, ActiveX objects are replaced with assemblies and can be built in any of the .NET languages.

The Language(s)
In traditional ASP, you could use VB script, which is a type-less language. In ASP.NET, you must use one of the .NET languages. The primary difference is that all of the .NET languages are strongly typed. That is, you can't work with variants or "unknown" data types. You must work explicitly with strings, numbers and integers. Another notable difference is that ASP was traditionally programmed in a combination of VBScript, JScript and JavaScript, with occasional calls to a compiled COM component or ActiveX control. ASP.NET, however, can be programmed directly in VB.NET, or C#, and much of the JScript or JavaScript code is written for you through the use of "drag and drop" elements.

Other new features include complex validation controls. The controls automatically create code for validating the presence and nature of information entered into a web form. Tired of rewriting the expression checker to ensure that the user has typed in a proper social security number? The validation control can do it for you. These controls will perform server side and/or client side validation. The summary control will also display a nicely formatted report of any missing or incorrect information on the web form.

When a function is declared in ASP.net it must appear in a );

protected override void Render (HtmlTextWriter writer)
StringBuilder builder = new StringBuilder ();

builder.Append (" builder.Append (_Text);
builder.Append ("\" onclick=\"javascript:__doAlert (\'");
builder.Append (Message);
builder.Append ("\');\" />");
writer.Write (builder.ToString ());

If the control's register tag prefix is win, then the following statement declares an AlertButton control that, when clicked, displays "Hello, world" in a message box:

The control uses RegisterClientScriptBlock to register the client-side script block that it returns. That script block contains the __doAlert function referenced by the tag's onclick attribute. It's returned only once no matter AlertButtons a page contains. RegisterClientScriptBlock should always be called from the control's OnPreRender method so ASP.NET can control the script's position in the output.

Q - The ASP.NET application cache doesn't have Lock and UnLock methods as application state does. Does this mean I never need to lock it?
A - No. It means you have to come up with your own mechanism for locking. System.Threading.ReaderWriterLock is the perfect tool for the job. Assuming rwlock is an instance of ReaderWriterLock, here's how you'd lock the application cache during an update:
rwlock.AcquireWriterLock (Timeout.Infinite);
Cache["ItemsSold"] = (int) Cache ["ItemsSold"] + 1;
Cache["ItemsLeft"] = (int) Cache ["ItemsLeft"] - 1;
rwlock.ReleaseWriterLock ();

And here's how you'd read "ItemsSold" and "ItemsLeft" values from the cache:
rwlock.AcquireReaderLock (Timeout.Infinite);
int sold = (int) Cache["ItemsSold"];
int left = (int) Cache ["ItemsLeft"];
rwlock.ReleaseReaderLock ();

As with application state, locking the application cache is only necessary when performing multistep updates that are to be treated as atomic operations.

Q - What does AspCompat="true" mean and when should I use it?
A - AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but should be set to true in any ASPX file that creates apartment-threaded COM objects, i.e. COM objects registered ThreadingModel=Apartment. AspCompat should also be set to true (regardless of threading model) if the page creates COM objects that access intrinsic ASP objects such as Request and Response. The following directive sets AspCompat to true:
<%@ Page AspCompat="true" %>
Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available to the COM components by placing unmanaged wrappers around the equivalent ASP.NET objects. Second, it improves the performance of calls that the page places to apartment-threaded COM objects by ensuring that the page (actually, the thread that processes the request for the page) and the COM objects it creates share an apartment. AspCompat="true" forces ASP.NET request threads into single-threaded apartments (STAs). If those threads create COM objects marked ThreadingModel=Apartment, then the objects are created in the same STAs as the threads that created them. Without AspCompat="true," request threads run in a multithreaded apartment (MTA) and each call to an STA-based COM object incurs a performance hit when it's marshaled across apartment boundaries.
Do not set AspCompat to true if your page uses no COM objects or if it uses COM objects that don't access ASP intrinsic objects and that are registered ThreadingModel=Free or ThreadingModel=Both.

Q - If I use the same user control in two different pages and include a @OutputCache directive in the ASCX file, will the user control be cached once or twice?
A - In ASP.NET version 1.0, the control will be cached twice. In version 1.1, you can include a Shared="true" attribute in the @ OutputCache directive to cache the control just once.

Q - How does System.Web.UI.Page's IsPostBack property work? How does it determine whether a request is a postback?
A - IsPostBack checks to see whether the HTTP request is accompanied by postback data containing a __VIEWSTATE or __EVENTTARGET parameter. No parameters, no postback.

Q - Running ASP.NET on a Web farm requires you to configure each server to use identical validation and encryption keys. Is there a tool available for producing those keys?
You can get the tool you're looking for right here. KeyGen is a command-line utility for producing validation and encryption keys of any length. Click here to download it, and here to download the C# source code. To run it, simply type KeyGen followed by a key length in bytes. The following command produces a 24-byte key:
keygen 24

KeyGen uses the .NET Framework Class Library's System.Security.Cryptography.RNGCryptoServiceProvider class to generate cryptographically strong keys. As such, it only runs on machines equipped with the .NET Framework.

Q - If I'm developing an application that must accommodate multiple security levels through secure login and my ASP.NET web application is spanned across three web-servers (using round-robin load balancing). What would be the best approach to maintain login-in state for the users?
A - Use the state server or store the state in the database. This can be easily done through simple setting change in the web.config.
sqlConnectionString="data source=;user id=sa;password="
cookieless="false" timeout="30" />
In the above one instead of mode="InProc", you specify stateserver or sqlserver.

Q - Which configuration files are used in web applications?
A - machine.config and web.config

Q – What do you mean by Data Binding?
A – Data Binding is the process by which a control is automatically synchronized with the DataSet. The data binding provides the underlying services needed to build data forms easily.

Q - Which tag is used to handle incoming request?
A - (Case sensitive)

Q - How do U store data in Cache?
A – Cache[“VariableName”]

Q - How do U get access of Checkbox in DataGrid?
A - FindControl

Q - How to use user control?
A – Using @ Register tag

Q - How do U share session between ASP and ASP.NET?
A - Can't be use directly

Q - What base class do all Web Forms inherit from?
A - System.Web.UI.Page

Q - How do you deploy ASP.NET application?
A – Using XCOPY feature i.e. direct copy.

Q - Which class is used in FormsAuthentication to set the cookie?
A - System.FormsAuthentication

Q - How to get the Logon user name from FormsAuthentication?
A - User.Identity.Name

Q - What is code access security used?
A - To set the permission for accessing code

Q - Does web.config file in a sub folder overrides the web.config in main folder?
A - Yes

Q - What control is used to manage state in web forms?
A - Viewstate

Q - Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
A - In the Application_Start event you could store the data, which is used throughout the life time of an application for example application name, where as Session_Start could be used to store the information, which is required for that session of the application say for example user id or user name.

Q - Can you edit data in the Repeater control?
A - No. Only DataList and DataGrid provide you editing capabilities.

Q - Which template must you provide, in order to display data in a Repeater control?
A - ItemTemplate.

Q - How can you provide an alternating color scheme in a Repeater control?
A - Use AlternatingItemTemplate

Q - What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?
A - The text property and the DataBind Method.

Q - What method do you use to explicitly kill a user's session?
A - Session.Abandon

Q - Which two properties are on every validation control?
A - The common properties are:
1. IsValid (bool)
2. ControlToValidate (string)
3. ErrorMessage (string)
4. ValidationDisplay (Display)
5. Text (string)
The common method is: Validate()

Q - What tags do you need to add within the asp:datagrid tags to bind columns manually?
A - You need to set AutoGenerateColumns Property to false.

Q – What tag do you use to add a hyperlink column to the DataGrid?
A – HyperLinkColumn

Q - What property do you have to set to tell the grid which page to go to when using the Pager object?
A - CurrentPageIndex. You need to set this one with the DataGridPageChangedEventArgs' NewPageIndex.

Q - Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
A - ListItem.

Q - Which control would you use if you needed to make sure the values in two different controls matched?
A - Use CompareValidator.

Q - Which one of the following occurs first: authentication or authorization?
A – authentication


Q - Can you explain the difference between an ADO.NET Dataset and an ADO RecordSet?
A. ADO.NET DataSet is a mini RDBMS based on XML, where as RecordSet is collection of rows. DataSet is independent of connection and communicates to the database through DataAdapter, so it could be attached to any well defined collections like hashtable, dictionary, tables, arraylists etc. practically. And also it can be bound to DataGrid etc. controls straightaway. RecordSet on the other hand is tightly coupled to Database System.

Q – Differentiate between DataSet and DataReader
A - To determine whether to use the DataSet or the DataReader when you design your application, consider the level of functionality that is needed in the application.

Use the DataSet in order to do the following with your application:
 Navigate between multiple discrete tables of results.
 Manipulate data from multiple sources (for example, a mixture of data from more than one database, from an XML file, and from a spreadsheet).
 Exchange data between tiers or using an XML Web service. Unlike the DataReader, the DataSet can be passed to a remote client.
 Reuse the same set of rows to achieve a performance gain by caching them (such as for sorting, searching, or filtering the data).
 Perform a large amount of processing per row. Extended processing on each row returned using a DataReader ties up the connection serving the DataReader longer than necessary, impacting performance.
 Manipulate data using XML operations such as Extensible Stylesheet Language Transformations (XSLT) or XPath queries.

Use the DataReader in your application if you:
 Do not need to cache the data.
 Are processing a set of results too large to fit into memory.
 Need to quickly access data once, in a forward-only and read-only manner.

Note: The DataAdapter uses the DataReader when filling a DataSet. Therefore, the performance gained by using the DataReader instead of the DataSet is that you save on the memory that the DataSet would consume and the cycles it takes to populate the DataSet. This performance gain is, for the most part, nominal so you should base your design decisions on the functionality required.

Q - How do you store XML into Dataset?
A – ReadXML

Q - How do U get the related row information DataTable?
A – ChildRelation

Q - Which method do you invoke on the DataAdapter control to load your generated dataset with data?
A - Fill()

Q - How do U start transaction in ADO.NET?
A –
Connection myConnection = new SqlConnection(myConnString);

SqlCommand myCommand = new SqlCommand();
SqlTransaction myTrans;

myTrans = myConnection.BeginTransaction();
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;

Q - Which Data Provider is not supported by ADO.NET?

Q - What is needed to use Parameter in Command?
A - SQLConnection, SQLCommand, SQLParameter

Q - How do you save the changes from Dataset to data source?
A – Use Update() method.

Q – What concurrency model does ADO.NET uses?
A – Optimistic

Q – You plan to update multiple tables using ADO.NET. How would you do it using DataAdapter?
A – Use multiple DataAdapters. A given DataAdapter can update only a single table.

Q – What is the only connection-oriented entity in ADO.Net?
A – DataReader

Q – What ADO.NET entity is used to maintain table relationships?
A – DataRelation

Q – What does ADO.NET uses internally to store data?

Q – How can you save a Data Table’s contents to a file?
A – Add it to a DataSet and use WriteXML method of the DataSet.

Q – How does ADO.NET know a conflict has occurred when the DataAdapter is used to update the data source?
A – Two versions of the data are maintained in DataSet: original and modified. Before updating it ensures that the existing data in the data source is the same as original. Else the situation is tagged as a conflict.

Q – What exception is thrown when a concurrency issue is encountered?
A – DBConcurrencyException

Q – How would you get a SQL command object without instantiating one explicitly?
A – SQLConnection.CreateCommand

Q – Which event occurs when SQL Server returns a warning or informational message?
A – SQLConnection.InfoMessage

Q – When invoking the DataRow.AcceptChanges method on a row that has been deleted with either the Delete or DataRowCollection.Remove method, which exception is thrown?
A – RowNotInTableException

Q – Which class enables us to use column names in a DataTable that are different from those in the data source?
A – DataColumnMapping in DataTableMapping

Q – What would you use to get all the titles (child table) manufactured by a publisher (master table)?
A – ds.Tables[“master”].rows[9].getChildRows(“relationname”)

Q – How would you delete the 5th row in the dataset?
A – Dataset.Tables[“Table”].Rows[4].Delete

Q – By default when you modify the values in a column the rowstate for the column does not change to “Modified” unless you move off the row. How will you overcome this issue by remaining on the current row itself?
A – By calling the EndCurrentEdit method on the underlying BindingContext object.

Q – What is the best way to determine if a DataReader has rows or not?
A – Call the HasRows method

Q – Which is the recommended way of working with Rows that have large BLOBS stored within them?
A – Opening DataReaders using the SequentialAccess behaviour

Web Services and Remoting

Q – What is WebServices?
A - It refers to a form of a component that can be used remotely.

Q – What do you mean by Remoting?
A – Remoting is a communication process and architecture that defines the methods by which a client can make calls to remote objects.

Q - What is the difference between Web Services and .NET Remoting?
A - The following list outlines some of the major differences between .NET Remoting and Web services that will help you to decide when to use one or the other:

 ASP.NET based Web services can only be accessed over HTTP. .NET Remoting can be used across any protocol.

 Web services work in a stateless environment where each request results in a new object created to service the request. .NET Remoting supports state management options and can correlate multiple calls from the same client and support callbacks.

 Web services serialize objects through XML contained in the SOAP messages and can thus only handle items that can be fully expressed in XML. .NET Remoting relies on the existence of the common language runtime assemblies that contain information about data types. This limits the information that must be passed about an object and allows objects to be passed by value or by reference.

 Web services support interoperability across platforms and are good for heterogeneous environments. .NET Remoting requires the clients be built using .NET, or another framework that supports .NET Remoting, which means a homogeneous environment.

Q – What do you mean by Serialization?
A – Serialization is the process of creating a storable form of an object’s data (or state). It is the process of converting an object into a form that can be readily transported. For example, you can serialize an object and transport it over the Internet using HTTP between a client and a server.
Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).

Q- Does the .NET Framework have in-built support for serialization?
A - There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

Note: XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all of an object's fields and properties, both public and private, use the BinaryFormatter instead of XML serialization.

Q - I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or BinaryFormatter?
A - It depends. XmlSerializer has several limitations such as the requirement that the target class has a parameterless constructor, and only public read/write properties and fields can be serialized. However, on the plus side, XmlSerializer has good support for customizing the XML document that is produced or consumed. XmlSerializer's features mean that it is most suitable for cross-platform work, or for constructing objects from existing XML documents.
SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can serialize private fields, for example. However they both require that the target class be marked with the [Serializable] attribute, so like XmlSerializer the class needs to be written with serialization in mind. Also there are some quirks to watch out for - for example on deserialization the constructor of the new object is not invoked.
The choice between SoapFormatter and BinaryFormatter depends on the application. BinaryFormatter makes sense where both serialization and deserialization will be performed on the .NET platform and where performance is important. SoapFormatter generally makes more sense in all other cases, for ease of debugging if nothing else.

Q - Can I customise the serialization process?
A - Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement] attribute, which can be used to specify the XML element name to be used for a particular property or field.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be achieved by implementing the ISerializable interface on the class whose instances are to be serialized.

Q - Why is XmlSerializer so slow?
A - There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

Q- What do you mean by Web Reference?
A - To simplify development of XML Web service client applications, Visual Studio provides the concept of Web references. A Web reference is a generated proxy class that locally represents the exposed functionality of an XML Web service. The proxy class defines methods that represent the actual methods exposed by an XML Web service. When the client application creates an instance of the proxy class, it is capable of calling the XML Web service methods as if the XML Web service was a locally available component.

Note You need to explicitly specify the address and port of the proxy server on your network to make XML Web services outside the firewall available to the Web browser in the Web Reference dialog box.

Q – What is the use of MarshalByRefObject class?
A – It enables access to objects across application domain boundaries in applications that support remoting.

Q - What attribute should be used to expose Webservice?
A - WebMethod

Q - What can the return type in Web services?
A - Anything

Q – True or False: A Web service can only be written in .NET.
A - False. It can be written in any language as long as it supports xml and soap.

Q - Where on the Internet would you look for Web services?
A - UDDI.org. Even Microsoft maintains an UDDI server - http://uddi.microsoft.com. UDDI is Universal Description, Discovery and Integration of Web Services. The UDDI server serves as yellow pages to WebServices.

Q -True or False: To test a Web service you must create a windows application or Web application to consume this service.
A - False. The WebService comes with a test page and it provides HTTP-GET method to test. And if the web service turned off HTTP-GET for security purposes then you need to create a web application or windows app as a client to this to test.

Q - If you need an XML entity that can have a default value, should you use an element or an attribute?
A – Attribute

Q - How are errors reported to a client when using the SOAP protocol?
A - By using SOAP Fault elements

Q - Which tool can you use to discover WSDL documents at a URL?
A - Disco.exe

Q - What are the three main components of a service-oriented architecture?
A - Service provider, Service consumer, and Service broker.

Q - Which tool can you use to generate client proxies for XML Web services?
A - Wsdl.exe or Visual Studio .NET

Q - When you add a Web reference to a client application, how is the types that are exposed by the XML Web service exposed in the client application?
A - They are exposed in a nested namespace that is a child of the default namespace of the client application.

Q - If an XML Web service method returns a stream that is 1 megabyte in size, which property of the WebMethod attribute should you modify to minimize the amount of time a client would wait for the arrival of the first set of data?
A - BufferResponse

Q - Which properties and fields of a class are serialized when an XML Web service method returns an instance of a class?
A - All public, read/write properties and all public, read/write fields.

Q - If your XML Web service will be deployed on a Web farm, what kind of data can be stored appropriately in Application state?
A - Read-only data that can be restored exactly in the event of an XML Web service being restarted.

Q- You deploy an XML Web service in production, and want to store trace information in a disk file on the server hosting the XML Web service. Which two classes could you use to do this?
A - Trace to emit trace output and TextWriterTraceListener to write the trace output to disk

Q - How can you use UDDI to determine if two XML Web services are compatible?
A - You can compare the tModelKey lists for each of the XML Web services. If the lists are identical, then the XML Web services are compatible.

Q - If the users of your XML Web service do not have Windows accounts, how can you provide authentication information to the XML Web service?
A - By defining a SOAP header representing the required information and requiring that a SOAP header be used in your XML Web service.

Q - When implementing role-based security, which type of object, stores a list of roles for an authenticated user?
A – Principal

Q - Which attribute should you use to request permissions for the assemblies in your XML Web service?
A – SecurityPermission

Q - Which protocol that XML Web services use supports the richest set of data types?

Q - Name the two forms of caching that the .NET Framework provides and that you can use in XML Web services.
A - Output and data caching

Q - When should you consider implementing asynchronous Web methods?
A - Whenever the method implementation will perform I/O that is based on Win32 kernel handles.

Q - Some Web service classes derive from System.Web.WebServices; others do not. What's the deal?
A - WebService contributes properties named Application, Session, Context, Server, and User to derived classes enabling Web services to access the ASP.NET objects of the same name. If you don't use these objects in your Web service-for example, if you don't use application state or session state-then you don't have to derive from WebService, either. Incidentally, if you want to use ASP.NET session state in a Web method, use the following WebMethod attribute to enable session state for that method:
[WebMethod (EnableSession="true")]

Q - What are VSDISCO files?
A - VSDISCO files are DISCO files that support dynamic discovery of Web services.

No comments: