Dot Net, .Net, C#, Faq

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 95

.

NET Framework FAQ


Andy McMullan The .NET Framework FAQ was first posted in July 2000, and is regularly updated. It covers the fundamentals of the .NET Framework including assemblies, garbage collection, security, interop with COM and remoting. Newcomers to the .NET framework may wish to read the FAQ from top to bottom as a tutorial. More experienced practitioners may prefer to consult the contents list for topics of particular interest. This FAQ was inspired by discussions on the DOTNET mailing list. The list has now been split into several DOTNET-X lists - for details see http://discuss.develop.com/. Christophe Lauer has translated the FAQ into French. Royal has translated the FAQ into Chinese. If you like this FAQ, you might be interested in my C# FAQ for C++ Programmers.

Latest updates: 27-Jan-2005: Rewritten Should I implement Finalize on my class? Should I implement IDisposable? 25-Jan-2005: What's new in the .NET 2.0 class library? 21-Jan-2005: What size is a .NET object? 18-Jan-2005: When do I need to call GC.KeepAlive? 13-Jan-2005: What is the lapsed listener problem? 08-Jan-2005: What is the difference between an event and a delegate? 06-Jan-2005: New section on .NET 2.0

Contents
1. Introduction o o o o o o 2. Terminology o o o o o o
2.1 What is the CLI? Is it the same as the CLR? 2.2 What is the CTS, and how does it relate to the CLS? 2.3 What is IL? 2.4 What is C#? 2.5 What does 'managed' mean in the .NET context? 2.6 What is reflection? 1.1 What is .NET? 1.2 When was .NET announced? 1.3 What versions of .NET are there? 1.4 What operating systems does the .NET Framework run on? 1.5 What tools can I use to develop .NET applications? 1.6 Why did they call it .NET?

3. Assemblies o o o o o o
web? 3.1 What is an assembly? 3.2 How can I produce an assembly? 3.3 What is the difference between a private assembly and a shared assembly? 3.4 How do assemblies find each other? 3.5 How does assembly versioning work? 3.6 How can I develop an application that automatically updates itself from the

4. Application Domains o o o
4.1 What is an application domain? 4.2 How does an AppDomain get created? 4.3 Can I write my own .NET host?

5. Garbage Collection o o o o o o o o o 6. Serialization o o o o o o o o


6.1 What is serialization? 6.2 Does the .NET Framework have in-built support for serialization? 6.3 I want to serialize instances of my class. Should I use XmlSerializer, 5.1 What is garbage collection? 5.2 Is it true that objects don't always get destroyed immediately when the last

reference goes away? 5.3 Why doesn't the .NET runtime offer deterministic destruction? 5.4 Is the lack of deterministic destruction in .NET a problem? 5.5 Should I implement Finalize on my class? Should I implement IDisposable? 5.6 Do I have any control over the garbage collection algorithm? 5.7 How can I find out what the garbage collector is doing? 5.8 What is the lapsed listener problem? 5.9 When do I need to use GC.KeepAlive?

SoapFormatter or BinaryFormatter? 6.4 Can I customise the serialization process? 6.5 Why is XmlSerializer so slow? 6.6 Why do I get errors when I try to serialize a Hashtable? 6.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass"

error. How do I find out what the problem is? 6.8 Why am I getting an InvalidOperationException when I serialize an

ArrayList?

7. Attributes o o o
7.1 What are attributes? 7.2 Can I create my own metadata attributes? 7.3 Can I create my own context attibutes?

8. Code Access Security o o o o o o o o


8.1 What is Code Access Security (CAS)? 8.2 How does CAS work? 8.3 Who defines the CAS code groups? 8.4 How do I define my own code group? 8.5 How do I change the permission set for a code group? 8.6 Can I create my own permission set? 8.7 I'm having some trouble with CAS. How can I troubleshoot the problem? 8.8 I can't be bothered with CAS. Can I turn it off?

9. Intermediate Language (IL) o o o o o


9.1 Can I look at the IL for an assembly? 9.2 Can source code be reverse-engineered from IL? 9.3 How can I stop my code being reverse-engineered from IL? 9.4 Can I write IL programs directly? 9.5 Can I do things in IL that I can't do in C#?

10. Implications for COM o o o o o o


10.1 Does .NET replace COM? 10.2 Is DCOM dead? 10.3 Is COM+ dead? 10.4 Can I use COM components from .NET programs? 10.5 Can I use .NET components from COM programs? 10.6 Is ATL redundant in the .NET world?

11. Miscellaneous o o o o o 12. .NET 2.0 o o


12.1 What are the new features of .NET 2.0? 12.2 What are the new 2.0 features useful for? 11.1 How does .NET remoting work? 11.2 How can I get at the Win32 API from a .NET program? 11.3 How do I write to the application configuration file at runtime? 11.4 What is the difference between an event and a delegate? 11.5 What size is a .NET object?

o o 13. Class Library o

12.3 What's the problem with .NET generics? 12.4 What's new in the .NET 2.0 class library?

13.1 Threads

13.1.1 How do I spawn a thread? 13.1.2 How do I stop a thread? 13.1.3 How do I use the thread pool? 13.1.4 How do I know when my thread pool work item has completed? 13.1.5 How do I prevent concurrent access to my data? o
13.2 Tracing

13.2.1 Is there built-in support for tracing/logging? 13.2.2 Can I redirect tracing to a file? 13.2.3 Can I customise the trace output? 13.2.4 Are there any third party logging components available? 14. Resources o o o
14.1 Recommended books 14.2 Web sites 14.3 Blogs

1. Introduction

1.1 What is .NET?


.NET is a general-purpose software development platform, similar to Java. At its core is a virtual machine that turns intermediate language (IL) into machine code. High-level language compilers for C#, VB.NET and C++ are provided to turn source code into IL. C# is a new programming language, very similar to Java. An extensive class library is included, featuring all the functionality one might expect from a contempory development platform - windows GUI development (Windows Forms), database access (ADO.NET), web development (ASP.NET), web services, XML etc. See also Microsoft's definition.

1.2 When was .NET announced?


Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET.

1.3 What versions of .NET are there?


The final version of the 1.0 SDK and runtime was made publicly available around 6pm PST on 15-Jan2002. At the same time, the final version of Visual Studio.NET was made available to MSDN subscribers. .NET 1.1 was released in April 2003 - it's mostly bug fixes for 1.0. .NET 2.0 is expected in 2005.

1.4 What operating systems does the .NET Framework run on?
The runtime supports Windows Server 2003, Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported. Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on XP and Windows 2000/2003. Windows 98/ME cannot be used for development. IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the ASP.NET Web Matrix web server does run on XP Home. The .NET Compact Framework is a version of the .NET Framework for mobile devices, running Windows CE or Windows Mobile. The Mono project has a version of the .NET Framework that runs on Linux.

1.5 What tools can I use to develop .NET applications?


There are a number of tools, described here in ascending order of cost:

The .NET Framework SDK is free and includes command-line compilers for C++, C#, and
VB.NET and various other utilities to aid development.

ASP.NET Web Matrix is a free ASP.NET development environment from Microsoft. As well as a
GUI development environment, the download includes a simple web server that can be used instead of IIS to host ASP.NET apps. This opens up ASP.NET development to users of Windows XP Home Edition, which cannot run IIS.

Microsoft Visual C# .NET Standard 2003 is a cheap (around $100) version of Visual Studio

limited to one language and also with limited wizard support. For example, there's no wizard support for class libraries or custom UI controls. Useful for beginners to learn with, or for savvy developers who can work around the deficiencies in the supplied wizards. As well as C#, there are VB.NET and C++ versions.

Microsoft Visual Studio.NET Professional 2003. If you have a license for Visual Studio 6.0, you
can get the upgrade. You can also upgrade from VS.NET 2002 for a token $30. Visual Studio.NET includes support for all the MS languages (C#, C++, VB.NET) and has extensive wizard support.

At the top end of the price spectrum are the Visual Studio.NET 2003 Enterprise and Enterprise Architect editions. These offer extra features such as Visual Sourcesafe (version control), and performance and analysis tools. Check out the Visual Studio.NET Feature Comparison at http://msdn.microsoft.com/vstudio/howtobuy/choosing.asp

1.6 Why did they call it .NET?

I don't know what they were thinking. They certainly weren't thinking of people using search tools. It's meaningless marketing nonsense - best not to think about it.

2. Terminology

2.1 What is the CLI? Is it the same as the CLR?


The CLI (Common Language Infrastructure) is the definiton of the fundamentals of the .NET framework - the Common Type System (CTS), metadata, the Virtual Execution Environment (VES) and its use of intermediate language (IL), and the support of multiple programming languages via the Common Language Specification (CLS). The CLI is documented through ECMA - see http://msdn.microsoft.com/net/ecma/ for more details. The CLR (Common Language Runtime) is Microsoft's primary implementation of the CLI. Microsoft also have a shared source implementation known as ROTOR, for educational purposes, as well as the .NET Compact Framework for mobile devices. Non-Microsoft CLI implementations include Mono and DotGNU Portable.NET.

2.2 What is the CTS, and how does it relate to the CLS?
CTS = Common Type System. This is the full range of types that the .NET runtime understands. Not all .NET languages support all the types in the CTS. CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language. This interop is very fine-grained - for example a VB.NET class can inherit from a C# class.

2.3 What is IL?


IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code (of any language) is compiled to IL during development. The IL is then converted to machine code at the point where the software is installed, or (more commonly) at run-time by a Just-In-Time (JIT) compiler.

2.4 What is C#?


C# is a new language designed by Microsoft to work with the .NET framework. In their "Introduction to C#" whitepaper, Microsoft describe C# as follows: "C# is a simple, modern, object oriented, and type-safe programming language derived from C and C+ +. C# (pronounced C sharp) is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++." Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still works pretty well :-).

If you are a C++ programmer, you might like to check out my C# FAQ.

2.5 What does 'managed' mean in the .NET context?


The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly different things. Managed code: The .NET framework provides several core run-time services to the programs that run within it - for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. Such code is called managed code. Managed data: This is data that is allocated and freed by the .NET runtime's garbage collector. Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can only inherit from one base class.

2.6 What is reflection?


All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly. Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries. Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

3. Assemblies

3.1 What is an assembly?


An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry point) or a library. An assembly consists of one or more files (dlls, exes, html files etc), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing. An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET runtime sees these as two

completely different types. Furthermore, don't get confused between assemblies and namespaces namespaces are merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime. Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at the assembly boundary. Finally, assemblies are the unit of versioning in .NET - more on this below.

3.2 How can I produce an assembly?


The simplest way to produce an assembly is directly from a .NET compiler. For example, the following C# program:
public class CTest { public CTest() { System.Console.WriteLine( "Hello from CTest" ); } }

can be compiled into a library assembly (dll) like this:


csc /t:library ctest.cs

You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET SDK. Alternatively you can compile your source into modules, and then combine the modules into an assembly using the assembly linker (al.exe). For the C# compiler, the /target:module switch is used to generate a module instead of an assembly.

3.3 What is the difference between a private assembly and a shared assembly?
Location and visibility: A private assembly is normally used by a single application, and is

stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. the .NET framework classes.

Versioning: The runtime enforces versioning constraints only on shared assemblies, not on
private assemblies.

3.4 How do assemblies find each other?


By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache.

3.5 How does assembly versioning work?

Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly. The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file. Remember: versioning is only applied to shared assemblies, not private assemblies.

3.6 How can I develop an application that automatically updates itself from the web?
For .NET 1.x, use the Updater Application Block. For .NET 2.x, use ClickOnce.

4. Application Domains

4.1 What is an application domain?


An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate applications from each other, and so it is particularly useful in hosting scenarios such as ASP.NET. An AppDomain can be destroyed by the host without affecting other AppDomains in the process. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but expensive. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory. One non-obvious use of AppDomains is for unloading types. Currently the only way to unload a .NET type is to destroy the AppDomain it is loaded into. This is particularly useful if you create and destroy types on-the-fly via reflection. Microsoft have an AppDomain FAQ.

4.2 How does an AppDomain get created?


AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain, creates an instance of an object inside it, and then executes one of the object's methods:
using System; using System.Runtime.Remoting; using System.Reflection;

public class CAppDomainInfo : MarshalByRefObject { public string GetName() { return AppDomain.CurrentDomain.FriendlyName; } } public class App { public static int Main() { AppDomain ad = AppDomain.CreateDomain( "Andy's new domain" ); CAppDomainInfo adInfo = (CAppDomainInfo)ad.CreateInstanceAndUnwrap( Assembly.GetCallingAssembly().GetName().Name, "CAppDomainInfo" ); Console.WriteLine( "Created AppDomain name = " + adInfo.GetName() ); return 0; } }

4.3 Can I write my own .NET host?


Yes. For an example of how to do this, take a look at the source for the dm.net moniker developed by Jason Whittington and Don Box. There is also a code sample in the .NET SDK called CorHost.

5. Garbage Collection

5.1 What is garbage collection?


Garbage collection is a heap-management strategy where a run-time component takes responsibility for managing the lifetime of the memory used by objects. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.

5.2 Is it true that objects don't always get destroyed immediately when the last reference goes away?
Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed. There was an interesting thread on the DOTNET list, started by Chris Sells, about the implications of non-deterministic destruction of objects in C#. In October 2000, Microsoft's Brian Harry posted a lengthy analysis of the problem. Chris Sells' response to Brian's posting is here.

5.3 Why doesn't the .NET runtime offer deterministic destruction?


Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next 'sweep' of the heap.

Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep.

5.4 Is the lack of deterministic destruction in .NET a problem?


It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some form of reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this.

5.5 Should I implement Finalize on my class? Should I implement IDisposable?


This issue is a little more complex than it first appears. There are really two categories of class that require deterministic destruction - the first category manipulate unmanaged types directly (generally via an IntPtr representing an OS handle), whereas the second category manipulate managed types that require deterministic destruction. An example of the first category is a class with an IntPtr member representing an OS file handle. An example of the second category is a class with a System.IO.FileStream member. For the first category, it makes sense to implement IDisposable and override Finalize. This allows the object user to 'do the right thing' by calling Dispose, but also provides a fallback of freeing the unmanaged resource in the Finalizer, should the calling code fail in its duty. However this logic does not apply to the second category of class, with only managed resources. In this case implementing Finalize is pointless, as managed member objects cannot be accessed in the Finalizer. This is because there is no guarantee about the ordering of Finalizer execution. So only the Dispose method should be implemented. (If you think about it, it doesn't really make sense to call Dispose on member objects from a Finalizer anyway, as the member object's Finalizer will do the required cleanup anyway.) For classes that need to implement IDisposable and override Finalize, see Microsoft's documented pattern. Note that some developers argue that implementing a Finalizer is always a bad idea, as it hides a bug in your code (i.e. the lack of a Dispose call). A less radical approach is to implement Finalize but include a Debug.Assert at the start, thus signalling the problem in developer builds but allowing the cleanup to occur in release builds.

5.6 Do I have any control over the garbage collection algorithm?


A little. For example the System.GC class exposes a Collect method, which forces the garbage collector to collect all unreferenced objects immediately. Also there is a gcConcurrent setting that can be specified via the application configuration file. This specifies whether or not the garbage collector performs some of its collection activities on a separate thread. The setting only applies on multi-processor machines, and defaults to true.

5.7 How can I find out what the garbage collector is doing?
Lots of interesting statistics are exported from the .NET runtime via the '.NET CLR xxx' performance counters. Use Performance Monitor to view them.

5.8 What is the lapsed listener problem?


The lapsed listener problem is one of the primary causes of leaks in .NET applications. It occurs when a subscriber (or 'listener') signs up for a publisher's event, but fails to unsubscribe. The failure to unsubscribe means that the publisher maintains a reference to the subscriber as long as the publisher is alive. For some publishers, this may be the duration of the application. This situation causes two problems. The obvious problem is the leakage of the subscriber object. The other problem is the performance degredation due to the publisher sending redundant notifications to 'zombie' subscribers. There are at least a couple of solutions to the problem. The simplest is to make sure the subscriber is unsubscribed from the publisher, typically by adding an Unsubscribe() method to the subscriber. Another solution, documented here by Shawn Van Ness, is to change the publisher to use weak references in its subscriber list.

5.9 When do I need to use GC.KeepAlive?


It's very unintuitive, but the runtime can decide that an object is garbage much sooner than you expect. More specifically, an object can become garbage while a method is executing on the object, which is contrary to most developers' expectations. Chris Brumme explains the issue on his blog. I've taken Chris's code and expanded it into a full app that you can play with if you want to prove to yourself that this is a real problem:
using System; using System.Runtime.InteropServices; class Win32 { [DllImport("kernel32.dll")] public static extern IntPtr CreateEvent( IntPtr lpEventAttributes, bool bManualReset,bool bInitialState, string lpName); [DllImport("kernel32.dll", SetLastError=true)] public static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll")] public static extern bool SetEvent(IntPtr hEvent); } class EventUser { public EventUser() { hEvent = Win32.CreateEvent( IntPtr.Zero, false, false, null ); } ~EventUser() { Win32.CloseHandle( hEvent ); Console.WriteLine("EventUser finalized"); } public void UseEvent() {

UseEventInStatic( this.hEvent ); } static void UseEventInStatic( IntPtr hEvent ) { //GC.Collect(); bool bSuccess = Win32.SetEvent( hEvent ); Console.WriteLine( "SetEvent " + (bSuccess ? "succeeded" : "FAILED!") ); } IntPtr hEvent; } class App { static void Main(string[] args) { EventUser eventUser = new EventUser(); eventUser.UseEvent(); } }

If you run this code, it'll probably work fine, and you'll get the following output:
SetEvent succeeded EventDemo finalized

However, if you uncomment the GC.Collect() call in the UseEventInStatic() method, you'll get this output:
EventDemo finalized SetEvent FAILED!

(Note that you need to use a release build to reproduce this problem.) So what's happening here? Well, at the point where UseEvent() calls UseEventInStatic(), a copy is taken of the hEvent field, and there are no further references to the EventUser object anywhere in the code. So as far as the runtime is concerned, the EventUser object is garbage and can be collected. Normally of course the collection won't happen immediately, so you'll get away with it, but sooner or later a collection will occur at the wrong time, and your app will fail. A solution to this problem is to add a call to GC.KeepAlive(this) to the end of the UseEvent method, as Chris explains.

6. Serialization

6.1 What is serialization?


Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process, i.e. 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).

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

6.3 I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or BinaryFormatter?
It depends. XmlSerializer has severe 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 customising 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.

6.4 Can I customise the serialization process?


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 acheived by implementing the the ISerializable interface on the class whose instances are to be serialized.

6.5 Why is XmlSerializer so slow?


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.

6.6 Why do I get errors when I try to serialize a Hashtable?


XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

6.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is?
Look at the InnerException property of the exception that is thrown to get a more specific error message.

6.8 Why am I getting an InvalidOperationException when I serialize an ArrayList?


XmlSerializer needs to know in advance what type of objects it will find in an ArrayList. To specify the type, use the XmlArrayItem attibute like this:
public class Person { public string Name; public int Age; } public class Population { [XmlArrayItem(typeof(Person))] public ArrayList People; }

7. Attributes

7.1 What are attributes?


There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be attached to a class and means that instances of the class can be serialized.
[serializable] public class CTest {}

The other type of attribute is a context attribute. Context attributes use a similar syntax to metadata attributes but they are fundamentally different. Context attributes provide an interception mechanism whereby instance activation and method calls can be pre- and/or post-processed. If you have encountered Keith Brown's universal delegator you'll be familiar with this idea.

7.2 Can I create my own metadata attributes?


Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example:
[AttributeUsage(AttributeTargets.Class)] public class InspiredByAttribute : System.Attribute { public string InspiredBy; public InspiredByAttribute( string inspiredBy )

{ InspiredBy = inspiredBy; } } [InspiredBy("Andy Mc's brilliant .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 ); } }

7.3 Can I create my own context attibutes?


Yes. Take a look at Peter Drayton's Tracehook.NET.

8. Code Access Security

8.1 What is Code Access Security (CAS)?


CAS is the part of the .NET security model that determines whether or not code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.

8.2 How does CAS work?


The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set. For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.)

8.3 Who defines the CAS code groups?

Microsoft defines some default ones, but you can modify these and even create your own. To see the code groups defined on your system, run 'caspol -lg' from the command-line. On my system it looks like this:
Level = Machine Code Groups: 1. All code: Nothing 1.1. Zone - MyComputer: FullTrust 1.1.1. Honor SkipVerification requests: SkipVerification 1.2. Zone - Intranet: LocalIntranet 1.3. Zone - Internet: Internet 1.4. Zone - Untrusted: Nothing 1.5. Zone - Trusted: Internet 1.6. StrongName 0024000004800000940000000602000000240000525341310004000003 000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD0 6 F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E0 8 07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5 C AC1DF1734633C602F8F2D5: Everything

Note the hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then sub-divided into several groups, each of which in turn can be sub-divided. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission set than its parent.

8.4 How do I define my own code group?


Use caspol. For example, suppose you trust code from www.mydomain.com and you want it have full access to your system, but you want to keep the default restrictions for all other internet sites. To achieve this, you would add a new code group as a sub-group of the 'Zone - Internet' group, like this:
caspol -ag 1.3 -site www.mydomain.com FullTrust

Now if you run caspol -lg you will see that the new group has been added as group 1.3.1:
... 1.3. Zone - Internet: Internet 1.3.1. Site - www.mydomain.com: FullTrust ...

Note that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to manipulate from the command-line. The underlying runtime never sees it.

8.5 How do I change the permission set for a code group?


Use caspol. If you are the machine administrator, you can operate at the 'machine' level - which means not only that the changes you make become the default for the machine, but also that users cannot change the permissions to be more permissive. If you are a normal (non-admin) user you can still modify the permissions, but only to make them more restrictive. For example, to allow intranet code to do what it likes you might do this:

caspol -cg 1.2 FullTrust

Note that because this is more permissive than the default policy (on a standard system), you should only do this at the machine level - doing it at the user level will have no effect.

8.6 Can I create my own permission set?


Yes. Use caspol -ap, specifying an XML file containing the permissions in the permission set. To save you some time, here is a sample file corresponding to the 'Everything' permission set - just edit to suit your needs. When you have edited the sample, add it to the range of available permission sets like this:
caspol -ap samplepermset.xml

Then, to apply the permission set to a code group, do something like this:
caspol -cg 1.3 SamplePermSet

(By default, 1.3 is the 'Internet' code group)

8.7 I'm having some trouble with CAS. How can I troubleshoot the problem?
Caspol has a couple of options that might help. First, you can ask caspol to tell you what code group an assembly belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a particular assembly using caspol -rsp.

8.8 I can't be bothered with CAS. Can I turn it off?


Yes, as long as you are an administrator. Just run:
caspol -s off

9. Intermediate Language (IL)

9.1 Can I look at the IL for an assembly?


Yes. MS supply a tool called Ildasm that can be used to view the metadata and IL for an assembly.

9.2 Can source code be reverse-engineered from IL?


Yes, it is often relatively straightforward to regenerate high-level source from IL. Lutz Roeder's Reflector does a very good job of turning IL into C# or VB.NET.

9.3 How can I stop my code being reverse-engineered from IL?


You can buy an IL obfuscation tool. These tools work by 'optimising' the IL in such a way that reverseengineering becomes much more difficult. Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL.

9.4 Can I write IL programs directly?


Yes. Peter Drayton posted this simple example to the DOTNET mailing list:
.assembly MyAssembly {} .class MyApp { .method static void Main() { .entrypoint ldstr "Hello, IL!" call void System.Console::WriteLine(class System.Object) ret } }

Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.

9.5 Can I do things in IL that I can't do in C#?


Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays.

10. Implications for COM

10.1 Does .NET replace COM?


This subject causes a lot of controversy, as you'll see if you read the mailing list archives. Take a look at the following two threads: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D=0&P=68241 http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R60761 The bottom line is that .NET has its own mechanisms for type interaction, and they don't use COM. No IUnknown, no IDL, no typelibs, no registry-based activation. This is mostly good, as a lot of COM was ugly. Generally speaking, .NET allows you to package and use components in a similar way to COM, but makes the whole thing a bit easier.

10.2 Is DCOM dead?

Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on DCOM. DCOM was pretty much dead anyway, once firewalls became widespread and Microsoft got SOAP fever. Of course DCOM will still be used in interop scenarios.

10.3 Is COM+ dead?


Not immediately. The approach for .NET 1.0 was to provide access to the existing COM+ services (through an interop layer) rather than replace the services with native .NET ones. Various tools and attributes were provided to make this as painless as possible. Over time it is expected that interop will become more seamless - this may mean that some services become a core part of the CLR, and/or it may mean that some services will be rewritten as managed code which runs on top of the CLR. For more on this topic, search for postings by Joe Long in the archives - Joe is the MS group manager for COM+. Start with this message: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R68370

10.4 Can I use COM components from .NET programs?


Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to .NET-compatible types. Here's a simple example for those familiar with ATL. First, create an ATL component which implements the following IDL:
import "oaidl.idl"; import "ocidl.idl"; [ object, uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206), helpstring("ICppName Interface"), pointer_default(unique), oleautomation ] interface ICppName : IUnknown { [helpstring("method SetName")] HRESULT SetName([in] BSTR name); [helpstring("method GetName")] HRESULT GetName([out,retval] *pName ); }; [ uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D), version(1.0), helpstring("cppcomserver 1.0 Type Library") ] library CPPCOMSERVERLib { importlib("stdole32.tlb"); importlib("stdole2.tlb"); [ uuid(600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70),

BSTR

helpstring("CppName Class") ] coclass CppName { [default] interface ICppName; }; };

When you've built the component, you should get a typelibrary. Run the TLBIMP utility on the typelibary, like this:
tlbimp cppcomserver.tlb

If successful, you will get a message like this:


Typelib imported successfully to CPPCOMSERVERLib.dll

You now need a .NET client - let's use C#. Create a .cs file containing the following code:
using System; using CPPCOMSERVERLib; public class MainApp { static public void Main() { CppName cppname = new CppName(); cppname.SetName( "bob" ); Console.WriteLine( "Name is " + cppname.GetName() ); } }

Compile the C# code like this:


csc /r:cppcomserverlib.dll csharpcomclient.cs

Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using TLBIMP. You should now be able to run csharpcomclient.exe, and get the following output on the console:
Name is bob

10.5 Can I use .NET components from COM programs?


Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW (see previous question), but works in the opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW can be developed. Also, for COM to 'see' the .NET component, the .NET component must be registered in the registry. Here's a simple example. Create a C# file called testcomserver.cs and put the following in it:
using System; using System.Runtime.InteropServices; namespace AndyMc {

[ClassInterface(ClassInterfaceType.AutoDual)] public class CSharpCOMServer { public CSharpCOMServer() {} public void SetName( string name ) { m_name = name; } public string GetName() { return m_name; } private string m_name; } }

Then compile the .cs file as follows:


csc /target:library testcomserver.cs

You should get a dll, which you register like this:


regasm testcomserver.dll /tlb:testcomserver.tlb /codebase

Now you need to create a client to test your .NET COM component. VBScript will do - put the following in a file called comclient.vbs:
Dim dotNetObj Set dotNetObj = CreateObject("AndyMc.CSharpCOMServer") dotNetObj.SetName ("bob") MsgBox "Name is " & dotNetObj.GetName()

and run the script like this:


wscript comclient.vbs

And hey presto you should get a message box displayed with the text "Name is bob". An alternative to the approach above it to use the dm.net moniker developed by Jason Whittington and Don Box.

10.6 Is ATL redundant in the .NET world?


Yes. ATL will continue to be valuable for writing COM components for some time, but it has no place in the .NET world.

11. Miscellaneous

11.1 How does .NET remoting work?


.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet). Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format.

There are a number of styles of remote access:

SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown
away when the request has finished.

Singleton. All incoming requests from clients are processed by a single server object. Client-activated object. This is the old stateful (D)COM model whereby the client receives a
reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it.

Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure. Objects have a default renew time - the lease is renewed when a successful call is made from the client to the object. The client can also explicitly renew the lease. If you're interested in using XML-RPC as an alternative to SOAP, take a look at Charles Cook's XMLRPC.Net.

11.2 How can I get at the Win32 API from a .NET program?
Use P/Invoke. This uses similar technology to COM Interop, but is used to access static DLL entry points instead of COM objects. Here is an example of C# calling the Win32 MessageBox function:
using System; using System.Runtime.InteropServices; class MainApp { [DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true, CharSet=CharSet.Auto)] 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 ); } }

Pinvoke.net is a great resource for off-the-shelf P/Invoke signatures.

11.3 How do I write to the application configuration file at runtime?


You don't. See http://www.interact-sw.co.uk/iangblog/2004/11/25/savingconfig.

11.4 What is the difference between an event and a delegate?


An event is just a wrapper for a multicast delegate. Adding a public event to a class is almost the same as adding a public multicast delegate field. In both cases, subscriber objects can register for notifications, and in both cases the publisher object can send notifications to the subscribers. However, a public multicast delegate has the undesirable property that external objects can invoke the delegate, something we'd normally want to restrict to the publisher. Hence events - an event adds public

methods to the containing class to add and remove receivers, but does not make the invocation mechanism public. See this post by Julien Couvreur for more discussion.

11.5 What size is a .NET object?


Each instance of a reference type has two fields maintained by the runtime - a method table pointer and a sync block. These are 4 bytes each on a 32-bit system, making a total of 8 bytes per object overhead. Obviously the instance data for the type must be added to this to get the overall size of the object. So, for example, instances of the following class are 12 bytes each:
class MyInt { ... private int x; }

However, note that with the current implementation of the CLR there seems to be a minimum object size of 12 bytes, even for classes with no data (e.g. System.Object). Values types have no equivalent overhead.

12. .NET 2.0

12.1 What are the new features of .NET 2.0?


Generics, anonymous methods, partial classes, iterators, property visibility (separate visibility for get and set) and static classes. See http://msdn.microsoft.com/msdnmag/issues/04/05/C20/default.aspx for more information about these features.

12.2 What are the new 2.0 features useful for?


Generics are useful for writing efficient type-independent code, particularly where the types might include value types. The obvious application is container classes, and the .NET 2.0 class library includes a suite of generic container classes in the System.Collections.Generic namespace. Here's a simple example of a generic container class being used:
List<int> myList = new List<int>(); myList.Add( 10 );

Anonymous methods reduce the amount of code you have to write when using delegates, and are therefore especially useful for GUI programming. Here's an example
AppDomain.CurrentDomain.ProcessExit += delegate { Console.WriteLine("Process ending ..."); };

Partial classes is a useful feature for separating machine-generated code from hand-written code in the same class, and will therefore be heavily used by development tools such as Visual Studio.

Iterators reduce the amount of code you need to write to implement IEnumerable/IEnumerator. Here's some sample code:
static void Main() { RandomEnumerator re = new RandomEnumerator( 5 ); foreach( double r in re ) Console.WriteLine( r ); Console.Read(); } class RandomEnumerator : IEnumerable<double> { public RandomEnumerator(int size) { m_size = size; } public IEnumerator<double> GetEnumerator() { Random rand = new Random(); for( int i=0; i < m_size; i++ ) yield return rand.NextDouble(); } int m_size = 0; }

The use of 'yield return' is rather strange at first sight. It effectively synthethises an implementation of IEnumerator, something we had to do manually in .NET 1.x.

12.3 What's the problem with .NET generics?


.NET generics work great for container classes. But what about other uses? Well, it turns out that .NET generics have a major limitation - they require the type parameter to be constrained. For example, you cannot do this:
static class Disposer<T> { public static void Dispose(T obj) { obj.Dispose(); } }

The C# compiler will refuse to compile this code, as the type T has not been constrained, and therefore only supports the methods of System.Object. Dispose is not a method on System.Object, so the compilation fails. To fix this code, we need to add a where clause, to reassure the compiler that our type T does indeed have a Dispose method
static class Disposer<T> where T : IDisposable { public static void Dispose(T obj) { obj.Dispose(); } }

The problem is that the requirement for explicit contraints is very limiting. We can use constraints to say that T implements a particular interface, but we can't dilute that to simply say that T implements a particular method. Contrast this with C++ templates (for example), where no constraint at all is required - it is assumed (and verified at compile time) that if the code invokes the Dispose() method on a type, then the type will support the method. In fact, after writing generic code with interface constraints, we quickly see that we haven't gained much over non-generic interface-based programming. For example, we can easily rewrite the Disposer class without generics:

static class Disposer { public static void Dispose( IDisposable obj ) { obj.Dispose(); } }

For more on this topic, start by reading the following articles: Bruce Eckel: http://www.mindview.net/WebLog/log-0050 Ian Griffiths: http://www.interact-sw.co.uk/iangblog/2004/03/14/generics Charles Cook: http://www.cookcomputing.com/blog/archives/000425.html Brad Wilson: http://dotnetguy.techieswithcats.com/archives/004273.shtml

12.4 What's new in the .NET 2.0 class library?


Here is a selection of new features in the .NET 2.0 class library (beta 1):

Generic collections in the System.Collections.Generic namespace. The System.Nullable<T> type. (Note that C# has special syntax for this type, e.g. int? is
equivalent to Nullable<int>)

The GZipStream and DeflateStream classes in the System.IO.Compression namespace. The Semaphore class in the System.Threading namespace. Wrappers for DPAPI in the form of the ProtectedData and ProtectedMemory classes in the
System.Security.Cryptography namespace. optimised intra-machine communication.

The IPC remoting channel in the System.Runtime.Remoting.Channels.Ipc namespace, for

13. Class Library

13.1 Threads

13.1.1 How do I spawn a thread?


Create an instance of a System.Threading.Thread object, passing it an instance of a ThreadStart delegate that will be executed on the new thread. For example:
class MyThread { public MyThread( string initData ) { m_data = initData; m_thread = new Thread( new ThreadStart(ThreadMain) ); m_thread.Start(); } // ThreadMain() is executed on the new thread. private void ThreadMain() { Console.WriteLine( m_data ); }

public void WaitUntilFinished() { m_thread.Join(); } private Thread m_thread; private string m_data; }

In this case creating an instance of the MyThread class is sufficient to spawn the thread and execute the MyThread.ThreadMain() method:
MyThread t = new MyThread( "Hello, world." ); t.WaitUntilFinished();

13.1.2 How do I stop a thread?


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.

13.1.3 How do I use the thread pool?


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 ); } // DoWork is executed on a thread from the thread pool. static void DoWork( object state ) { Console.WriteLine( state ); } } // Give time for work item to be executed

13.1.4 How do I know when my thread pool work item has completed?
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.

13.1.5 How do I prevent concurrent access to my data?


Each object has a concurrency lock (critical section) associated with it. The System.Threading.Monitor.Enter/Exit methods are used to acquire and release this lock. For example, instances of the following class only allow one thread at a time to enter method f():
class C { public void f() { try { Monitor.Enter(this); ... } finally { Monitor.Exit(this); } } }

C# has a 'lock' keyword which provides a convenient shorthand for the code above:
class C { public void f() { lock(this) { ... } } }

Note that calling Monitor.Enter(myObject) does NOT mean that all access to myObject is serialized. It means that the synchronisation lock associated with myObject has been acquired, and no other thread can acquire that lock until Monitor.Exit(o) is called. In other words, this class is functionally equivalent to the classes above:
class C { public void f() { lock( m_object ) { ... } } private m_object = new object(); }

Actually, it could be argued that this version of the code is superior, as the lock is totally encapsulated within the class, and not accessible to the user of the object.

13.2 Tracing

13.2.1 Is there built-in support for tracing/logging?


Yes, in the System.Diagnostics namespace. There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.

13.2.2 Can I redirect tracing to a file?


Yes. The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose. Here's how to use the TextWriterTraceListener class to redirect Trace output to a file:
Trace.Listeners.Clear(); FileStream fs = new FileStream( @"c:\log.txt", FileAccess.Write ); Trace.Listeners.Add( new TextWriterTraceListener( fs ) ); Trace.WriteLine( @"This will be writen to c:\log.txt!" ); Trace.Flush();

FileMode.Create,

Note the use of Trace.Listeners.Clear() to remove the default listener. If you don't do this, the output will go to the file and OutputDebugString(). Typically this is not what you want, because OutputDebugString() imposes a big performance hit.

13.2.3 Can I customise the trace output?


Yes. You can write your own TraceListener-derived class, and direct all output through it. Here's a simple example, which derives from TextWriterTraceListener (and therefore has in-built support for writing to files, as shown above) and adds timing information and the thread ID for each trace line:
class MyListener : TextWriterTraceListener { public MyListener( Stream s ) : base(s) { } public override void WriteLine( string s ) { Writer.WriteLine( "{0:D8} [{1:D4}] {2}", Environment.TickCount - m_startTickCount, AppDomain.GetCurrentThreadId(), s ); } protected int m_startTickCount = Environment.TickCount; }

(Note that this implementation is not complete - the TraceListener.Write method is not overridden for example.) The beauty of this approach is that when an instance of MyListener is added to the Trace.Listeners collection, all calls to Trace.WriteLine() go through MyListener, including calls made by referenced assemblies that know nothing about the MyListener class.

13.2.4 Are there any third party logging components available?


Log4net is a port of the established log4j Java logging component.

Contents
1. Introduction o o o o 2. Types o o o o
types? 2.1 What standard types does C# use? 2.2 Is it true that all C# types derive from a common base class? 2.3 So I can pass an instance of a value type to a method that takes an object 1.1 What is C#? 1.2 How do I develop C# apps? 1.3 Does C# replace C++? 1.4 Does C# have its own class library?

as a parameter? 2.4 What are the fundamental differences between value types and reference

o o

2.5 Okay, so an int is a value type, and a class is a reference type. How can int

be derived from object? 2.6 Are C# references the same as C++ references?

3. Classes and Structs o o o o o o o o o


3.1 Structs are largely redundant in C++. Why does C# have them? 3.2 Does C# support multiple inheritance (MI)? 3.3 Is a C# interface the same as a C++ abstract class? 3.4 Are C# constructors the same as C++ constructors? 3.5 Are C# destructors the same as C++ destructors? 3.6 If C# destructors are so different to C++ destructors, why did MS use the

same syntax? 3.7 Are all methods virtual in C#? 3.8 How do I declare a pure virtual function in C#? 3.9 Can I call a virtual method from a constructor/destructor?

o 4. Exceptions o o o o o o

3.10 Should I make my destructor virtual?

4.1 Can I use exceptions in C#? 4.2 What types of object can I throw as exceptions? 4.3 Can I define my own exceptions? 4.4 Does the System.Exception class have any cool features? 4.5 When should I throw an exception? 4.6 Does C# have a 'throws' clause?

5. Run-time Type Information o o 6. Miscellaneous o o o o o o o o 7. C# 2.0 o o 8. Resources o


8.1 Books 7.1 What are the new features in C# 2.0? 7.2 Are C# generics the same as C++ templates? 6.1 How do I do a case-insensitive string comparison? 6.2 Does C# support a variable number of arguments? 6.3 How can I process command-line arguments? 6.4 Does C# do array bounds checking? 6.5 How can I make sure my C# classes will interoperate with other .NET 5.1 How can I check the type of an object at runtime? 5.2 Can I get the name of a type at runtime?

languages? 6.6 How do I use the 'using' keyword with multiple objects? 6.7 What is the difference between == and object.Equals? 6.8 How do I enforce const correctness in C#?

1. Introduction

1.1 What is C#?


C# is a programming language designed by Microsoft. It is loosely based on C/C++, and bears a striking similarity to Java. Microsoft describe C# as follows: "C# is a simple, modern, object oriented, and type-safe programming language derived from C and C+ +. C# (pronounced 'C sharp') is firmly planted in the C and C++ family tree of languages, and will

immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++."

1.2 How do I develop C# apps?


The (free) .NET SDK contains the C# command-line compiler (csc.exe). Visual Studio has fully integrated support for C# development. On Linux you can use Mono.

1.3 Does C# replace C++?


There are three options open to the Windows developer from a C++ background:

Stick with standard C++. Don't use .NET at all. Use C++ with .NET. Microsoft supply a .NET C++ compiler that produces IL rather than machine
code. However to make full use of the .NET environment (e.g. garbage collection), a set of extensions are required to standard C++. In .NET 1.x this extended language is called Managed Extensions for C++. In .NET 2.0 ME C++ has been completely redesigned under the stewardship of Stan Lippman, and renamed C++/CLI.

Forget C++ and use C#.


Each of these options has merits, depending on the developer and the application. For my own part, I intend to use C# where possible, falling back to C++ only where necessary. ME C++ (soon to be C+ +/CLI) is very useful for interop between new .NET code and old C++ code - simply write a managed wrapper class using ME C++, then use the managed class from C#. From experience, this works well.

1.4 Does C# have its own class library?


Not exactly. The .NET Framework has a comprehensive class library, which C# can make use of. C# does not have its own class library.

2. Types

2.1 What standard types does C# use?


C# supports a very similar range of basic types to C++, including int, long, float, double, char, string, arrays, structs and classes. However, don't assume too much. The names may be familiar, but many of the details are different. For example, a long is 64 bits in C#, whereas in C++ the size of a long depends on the platform (typically 32 bits on a 32-bit platform, 64 bits on a 64-bit platform). Also classes and structs are almost the same in C++ - this is not true for C#. Finally, chars and strings in .NET are 16-bit (Unicode/UTF-16), not 8-bit like C++.

2.2 Is it true that all C# types derive from a common base class?
Yes and no. All types can be treated as if they derive from object (System.Object), but in order to treat an instance of a value type (e.g. int, float) as object-derived, the instance must be converted to a

reference type using a process called 'boxing'. In theory a developer can forget about this and let the run-time worry about when the conversion is necessary, but in reality this implicit conversion can have side-effects that may trip up the unwary.

2.3 So I can pass an instance of a value type to a method that takes an object as a parameter?
Yes. For example:
class CApplication { public static void Main() { int x = 25; string s = "fred"; DisplayMe( x ); DisplayMe( s ); } static void DisplayMe( object o ) { System.Console.WriteLine( "You are {0}", o ); } }

This would display:


You are 25 You are fred

2.4 What are the fundamental differences between value types and reference types?
C# divides types into two categories - value types and reference types. Most of the intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, arrays and strings. The basic idea is straightforward - an instance of a value type represents the actual data, whereas an instance of a reference type represents a pointer or reference to the data. The most confusing aspect of this for C++ developers is that C# has predetermined which types are represented as values, and which are represented as references. A C++ developer expects to take responsibility for this decision. For example, in C++ we can do this:
int x1 = 3; // x1 is a value on the stack int *x2 = new int(3) // x2 is a pointer to a value on the heap

but in C# there is no control:


int x1 = 3; // x1 is a value on the stack int x2 = new int(); x2 = 3; // x2 is also a value on the stack!

2.5 Okay, so an int is a value type, and a class is a reference type. How can int be derived from object?
It isn't, really. When an int is being used as an int, it is a value. However, when it is being used as an object, it is a reference to an integer value (on the managed heap). In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the int to the heap, and creating an object instance which refers to it. Unboxing is the reverse process - the object is converted back to a value.
int x = 3; // new int value 3 on the stack object objx = x; // new int on heap, set to value 3 - still have x=3 on stack int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap

2.6 Are C# references the same as C++ references?


Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. In that respect a C# reference is more like a C++ pointer than a C++ reference. If you try to use a null reference, a NullReferenceException is thrown. For example, look at the following method:
void displayStringLength( string s ) { Console.WriteLine( "String is length {0}", s.Length ); }

The problem with this method is that it will throw a NullReferenceException if called like this:
string s = null; displayStringLength( s );

Of course for some situations you may deem a NullReferenceException to be a perfectly acceptable outcome, but in this case it might be better to re-write the method like this:
void displayStringLength( string s ) { if( s == null ) Console.WriteLine( "String is null" ); else Console.WriteLine( "String is length {0}", s.Length ); }

3. Classes and Structs

3.1 Structs are largely redundant in C++. Why does C# have them?
In C++, a struct and a class are pretty much the same thing. The only difference is the default visibility level (public for structs, private for classes). However, in C# structs and classes are very different. In C#, structs are value types (instances stored directly on the stack, or inline within heap-based objects),

whereas classes are reference types (instances stored on the heap, accessed indirectly via a reference). Also structs cannot inherit from structs or classes, though they can implement interfaces. Structs cannot have destructors. A C# struct is much more like a C struct than a C++ struct.

3.2 Does C# support multiple inheritance (MI)?


No, though it does support implementation of multiple interfaces on a single class or struct.

3.3 Is a C# interface the same as a C++ abstract class?


No, not quite. An abstract class in C++ cannot be instantiated, but it can (and often does) contain implementation code and/or data members. A C# interface cannot contain any implementation code or data members - it is simply a group of method names & signatures. A C# interface is more like a COM interface than a C++ abstract class.

3.4 Are C# constructors the same as C++ constructors?


Very similar. A significant difference is that C# supports constructor chaining. This means one constructor can use another:
class Person { public Person( string name, int age ) { ... } public Person( string name ) : this( name, 0 ) {} public Person() : this( "", 0 ) {} }

Another difference is that virtual method calls within a constructor are routed to the most derived implementation - see Can I Call a virtual method from a constructor. Finally, C# has static constructors. The static constructor for a class runs before the first instance of the class is created. Note that (like C++) some C# developers prefer the factory method pattern over constructors. See Brad Wilson's article.

3.5 Are C# destructors the same as C++ destructors?


No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed 'non-deterministic finalization', and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc. To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must

call the Dispose() method when it has finished with the object. C# offers the 'using' construct to make this easier.

3.6 If C# destructors are so different to C++ destructors, why did MS use the same syntax?
Presumably they wanted C++ programmers to feel at home. I think they made a mistake.

3.7 Are all methods virtual in C#?


No. Like C++, methods are non-virtual by default, but can be marked as virtual.

3.8 How do I declare a pure virtual function in C#?


Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).

3.9 Can I call a virtual method from a constructor/destructor?


Yes, but it's generally not a good idea. The mechanics of object construction in .NET are quite different from C++, and this affects virtual method calls in constructors. C++ constructs objects from base to derived, so when the base constructor is executing the object is effectively a base object, and virtual method calls are routed to the base class implementation. By contrast, in .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.) The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.

3.10 Should I make my destructor virtual?


A C# destructor is really just an override of the System.Object Finalize method, and so is virtual by definition.

4. Exceptions

4.1 Can I use exceptions in C#?


Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.

4.2 What types of object can I throw as exceptions?


Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown.

4.3 Can I define my own exceptions?


Yes, as long as you follow the rule that exceptions derive from System.Exception. More specifically, MS recommend that user-defined exceptions inherit from System.ApplicationException (which is derived from System.Exception).

4.4 Does the System.Exception class have any cool features?


Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code:
using System; class CApp { public static void Main() { try { f(); } catch( Exception e ) { Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace ); } } static void f() { throw new Exception( "f went pear-shaped" ); } }

produces this output:


System.Exception stack trace = at CApp.f() at CApp.Main()

Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn't quite what you expect.

4.5 When should I throw an exception?


This is the subject of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an 'unexpected' error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error

is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.

4.6 Does C# have a 'throws' clause?


No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw.

5. Run-time Type Information

5.1 How can I check the type of an object at runtime?


You can use the is keyword. For example:
using System; class CApp { public static void Main() { string s = "fred"; long i = 10; Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") ); Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") ); } static bool IsInteger( object obj ) { if( obj is int || obj is long ) return true; else return false; } }

produces the output:


fred is not an integer 10 is an integer

5.2 Can I get the name of a type at runtime?


Yes, use the GetType method of the object class (which all types inherit from). For example:
using System; class CTest { class CApp

{ public static void Main() { long i = 10; CTest ctest = new CTest(); DisplayTypeInfo( ctest ); DisplayTypeInfo( i ); } static void DisplayTypeInfo( object obj ) { Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName ); } } }

produces the following output:


Type name = CTest, full type name = CTest Type name = Int64, full type name = System.Int64

6. Miscellaneous

6.1 How do I do a case-insensitive string comparison?


Use the String.Compare function. Its third parameter is a boolean which specifies whether case should be ignored or not.
"fred" == "Fred" // false System.String.Compare( "fred", "Fred", true )

// true

6.2 Does C# support a variable number of arguments?


Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine().

6.3 How can I process command-line arguments?


Like this:
using System; class CApp { public static void Main( string[] args ) { Console.WriteLine( "You passed the following arguments:" ); foreach( string arg in args ) Console.WriteLine( arg );

} }

6.4 Does C# do array bounds checking?


Yes. An IndexOutOfRange exception is used to signal an error.

6.5 How can I make sure my C# classes will interoperate with other .NET languages?
Make sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global attribute to your C# source files. The compiler will emit an error if you use a C# feature which is not CLS-compliant.

6.6 How do I use the 'using' keyword with multiple objects?


You can nest using statements, like this:
using( obj1 ) { using( obj2 ) { ... } }

However consider using this more aesthetically pleasing (but functionally identical) formatting:
using( obj1 ) using( obj2 ) { ... }

6.7 What is the difference between == and object.Equals?


For value types, == and Equals() usually compare two objects by value. For example:
int x = 10; int y = 10; Console.WriteLine( x == y ); Console.WriteLine( x.Equals(y) );

will display:
True True

However things are more complex for reference types. Generally speaking, for reference types == is expected to perform an identity comparison, i.e. it will only return true if both references point to the same object. By contrast, Equals() is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent. For example:

StringBuilder s1 = StringBuilder s2 = Console.WriteLine( Console.WriteLine(

new StringBuilder("fred"); new StringBuilder("fred"); s1 == s2 ); s1.Equals(s2) );

will display:
False True

s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true). Unfortunately there are exceptions to these rules. The implementation of Equals() in System.Object (the one you'll inherit by default if you write a class) compares identity, i.e. it's the same as operator==. So Equals() only tests for equivalence if the class author overrides the method (and implements it correctly). Another exception is the string class - its operator== compares value rather than identity. Bottom line: If you want to perform an identity comparison use the ReferenceEquals() method. If you want to perform a value comparison, use Equals() but be aware that it will only work if the type has overridden the default implementation. Avoid operator== with reference types (except perhaps strings), as it's simply too ambiguous.

6.8 How do I enforce const correctness in C#?


You can't - at least not in the same way you do in C++. C# (actually, the CLI) has no real concept of const correctness, For example, there's no way to specify that a method should not modify an argument passed in to it. And there's no way to specify that a method does not modify the object on which it is acting. To get a feel for the angst this causes among some C++ programmers, read the feedback on this post from Raymond Chen. There are of course ways of addressing this issue. For example, see Brad Abram's post (and associated feedback) for some ideas on adding optional read-only behaviour to collection classes.

7. C# 2.0

7.1 What are the new features in C# 2.0?


Support for all of the new framework features such as generics, anonymous methods, partial classes, iterators and static classes. See the .NET FAQ for more on these features. Delegate inference is a new feature of the C# compiler which makes delegate usage a little simpler. It allows you to write this:
Thread t = new Thread(ThreadFunc);

instead of this:

Thread t = new Thread( new ThreadStart(ThreadFunc) );

Another minor but welcome addition is the explicit global namespace, which fixes a hole in namespace usage in C# 1.x. You can prefix a type name with global:: to indicate that the type belongs to the global namespace, thus avoiding problems where the compiler infers the namespace and gets it wrong. Finally C# 2.0 includes some syntactic sugar for the new System.Nullable type. You can use T? as a synonym for System.Nullable<T>, where T is a value type. As suggested by the name, this allows values of the type to be 'null', or 'undefined'.

7.2 Are C# generics the same as C++ templates?


No, not really. There are some similarities, but there are also fundamental differences. See the .NET FAQ for more details.

FAQs
The FAQs have been split into a few broad categories. In many senses, a lot of the FAQs aren't really appropriate for the C# newsgroup in the first place, but that's true of a lot of the posts in the group anyway, and I'd rather people were able to find the answer here than ask a possibly inappropriate question in the group. Where "my" and "I" are used, this tends to indicate Jon Skeet as the initial author of the FAQ. If many extra questions and answers are added which use the first person, I'll convert everything to the third person, but for now I think it'll suffice.

C# and .NET descriptions and history


What is C#? What is .NET? What version of Windows do I need to use .NET? Do I have to be running Windows to use .NET? Does the framework have to be installed to run my .NET application? What do all the acronyms (CLI, CLR, IL etc) mean? What is Whidbey and when is it coming out?

C# as a language

Where is the C# specification? Should I choose VB.NET or C#? Why doesn't C# have VB's 'with' feature? Why doesn't C# have multiple inheritance? Does C# have macros or a preprocessor? Does C# have templates like C++? Are parameters passed by reference or value in C#?

Are constructors inherited in C#? How do I call one constructor from another? What does an @ before the start of a string literal mean? What does an @ before the start of an identifier mean? What character escape sequences are available? Why can't I use static and const together? What's the difference between an event and a delegate? What's the difference between string and System.String? Can I define a property to have different "get" access to "set" access? What's the difference between override and new? What's the difference between using cast syntax and the as operator? How do I use an alias for a namespace or class? Why doesn't C# have checked exceptions? Why are struct constructors in C# required to have at least one argument? How do I tell C# what kind of literal number I want? What's the difference between the ref and out modifiers on parameters? When should I use Equals and when should I use ==?

Converting to C# from VB.NET


What's the equivalent of Nothing? How do I get the rightmost part of a string? What do I use instead of addressof? Is there an equivalent of MyClass? What are the equivalents of Me and MyBase? Is there a fuller comparison between C# and VB.NET?

.NET core libraries


How do I start another program from .NET? How do I make sure that only one instance of my application runs at a time? Why can't I read files with accented characters? Why does .NET get simple arithmetic wrong? How can I call a method when I have its name as a string? How can I show an int as a binary number - a string of 1s and 0s? Why doesn't calling Initialize() on a reference-type array fill the array with objects? Does .NET have any compressiong/zipping capabilities? How do I retrieve assembly attributes at runtime? How do I convert a string to an int etc? What's the difference between Convert.ToInt32(string) and Int32.Parse(string)? How do I create an instance of a type if I only know its name? What's the simplest way of retrieving a web page in .NET?

Windows Forms programming


How do I pass parameters from one form to another? How do I set the background of an MDI container window?

ASP.NET programming
(No questions yet.)

ADO.NET programming

Which should I call on database connections: Dispose or Close? How should I escape text in SQL statements, and express dates and times?

General questions

How can I protect my code against decompilation?

Resources

What other relevant FAQs are available? What online tutorials are available? What are the best C#/.NET books available?

Answers
C# and .NET descriptions and history What is C#?
C# is a language created by Microsoft specifically for the .NET framework. It has been standardised by ECMA for version 1, and version 2 will no doubt go through ECMA when it's been fully released by Microsoft. It is similar in syntax to the C language of families, and also appears to borrow from Java and Delphi. (This is in no way a criticism of it - it's always good to learn from the mistakes and positive aspects of other things.)

What is .NET?
.NET is a platform created by Microsoft. It consists of a virtual execution environment (including garbage collection, JITting, strong versioning, type and memory safety etc) and a large runtime library. It is at the heart of Microsoft's future strategy for the Windows platform, and will be a central part of the next release of Windows (Longhorn).

What version of Windows do I need to use .NET?


The .NET framework itself runs on all versions of Windows from Windows 98/NT4 upwards. It does not run on Windows 95 or NT3.5. For NT4, it requires service pack 6a.

Do I have to be running Windows to use .NET?


There are various (mostly open source) projects to write a CLR (Common Language Runtime) on other operating systems such as Linux and BSD. The two best known are:

Mono - an open source multi-platform system ROTOR - a Microsoft Shared Source implementation for FreeBSD, Windows XP and Mac OS X 10.2. (Link is to a website with a range of links; no one link seems particularly suitable on its own.)

Strictly speaking, these are not actually .NET - .NET is Microsoft's closed-source Windows-only implementation of the CLR and other technologies, including various other framework libraries which aren't all covered in the above projects (which may themselves have libraries which aren't in .NETproper). They do, however, allow you to write programs in C# and run them.

Does the framework have to be installed to run my .NET application?


Yes - if you have a managed application, it will require the framework to be present in order to run. This is like requiring the Win32 libraries to be present in order to run Windows applications. Precompiling your code using ngen doesn't affect this requirement. Having said the above, there are two products which build everything you need from the framework for your application, along with your application itself, into one big bundle:

RemoteSoft's linker and mini-deployment tool Thinstall Studio

Both of these mean the framework itself isn't required, and give additional protection against decompilation. The downside is that if a user then has many such applications, they end up effectively with multiple copies of bits of the framework. I cannot vouch for either of these products myself, as I've had no experience of them.

What do all the acronyms (CLI, CLR, IL etc) mean?


There are many acronyms in .NET and related technologies. They're often abused, including by me, almost always unknowingly. Don't be too worried about them. CIL - Common Intermediate Language The language all .NET languages compile to. Equivalent to Java bytecode. CLI - Common Language Infrastructure The combination of the CLR, CLS, CTS and CIL CLR - Common Language Runtime The runtime environment itself, including garbage collection, threading etc. CLS - Common Language Specification A set of conventions intended to promote language interoperability. CTS - Common Type System The language-neutral type system used in the CLI. IL - Intermediate Language More commonly used abbreviation for CIL. VES - Virtual Execution System Another name for the CLR as far as I can tell.

What is Whidbey and when is it coming out?


Whidbey is the next version of Visual Studio .NET, and is closely tied to V2.0 of the framework. It is likely to be released in the first half of 2005.

C# as a language Where is the C# specification?


There are two versions of the C# specification - one from Microsoft, and one from ECMA. They are the same in all important respects as far as I can tell (a few pieces of explanatory wording are different, but nothing that affects the specification itself) but the numbering of sections is different. The ECMA specification is available as a PDF, or you can email ECMA and they will send you a hard copy for free. Details are on the ECMA website. Alternatively, Jon Jagger's HTML version is available and is a useful download. It is from a draft version, but it's very close to the final version. I don't know whether or not Jon Jagger is planning to make an HTML copy of version 2 of the specification when it's released. The Microsoft version is available online or within the offline version of the MSDN - look for "specifications, Visual C#" in the index to find it quickly.

Should I choose VB.NET or C#?


The choice between C# and VB.NET is largely one of subjective preference. Some people like C#'s terse syntax, others like VB.NET's natural language, case-insensitive approach. Both have access to the same framework libraries. Both will perform largely equivalently (with a few small differences which are unlikely to affect most people, assuming VB.NET is used with Option Strict on). Learning the .NET framework itself is a much bigger issue than learning either of the languages, and it's perfectly possible to become fluent in both - so don't worry too much about which to plump for. There are, however, a few actual differences which may affect your decision:
VB.NET Advantages

Support for optional parameters - very handy for some COM interoperability Support for late binding with Option Strict off - type safety at compile time goes out of the window, but legacy libraries which don't have strongly typed interfaces become easier to use. Support for named indexers (aka properties with parameters). Various legacy VB functions (provided in the Microsoft.VisualBasic namespace, and can be used by other languages with a reference to the Microsoft.VisualBasic.dll). Many of these can be harmful to performance if used unwisely, however, and many people believe they should be avoided for the most part. Some methods here are apparently faster than the more idiomatic .NET equivalent, however. Readability should be considered: using VB functions probably makes the code easier for a VB-classic programmer to read, but harder for someone from a background in another .NET language to read. The with construct: it's a matter of debate as to whether this is an advantage or not, but it's certainly a difference. Simpler (in expression - perhaps more complicated in understanding) event handling, where a method can declare that it handles an event, rather than the handler having to be set up in code. The ability to implement interfaces with methods of different names. (Arguably this makes it harder to find the implementation of an interface, however.) Catch ... When ... clauses, which allow exceptions to be filtered based on runtime expressions rather than just by type. The VB.NET part of Visual Studio .NET compiles your code in the background. While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.

C# Advantages

XML documentation generated from source code comments. (This is coming in VB.NET with Whidbey (the code name for the next version of Visual Studio and .NET), and there are tools which will do it with existing VB.NET code already.) Operator overloading - again, coming to VB.NET in Whidbey. Language support for unsigned types (you can use them from VB.NET, but they aren't in the language itself). Again, support for these is coming to VB.NET in Whidbey. The using statement, which makes unmanaged resource disposal simple. Explicit interface implementation, where an interface which is already implemented in a base class can be reimplemented separately in a derived class. Arguably this makes the class harder to understand, in the same way that member hiding normally does.

Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies). Note that unsafe code is still managed code, i.e. it is compiled to IL, JITted, and run within the CLR.

Despite the fact that the above list appears to favour VB.NET (if you don't mind waiting for Whidbey), many people (myself included) prefer C#'s terse syntax enough to make them use C# instead.

Why doesn't C# have VB's 'with' feature?


Many people, including myself and the C# language designers, believe that 'with' often harms readability, and is more of a curse than a blessing. For more information, see the Ask a C# Language Designer page.

Why doesn't C# have multiple inheritance?


C# (and .NET in general) has multiple inheritance of interface (meaning that you can implement many interfaces in a type) but only single inheritance of implementation (meaning that you can only derive a class from one other class - which may, itself derive from another, etc). (I'll get round to the actual reasoning behind this sooner or later...)

Does C# have macros or a preprocessor?


C# doesn't have macros as such, nor does it strictly speaking have a pre-processor, but it does have conditional compilation symbols which can be used to affect compilation. These can be defined within code or with parameters to the compiler. The "pre-processing" directives in C# (named solely for consistency with C/C++, despite there being no separate pre-processing step) are (text taken from the ECMA specification): and #undef Used to define and undefine conditional compilation symbols #if, #elif, #else and #endif Used to conditionally skip sections of source code
#define #line

Used to control line numbers emitted for errors and warnings. #error and #warning Used to issue errors and warnings. #region and #endregion Used to explicitly mark sections of source code. See section 9.5 of the ECMA specification for more information on the above. Conditional compilation can also be achieved using the Conditional attribute on a method, so that calls to the

method will only be compiled when the appropriate symbol is defined. See section 24.4.2 of the ECMA specifcation for more information on this.

Does C# have templates like C++?


Although C# doesn't have templates, and isn't likely to get them, it is getting a feature called generics which will be available in Whidbey, the next version of .NET, which should be available in the first half of 2005. (A beta version is currently available.) Generics will be a feature in the CLR itself, and most languages targetting the CLR will change to support it. Generics provide a lot of the functionality of C++ templates (mostly in terms of type safety) but in a more restricted (and therefore potentially less confusing) way.

Are parameters passed by reference or value in C#?


By default, all parameters are passed by value in C# - but you need to be aware that when you're passing a reference type, you're passing a reference rather than an actual object. For more information, see my article on parameter passing.

Are constructors inherited in C#?


No, constructors are not inherited. For more information about constructors and constructor chaining, see my article on constructors.

How do I call one constructor from another?


You use : base (parameters) or : this (parameters) just before the actual code for the constructor, depending on whether you want to call a constructor in the base class or in this class. For more information about constructor chaining, see my article on constructors.

What does an @ before the start of a string literal mean?


A string literal such as @"c:\Foo" is called a verbatim string literal. It basically means, "don't apply any interpretations to characters until the next quote character is reached". So, a verbatim string literal can contain backslashes (without them being doubled-up) and even line separators. To get a doublequote (") within a verbatim literal, you need to just double it, e.g. @"My name is ""Jon""" represents the string My name is "Jon". Verbatim string literals which contain line separators will also contain the white-space at the start of the line, so I tend not to use them in cases where the whitespace matters. They're very handy for including XML or SQL in your source code though, and another typical use (which doesn't need line separators) is for specifying a path.

What does an @ before the start of an identifier mean?


When @ appears before an identifier (the name of a variable, property, method etc), it indicates that the compiler should treat what follows as an identifier, even if it normally means something else. For instance, this code fails to compile:
int this = 42; // 'this' is a reserved word

but this code compiles successfully:


int @this = 42;

What character escape sequences are available?


C# defines the following character escape sequences:
\' - single quote, needed for character literals \" - double quote, needed for string literals \\ - backslash \0 - Unicode character 0 \a - Alert (character 7) \b - Backspace (character 8) \f - Form feed (character 12) \n - New line (character 10) \r - Carriage return (character 13) \t - Horizontal tab (character 9) \v - Vertical quote (character 11) \uxxxx - Unicode escape sequence for character with hex value xxxx \xn[n][n][n] - Unicode escape sequence for character with hex value

nnnn (variable length

version of \uxxxx) \Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)

Of these, \a, \f, \v, \x and \U are rarely used in my experience.

Why can't I use static and const together?


All constants declarations are implicitly static, and the C# specification states that the (redundant) inclusion of the static modifier is prohibited. I believe this is to avoid the confusion which could occur if a reader were to see two constants, one declared static and one not - they could easily assume that the difference in specification implied a difference in semantics. (Having said that, there is no prohibition on redundantly specifying an access modifier which is also the default one, where there is a choice. For instance, a (concrete) method can be explicitly marked as private despite that being the

default. The rule appears to be that where there is no choice (e.g. a method declaration in an interface) the redundant modifier is prohibited. Where there is a choice, it's allowed.

What's the difference between an event and a delegate?


Put simply, an event gives more limited access than a delegate. If an event is made public, code in other classes can only add or remove handlers for that event; they can't necessarily fire it, find out all the handlers for it, or remove handlers they don't know about. Events also allow more flexibility in terms of how the handlers are stored. For more details on this, see Eric Gunnerson's article on the topic.

What's the difference between string and System.String?


C# defines a number of aliases for CLR types. They may be used interchangably, and even mixed together, e.g. string x = new System.String(' ', 5);. These are the aliases defined: Alias string sbyte byte short ushort int uint long ulong char float double bool decimal CLR type System.String System.SByte System.Byte System.Int16 System.UInt16 System.Int32 System.UInt32 System.Int64 System.UInt64 System.Char System.Single System.Double System.Boolean System.Decimal

Can I define a property to have different "get" access to "set" access?


Unfortunately, you can't at the moment - if a property is public, it's wholly public. It needn't have a setter (or, in rare cases, it can have a setter but no getter) but you can't have a public getter and a private setter, or vice versa. Thankfully, this is being changed in Whidbey.

What's the difference between override and new?

This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class. For instance:
public class Base { public virtual void SomeMethod() { } } public class Derived : Base { public override void SomeMethod() { } } ... Base b = new Derived(); b.SomeMethod();

will end up calling Derived.SomeMethod if that overrides Base.SomeMethod. Now, if you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it. In that case, code like this:
public class Base { public virtual void SomeOtherMethod() { } } public class Derived : Base { public new void SomeOtherMethod() { } } ... Base b = new Derived(); Derived d = new Derived(); b.SomeOtherMethod(); d.SomeOtherMethod();

Will first call Base.SomeOtherMethod (line 3), then Derived.SomeOtherMethod (line 4). They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method. If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword). That provides the basics of overriding and the difference between new and override, but you should really see a book or tutorial for a more in-depth look at polymorphism.

How can I call a method when I have its name as a string?


What you need is reflection. The basic idea is that you find the type which contains the method, find the method from that type, and then invoke it. Here's a sample program - it's simple (it doesn't pass any parameters, it only finds a public method, it doesn't use a return value) but it gives the basic idea. Look up the relevant methods in MSDN for more information.
using System; using System.Reflection; class Test { string name; Test (string name) { this.name = name; } public void ShowName() { Console.WriteLine(name); } static void Main() { // Create an instance of Test Test t = new Test ("Foo"); // Get the method we want to call MethodInfo mi = typeof(Test).GetMethod("ShowName"); // Call it on the instance we've created, // with no arguments mi.Invoke (t, null); }

What's the difference between using cast syntax and the as operator?
Using the as operator differs from a cast in C# in three important ways: 1. It returns a null when the variable you are trying to convert is not of the requested type or in it's inheritance chain, instead of throwing an exception. 2. It can only be applied to reference type variables converting to reference types. 3. Using as will not perform user-defined conversions, such as implicit or explicit conversion operators, which casting syntax will do. There are in fact two completely different operations defined in IL that handle these two keywords (the castclass and isinst instructions) - it's not just "syntactic sugar" written by C# to get this different behavior. The as operator appears to be slightly faster in v1.0 and v1.1 of Microsoft's CLR compared to casting (even in cases where there are no invalid casts which would severely lower casting's performance due to exceptions).

How do I use an alias for a namespace or class?


Use the using directive to create an alias for a long namespace or class. You can then use it anywhere you normally would have used that class or namespace. The using alias has a scope within the namespace you declare it in. Sample code:
// Namespace: using act = System.Runtime.Remoting.Activation; // Class: using list = System.Collections.ArrayList; ... list l = new list(); // Creates an ArrayList act.UrlAttribute foo; // Equivalent to System.Runtime.Remoting.Activation.UrlAttribute foo

Why doesn't C# have checked exceptions?


Checked exceptions are a very hotly debated topic in some circles, particularly for experienced Java developers moving to, or additionally learning, C#. Here are some resources that discuss the issue in depth:

The Trouble With Checked Exceptions (Anders Hejlsberg, Bruce Eckel, Bill Venners) Does Java Need Checked Exceptions? (Bruce Eckel)

Note that without the CLR itself supporting checked exceptions, it would be effectively impossible for C# to do so alone.

Why are struct constructors in C# required to have at least one argument?


The .NET runtime can't guarantee that parameterless constructors will be called. If structs where to allow default, parameterless constructors, it would imply that these default constructors would *always* be called. However, the runtime can not make this guarantee. For example an array of value types will be initialized to the initial values of it's members (i.e. 0 for number type primitive members, null for reference types etc) not to the values provided in a default constructor - which makes structs better performing by not having to call constructor code. Enforcing a minimum of one parameter in the constructor reduces the possibility that someone will define a constructor that they then expect to be called every time one of their struct types is constructed.

How do I tell C# what kind of literal number I want?


If you need to tell C# that you want it to treat a literal as a particular type of number, you may do so by adding a number type suffix at the end of the literal you provide. For example:
1U; // An unsigned int 1ul; // An unsigned long 1f; // A System.Single floating-point number; 1d; // A System.Double floating-point number 1m; // a System.Decimal floating-point number

This is somewhat important because sometimes you must match a literal to the signature of something or specify the value to 'defeat' an implicit cast behavior you don't like. For example, Hashtable names = new Hashtable(100, 0.1); won't compile because the constructor takes parameters (int, float) and the above is (int, double). The line should read Hashtable names = new
Hashtable(100, 0.1f);

A full listing of the suffixes is in the Grammar portion of the C# specification (appendix A in the ECMA specification, appendix C in the MS specification). The suffixes are also detailed in the Literals section of the specification (9.4.4 of the ECMA specification, 2.4.4 of the MS specification).

What's the difference between the ref and out modifiers on parameters?
Both the ref and out modifiers are applied to arguments of a method and both mean that the argument will be passed "by reference" (either a value type variable by reference or a reference type variable by reference). The out parameter, however, allows you to pass in an uninitialized variable like so and guarantees it will come back with it's value set (so long as the called method was written in C#, anyway).
int i; DoStuffByRef(out i); // i is now a usable int value

For more details, see my article on parameter passing.

When should I use Equals and when should I use ==?


The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour. For reference types where == has not been overloaded, it compares whether two references refer to the same object - which is exactly what the implementation of Equals does in System.Object. Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared. However, the main difference between the two types of comparison in normal use (where you're unlikely to be defining your own value types very often) is polymorphism. Operators are overloaded, not overridden, which means that unless the compiler knows to call the more specific version, it'll just call the identity version. To illustrate that, here's an example:
using System; public class Test { static void Main() { // Create two equal but distinct strings string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'}); string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'}); Console.WriteLine (a==b); Console.WriteLine (a.Equals(b)); // Now let's see what happens with the same tests but // with variables of type object object c = a; object d = b; Console.WriteLine (c==d); Console.WriteLine (c.Equals(d)); } }

The results are:


True True False True

The third line is False because the compiler can only call the non-overloaded version of == as it doesn't know that the contents of c and d are both string references. As they are references to different strings, the identity operator returns false. So, when should you use which operator? My rule of thumb is that for almost all reference types, use Equals when you want to test equality rather than reference identity. The exception is for strings comparing strings with == does make things an awful lot simpler and more readable but you need to remember that both sides of the operator must be expressions of type string in order to get the comparison to work properly. For value types, I'd normally use == for easier-to-read code. Things would get tricky if a value type provided an overload for == which acted differently to Equals, but I'd consider such a type very badly designed to start with.

Converting to C# from VB.NET What's the equivalent of Nothing?


For reference types, the equivalent of VB's Nothing is C#'s null. For value types, it's the default value - 0, false, etc.

How do I get the rightmost part of a string?


Use String.Substring. Assuming that x is a string of length at least n, to get the last n characters, you would use x.Substring(x.Length-n).

What do I use instead of addressof?


To create delegate instances in C#, you just specify the delegate type, the method, and (if you want to create a delegate targetting a different instance or type from the current one) the target. For instance, each of these creates a ThreadStart delegate:
ThreadStart x1 = new ThreadStart(SomeInstanceMethod); ThreadStart x2 = new ThreadStart(AnotherType.SomeStaticMethod);

ThreadStart x3 = new ThreadStart(someVariable.SomeInstanceMethod);

Is there an equivalent of MyClass?


No, C# doesn't have an equivalent of VB.NET's MyClass keyword. If you want to guarantee not to call an overridden version of a method, you need to make it non-virtual in the first place.

What are the equivalents of Me and MyBase?


in C# is this, and MyBase in C# is base. To access normal members, just use this.memberName or base.memberName. For information about chaining constructors together, see my article on constructors.
Me

Is there a fuller comparison between C# and VB.NET?


Microsoft provides a very full language equivalents page which compares not only C# and VB.NET, but also other languages targeted at the .NET framework. It looks at the equivalent concepts, keywords, types, operators etc. A very valuable resource when you're trying to read or write code in a language which isn't your preferred one.

.NET core libraries How do I start another program from .NET?


You need to use the Process.Start method. You can build more complicated start-up parameters using the ProcessStartInfo class which allows you to specify command line parameters, redirect output etc. The ProcessStartInfo and Process classes are in the System.Diagnostics namespace.

How do I make sure that only one instance of my application runs at a time?
Probably the best way of accomplishing this is using a named mutex. Create the mutex using code such as:
bool firstInstance; Mutex mutex = new Mutex(false, "Local\\"+someUniqueName, out firstInstance); // If firstInstance is now true, we're the first instance of the application;

// otherwise another instance is running.

Note that the mutex is a local one, which means it's in the current user's session - without the local part, other users would share the mutex, so two different users couldn't run the program at the same time. Also note that (unlike various samples around the net) my code doesn't have a call to ReleaseMutex - this is because the mutex will automatically be released when the process dies, which is usually the desired behaviour anyway. One thing to beware of is that the mutex isn't garbage collected. If a local variable is only used near the start of a method, the GC may ignore it when working out which variables are garbage collection "roots" if that part of the method has already been executed. This can lead to the mutex being released earlier than you might anticipate! To prevent this from happening, make a call to GC.KeepAlive (mutex); at the end of your main method. Alternatively, use a static variable to store the mutex. That will ensure that the mutex is not garbage collected until the AppDomain is unloaded. (That way even if Main terminates, you won't have any problems if you've got other threads running.) Another way of attacking the problem (which comes with its own issues) is to listen on a local port. As only one process can listen on any particular port, that can ensure that no other instance of your application is running. However, it could just be that another application wants to use that port, in which case either your application will think there's another instance running, or the other application is likely to malfunction. Note that this approach has the added benefit that it provides a communication channel between the "main" instance and the newly created instance - if, say, the newly created instance wants to tell the main instance to open a file that the user has just requested, it can do so using the socket.

Why can't I read files with accented characters?


Whenever text is stored in a file, or sent across a network, it is always encoded in some way or other, to convert the characters into bytes. It then needs to be decoded to get the characters back again. If you use the wrong encoding, you (naturally) get the wrong results. This is usually the cause of a failure to see "extended" characters. It's a big topic, so see my article on Unicode for more information.

Why does .NET get simple arithmetic wrong?


.NET doesn't get arithmetic wrong, as such - it just does arithmetic in a different way to how you might expect. For instance, when you write 0.1 in code to be stored in a double variable, the value stored isn't actually 0.1. It's as close to 0.1 as can be represented in the double type, but it's not actually 0.1. This is because the float/double types are binary floating point types, and 0.1 (decimal) can't be exactly represented in base 2. For more information on this, see my article on .NET floating point types.

How can I show an int as a binary number - a string of 1s and 0s?


The Convert class has an overload of the static ToString() method that takes two ints and returns a string populated with the number in the specified base. For instance, calling Convert.ToString(128, 2) will return "10000000".

Why doesn't calling Initialize() on a reference-type array fill the array with objects?
The System.Array class instance method Initialize() exists solely to initialize value type arrays to their default values and is not valid on reference type arrays. (In fact it is not even intended for C# value type structs, as these structs can have no default constructor for Initialize to call. CLR value types are allowed to have parameterless constructors, but there's no way of creating such a type in C#.)

Does .NET have any compressiong/zipping capabilities?


The .NET framework doesn't contain any general purpose compression libraries, but there are plenty of third-party libraries available. The most commonly referenced is probably SharpZipLib, which is free and open source but may still be used in commercial applications.

How do I retrieve assembly attributes at runtime?


Most of the assembly-wide attributes (which are usually specified in AssemblyInfo.cs) are available using Assembly.GetCustomAttributes. For instance, to get the assembly title, you could use code such as:
Assembly thisAsm = this.GetType().Assembly; object[] attrs = thisAsm.GetCustomAttributes(typeof(AssemblyTitleAttribute), false)); if (attrs.Length == 1) { Console.WriteLine(((AssemblyTitleAttribute)attrs[0]).Title); }

Note, however, that AssemblyVersionAttribute ends up as just part of the assembly name, which can be retrieved with the Assembly.GetName method. The version can be retrieved from the name with the Version property. For example:
Assembly thisAsm = this.GetType().Assembly; Console.WriteLine (thisAsm.GetName().Version);

How do I convert a string to an int etc?


In general, when you want to convert from one type to another, the first class to look at is System.Convert. It has a load of static methods which are likely to help you. If you're converting from a String, you could also check whether the type that you want to convert to has a Parse method or something similar - for instance, I usually use DateTime.ParseExact to convert from a String to a DateTime.

What's the difference between Convert.ToInt32(string) and Int32.Parse(string)?


The two give identical results, except where the string is null. Convert.ToInt32(null) returns zero, whereas Int32.Parse(null) throws an ArgumentNullException.

How do I create an instance of a type if I only know its name?


This is a two stage process. Firstly, you need to get a Type reference for the type. If the type you want to create an instance of is in either mscorlib or the current assembly, you can just use Type.GetType(name). If it's in a different assemby, you could either call Type.GetType and pass in the full type name including assembly information, or you could find or load the assemnbly and then call Assembly.GetType(name) on that assembly reference. Once you've got a Type reference, you can either use Activator.CreateInstance(type) to create an instance, or call Type.GetConstructor to get a specific constructor which you can then use to create an instance by calling Invoke on it.

What's the simplest way of retrieving a web page in .NET?


For a good mixture of flexibility and ease of use, the System.Net.WebRequest class is a good way of retrieving web content. Some very simple code is given below, but there are many options available including asynchronous downloads and lots of properties to both set and retrieve for the request and response. For some very simple scenarios, System.Net.WebClient is an alternative providing limited but very easy to use functionality.
using System.Net; using System.IO; using System.Text; ... string url = "http://www.microsoft.com"; WebRequest req = WebRequest.Create(url);

// // // // //

If the URL is an HTTP one, you can cast req to HttpWebRequest, which allows you to set more properties, such as the user agent. Similarly, a response to an HTTP request can be cast to HttpWebResponse.

using (WebResponse resp = req.GetResponse()) { // Make sure you use the right encoding // if you don't know it in advance, you should // look at the response to see what the web server // says it is. For binary content, you'd // want to use the stream directly instead // of wrapping it in a StreamReader. using (StreamReader reader = new StreamReader (resp.GetResponseStream(), Encoding.UTF8)) { string content = reader.ReadToEnd(); // Do whatever you want with the content here } }

Windows Forms programming How do I pass parameters from one form to another?
Forms are just objects like any other. To call a method or pass a parameter from one form to another, you need to have a reference to the "target" form in the "source" form, and the method/property/whatever of the "target" form needs to be accessible (which usually means at least "internal" visibility).

How do I set the background of an MDI container window?


The area of an MDI container window is covered by an MdiClient control, so Form.BackColor and Form.BackgroundImage don't do anything useful. Instead, iterate through the controls to find the MdiClient, like this:
private void Form_Load(object sender, System.EventArgs e) { foreach (Control ctl in this.Controls) { if (ctl is MdiClient) // found it { ctl.BackColor = Color.Yellow;

break; } } }

If you need to update the MDI background when the window is resized - to keep a logo in the centre, for example - you must handle the Paint event for the MdiClient.

ASP.NET programming ADO.NET programming Which should I call on database connections: Dispose or Close?
As far as I can tell, the only difference between calling Close and Dispose on database connections should be that Close leaves the connection in a reusable but closed state - you can still access all the properties, etc, and even call Open again. As with any object, after calling Dispose on a database connection, you shouldn't access it any further. This does not mean that calling Dispose removes the connection from the connection pool, however. There is a sort of urban myth that it does, and that you should therefore only call Close on connections, and not Dispose. Fortunately, it's untrue according to tests I've performed. I say "fortunately" because it lends consistency to the framework - basically, you should always be able to call Dispose on an instnace of any type implementing IDisposable without suffering from problems - it should (in my view) be considered the "default" way of releasing non-memory resources. This is supported by the C# "using" statement which makes it so easy to automatically call Dispose. Just as I never call Close on a Stream, I never call Close on a database connection unless I specifically want to reuse it later.

How should I escape text in SQL statements, and express dates and times?
The answer here is not to put the data in your SQL statements at all, but to use parameters. Every data provider worth using provides a way of specifying parameters in SQL statements, either named (e.g. SELECT NAME FROM PEOPLE WHERE ID=@ID) or positional (e.g. SELECT NAME FROM PEOPLE WHERE ID=?). Some providers only support positional parameters, others only support named parameters, others support both. In practice it's not hard to work in a consistent way with either, by always using sensible names and always specifying the command's parameters in the same order that they appear in the SQL statement. Parameters are basically a mechanism for having a single SQL statement which can take different values for some parts. You use a SqlCommand (or the equivalent for your database provider) to specify the query text, the type of the command (stored procedure, text, etc) and the parameters. You set the

command up with parameters once, and then you can use the command several times, having set the parameter values up with the relevant data for each request. If you're using a DataAdapter to update your database, the parameter values for the relevant command (update, insert or delete) are filled in automatically, assuming you've set the parameters up correctly. Parameters allow you to write your SQL without worrying about escaping values or formatting dates and times etc. The database provider will do all that (assuming it even needs to). You don't need to worry about SQL injection attacks - whatever parameter value you specify, it won't be used as SQL itself. Parameters also make life easier for the database - it can cache the query you've provided it so that it doesn't need to do as much work on future requests - it knows everything apart from the actual parameter values already. In short, parameters are wonderful things, and should be used whenever you've got values which may change for different requests. It even makes life easier if you're always going to use the same value, if that value is anything complicated (like a string which may require escaping, or a date and time which requires formatting). For more information about using parameters in database access, see the documentation for whichever database provider you're using. The command type for your provider is likely to have a Parameters property which is a good starting point for finding out more.

General Questions How can I protect my code against decompilation?


Many people have intellectual property concerns about .NET, because it's easy to decompile IL into C# or VB.NET, and the code produced is often remarkably similar to the original source. Personally I feel that most of the time these concerns are misplaced. If your application becomes sufficiently popular that people are decompiling it, chances are you're making significant money from it anyway. If you're worried about your algorithsm themselves being poached, I believe that the overall design of an application or architecture is usually more valuable than a specific algorithm. If you're concerned about the security of private keys (or whatever) which are in your code, you're relying on security through obscurity to start with, which is never a good idea. Valid IL can always be decompiled to some extent, and modifying it so that it's no longer the kind of IL which is "naturally" produced by the C# or VB.NET compilers is likely to have a negative performance impact as the JIT will have been tailored towards the output of those compilers. However, you can go a long way by using an obfuscator. Obfuscators change the names in code (where possible) so that lumps of code become a lot less meaningful. For most sufficiently large apps, I believe this to be "good enough" protection as understanding a large app with no source documentation is hard enough originally, let alone with mangled names. One possible exception to this is licence-handling code - if someone can work out which part of your code is responsible for checking that the installation is licensed, it may well be simple for them to disable it. Of course, with a large program with type names which are no longer readable, it may not always be easy to do this in the first place...

RemoteSoft's linker (see an earlier question) provides more protection than a normal obfuscator, as the IL is no longer present. (This is in contrst to ngen, which precompiles the code but still maintains the IL.) Note that even this is only going to increase the protection rather than giving absolute protection though - if someone has your code and can run it, they can work out how it does what it does, given enough time and patience. This has always been true, and gives one of the benefits of server-side code, where the user never actually has your code at all, only the results of specific requests etc. There are many obfuscators around, some free and some commercial. VS.NET 2003 comes with the community version of Dotfuscator. See the .NET tools list on MSDN for other options. I don't have any experience of Dotfuscator or any other .NET obfuscators.

GeneralQuestions 1. Does C# support multiple-inheritance? No, use interfaces instead. 2. When you inherit a protected class-level variable, who is it available to? Classes in the same namespace. 3. 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. 4. Describe the accessibility modifier protected internal. It is available to derived classes and classes within the same Assembly (and naturally from the base class its declared in). 1. To do: Confirm the within the same assembly portion.

5. C# provides a default class constructor for me. I decide to write a constructor that takes a string as a parameter, but want to keep the constructor that has no parameter. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if theres no implementation in it. 6. Whats the top .NET class that everything is derived from? System.Object. 7. 1. answer the question. What does the term immutable mean?

8. Whats the difference between System.String and System.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. 9. Whats 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 its being operated on, a new instance is created. 10. Can you store multiple data types in System.Array? No. 11. Whats the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow. 1. To do: improve the answer.

12. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. 13. Whats the .NET class that allows the retrieval of a data element using a unique key? HashTable. 14. What class is underneath the SortedList class? A sorted HashTable. 15. Will the finally block get executed if an exception has not occurred? Yes. 16. Whats the C# equivalent of C++ catch (), which was a catch-all statement for 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 {}. 1. To do: Bad question. Re-word.

17. Can multiple catch blocks be executed? No. Once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block. 18. 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). 19. What is the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed. 1. To do: Improve the answer.

Class Questions 20. How do you inherit from a class in C#? Place a colon and then the name of the base class. 21. Can you prevent your class from being inherited by another class? Yes. The keyword sealed will prevent the class from being inherited. 22. 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. 23. Whats 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. 24. When do you absolutely have to declare a class as abstract? 1. When at least one of the methods in the class is abstract.

2. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.

25. Whats an interface class? Its an abstract class with public abstract methods all of which must be implemented in the inherited classes. 26. Why cant you specify the accessibility modifier for methods inside the interface? They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, its public by default. 1. To do: Clean up this answer.

27. Can you inherit multiple interfaces? Yes, why not. 1. To do: Need a better answer.

28. And if they have conflicting method names? Its 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 youre okay. 29. Whats the difference between an interface and abstract class? In an interface class, all methods must be abstract. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed, which is ok in an abstract class. 30. 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. (questions courtesy of Eyal) Method and Property Questions 31. Whats 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. 32. What does the keyword virtual declare for a method or property? The method or property can be overridden. 33. 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. 34. Can you declare an override method to be static if the original method is non-static? No. The signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override. 1. To do: Re-word the answer for better clarity.

35. Can you override private virtual methods? No. Private methods are not accessible outside the class. 1. Original answer: No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access. 2. To do: Can a private method even be declared a virtual?

36. What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters. 37. If a base class has a number of overloaded constructors, and an inherited 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. 1. To do: question is to complex. It can be stated better.

38. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project. 39. Whats a delegate? A delegate object encapsulates a reference to a method. 40. Whats a multicast delegate? Its a delegate that points to and eventually fires off several methods. 1. Assembly Questions 41. 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. 42. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command. 43. 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. 44. What namespaces are necessary to create a localized application? System.Globalization and System.Resources. XML Documentation Questions 45. Whats the difference between // comments, /* */ comments and /// comments? Single-line comments, multi-line comments, and XML documentation comments. 46. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with the /doc switch. To do: Need a better answer.

47.What is the difference between and XML documentation tag? Single line code example and multiple-line code example. 1. To do: Bad question 48. Is XML case-sensitive? Yes. Debugging and Testing Questions 49. 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.

50. What does the This window show in the debugger? It points to the object thats pointed to by this reference. Objects instance data is shown. 1. To do: Need a better answer.

51. 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. 52. Whats 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. 53. 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. 54. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor. 55. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger. 56. What are three test cases you should go through in unit testing? 1. 2. 3. Positive test cases (correct data, correct output). Negative test cases (broken or missing data, proper handling). Exception test cases (exceptions are thrown and caught properly).

57. Can you change the value of a variable while debugging Yes. If you are debugging via Visual Studio.NET, just go to Immediate window. ADO.NET and Database Questions

C#

application?

58. 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 its not as fastest and efficient as SqlServer.NET. 59. What is the wildcard character in SQL? Lets 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%. 60. 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 hasnt. 3. 4. Isolated - no transaction sees the intermediate results of the current transaction). Durable - the values persist if the data had been committed even if the system crashes right after.

61. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password). 62. 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. 1. To do: ask the question better.

63. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications. 1. To do: answer better.

64. What does the Initial Catalog parameter define in the connection string? The database name to connect to. 65. What is the data provider name to connect to an Access database? Microsoft.Access. 66. What does the Dispose method do with the connection object? Deletes it from the memory.

1.

To do: answer better. The current answer is not entirely correct.

67. 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.

Deference bw Abstract and Interface: In the Object orient design Interface is nothing like a Class without having the implementation, Interface default access specifies is public not usual like a class representation. Interface can have method, properties and events. The advantage interface provides is high level abstract of how the implementation is done. In the design prospective interface no need to know how the implementation and where the implementation is happened. For C++ world interface is nothing but all method in that particular class is having pure virtual functions. Interface methods must need to implement when the class is derived from the interface. In any thing is not implemented in the class level what ever is there in interface compiler provides the error notification to the developer. The UML Design notation the Interface looks like this: In this figure Shape is the interface having the Area () method without having the implementation. In that Circle, square, and rectangle class having various values and varies implementation of the area based on that class, in this scenarios interface with implementation class will help. The highlight of the interface is: Interface should not have any implementation. Interface can not create any instance. Interface should provide high level abstraction from the implementation. Interface can have multiple inheritances. Default access level of the interface is public.

Abstract class A class is said to be a abstract class it should have at least one ore more abstract methods and some of the method having the implementation also in that case that type of class is called abstract class. The requirement of abstract class, if the designer things the common implementation we can put in abstract class instead of implementing the all the derived class. The highlight of the Abstract class is: Abstract class should have at least one or more method should not have any implementation. Instance can not be created for the abstract class. Common implementation will implemented in the abstract base class (ABC)

The UML usage notation of Abstract class looks like this: In the case of the ABC, Get Balance() method is very common to both saving as well as current account in that case, instead implementing Get Balance() we will implement in base class and consume in derive class. But in the case of print Balance () is abstract method that must need to implement in the derived classes to get there own implementation.

Summary Based on the useage we have to choose interface / Abstract classes. 1. What is datagrid? The DataGrid Web server control is a powerful tool for displaying information from a data source. It is easy to use; you can display editable data in a professional-looking grid by setting only a few properties. At the same time, the grid has a sophisticated object model that provides you with great flexibility in how you display the data. 2. Whats the difference between the System.Web.UI.WebControls.DataGrid and and System.Windows.Forms.DataGrid? The Web UI control does not inherently support masterdetail data structures. As with other Web server controls, it does not support two-way data binding. If you want to update data, you must write code to do this yourself. You can only edit one row at a time. It does not inherently support sorting, although it raises events you can handle in order to sort the grid contents. You can bind the Web Forms DataGrid to any object that supports the IEnumerable interface. The Web Forms DataGrid control supports paging. It is easy to customize the appearance and layout of the Web Forms DataGrid control as compared to the Windows Forms one. 3. How do you customize the column content inside the datagrid? If you want to customize the content of a column, make the column a template column. Template columns work like item templates in the DataList or Repeater control, except that you are defining the layout of a column rather than a row. 4. How do you apply specific formatting to the data inside the cells? You cannot specify formatting for columns generated when the grids AutoGenerateColumns property is set to true, only for bound or template columns. To format, set the columns DataFormatString property to a string-formatting expression suitable for the data type of the data you are formatting. 5. How do you hide the columns? One way to have columns appear dynamically is to create them at design time, and then to hide or show them as needed. You can do this by setting a columns Visible property. 6. How do you display an editable drop-down list? Displaying a drop-down list requires a template column in the grid. Typically, the ItemTemplate contains a control such as a data-bound Label control to show the current value of a field in the record. You then add a drop-down list to the EditItemTemplate. In Visual Studio, you can add a template column in the Property builder for the grid, and then use standard template editing to remove the default TextBox control from the EditItemTemplate and drag a DropDownList control into it instead. Alternatively, you can add the template column in HTML view. After you have created the template column with the drop-down list in it, there are two tasks. The first is to populate the list. The second is to preselect the

appropriate item in the list for example, if a books genre is set to fiction, when the dropdown list displays, you often want fiction to be preselected. 7. How do you check whether the row data has been changed? The definitive way to determine whether a row has been dirtied is to handle the changed event for the controls in a row. For example, if your grid row contains a TextBox control, you can respond to the controls TextChanged event. Similarly, for check boxes, you can respond to a CheckedChanged event. In the handler for these events, you maintain a list of the rows to be updated. Generally, the best strategy is to track the primary keys of the affected rows. For example, you can maintain an ArrayList object that contains the primary keys of the rows to update.

.NET deployment questions


1. What do you know about .NET assemblies? Assemblies are the smallest units of versioning and deployment in the .NET application. Assemblies are also the building blocks for programs such as Web services, Windows services, serviced components, and .NET remoting applications. 2. Whats the difference between private and shared assembly? Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name. 3. Whats a strong name? A strong name includes the name of the assembly, version number, culture identity, and a public key token. 4. How can you tell the application to look for assemblies at the locations other than its own install? Use the directive in the XML .config file for a given application. <probing privatePath="c:\mylibs; bin\debug /> should do the trick. Or you can add additional search paths in the Properties box of the deployed application. 5. How can you debug failed assembly binds? Use the Assembly Binding Log Viewer (fuslogvw.exe) to find out the paths searched. 6. Where are shared assemblies stored? Global assembly cache. 7. How can you create a strong name for a .NET assembly? With the help of Strong Name tool (sn.exe). 8. Wheres global assembly cache located on the system? Usually C:\winnt\assembly or C:\windows\assembly. 9. Can you have two files with the same file name in GAC? Yes, remember that GAC is a very special folder, and while normally you would not be able to place two files with the same name into a Windows folder, GAC differentiates by version number as well, so its possible for MyApp.dll and MyApp.dll to co-exist in GAC if the first one is version 1.0.0.0 and the second one is 1.1.0.0. 10. So lets say I have an application that uses MyApp.dll assembly, version 1.0.0.0. There is a security bug in that assembly, and I publish the patch, issuing it under name MyApp.dll 1.1.0.0. How do I tell the client applications that are already installed to start using this new MyApp.dll? Use publisher policy. To configure a publisher policy, use the publisher policy configuration file, which uses a format similar app .config file. But unlike the app .config file, a publisher policy file needs to be compiled into an assembly and placed in the GAC.

11. What is delay signing? Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.

Windows code security questions


1. Whats the difference between code-based security and role-based security? Which one is better? Code security is the approach of using permissions and permission sets for a given code to run. The admin, for example, can disable running executables off the Internet or restrict access to corporate database to only few applications. Role-based security most of the time involves the code running with the privileges of the current user. This way the code cannot supposedly do more harm than mess up a single user account. Theres no better, or 100% thumbs-up approach, depending on the nature of deployment, both code-based and role-based security could be implemented to an extent. 2. How can you work with permissions from your .NET application? You can request permission to do something and you can demand certain permissions from other apps. You can also refuse permissions so that your app is not inadvertently used to destroy some data. 3. How can C# app request minimum permissions? using System.Security.Permissions; [assembly:FileDialogPermissionAttribute(SecurityAction.RequestMinimum, Unrestricted=true)] 4. Whats a code group? A code group is a set of assemblies that share a security context. 5. Whats the difference between authentication and authorization? Authentication happens first. You verify users identity based on credentials. Authorization is making sure the user only gets access to the resources he has credentials for. 6. What are the authentication modes in ASP.NET? None, Windows, Forms and Passport. 7. Are the actual permissions for the application defined at run-time or compile-time? The CLR computes actual permissions at runtime based on code group membership and the calling chain of the code.

ASP.NET questions, part 2


ASP.NET interview questions, part 1 1. Whats an assembly? Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

2. Describe the difference between inline and code behind - which is best in a loosely coupled solution? ASP.NET supports two modes of page development: Page logic code that is written inside <script runat=server> blocks within an .aspx file and dynamically compiled the first time the page is requested on the server. Page logic code that is written within an external class that is compiled prior to deployment on a server and linked "behind" the .aspx file at run time. 3. Explain what a diffgram is, and a good use for one? A DiffGram is an XML format that is used to identify current and original versions of data elements. The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order. 4. Where would you use an iHTTPModule, and what are the limitations of anyapproach you might take in implementing one? One of ASP.NETs most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the request in a custom HTTP module. 5. What are the disadvantages of viewstate/what are the benefits? 6. Describe session handling in a webfarm, how does it work and what are the limits? 7. How would you get ASP.NET running in Apache web servers - why would you even do this? 8. Whats MSIL, and why should my developers need an appreciation of it if at all? 9. In what order do the events of an ASPX page execute. As a developer is it important to undertsand these events? Every Page object (which your .aspx page is) has nine events, most of which you will not have to worry about in your day to day dealings with ASP.NET. The three that you will deal with the most are: Page_Init, Page_Load, Page_PreRender. 10. Which method do you invoke on the DataAdapter control to load your generated dataset with data? System.Data.Common.DataAdapter.Fill(System.Data.DataSet); If my DataAdapter is sqlDataAdapter and my DataSet is dsUsers then it is called this way: sqlDataAdapter.Fill(dsUsers); 11. ata in the Repeater control? 12. Which template must you provide, in order to display data in a Repeater control? ItemTemplate 13. How can you provide an alternating color scheme in a Repeater control? AlternatingItemTemplate Like the ItemTemplate element, but rendered for every other row (alternating items) in the Repeater control. You can specify a different appearance for the AlternatingItemTemplate element by setting its style properties. 14. 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? You must set the DataMember property which Gets or sets the specific table in the DataSource to

bind to the control and the DataBind method to bind data from a source to a server control. This method is commonly used after retrieving a data set through a database query. 15. What base class do all Web Forms inherit from? System.Web.UI.Page 16. What method do you use to explicitly kill a users session? The Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out. Syntax: Session.Abandon 17. How do you turn off cookies for one page in your site? Use the Cookie.Discard Property which Gets or sets the discard flag set by the server. When true, this property instructs the client application not to save the Cookie on the users hard disk when a session ends. 18. Which two properties are on every validation control? ControlToValidate & ErrorMessage properties 19. What tags do you need to add within the asp:datagrid tags to bind columns manually? 20. How do you create a permanent cookie? Setting the Expires property to MinValue means that the Cookie never expires. 21. What tag do you use to add a hyperlink column to the DataGrid? 22. What is the standard you use to wrap up a call to a Web service? 23. Which method do you use to redirect the user to another page without performing a round trip to the client? Server.transfer() 24. What is the transport protocol you use to call a Web service? SOAP. Transport Protocols: It is essential for the acceptance of Web Services that they are based on established Internet infrastructure. This in fact imposes the usage of of the HTTP, SMTP and FTP protocols based on the TCP/IP family of transports. Messaging Protocol: The format of messages exchanged between Web Services clients and Web Services should be vendor neutral and should not carry details about the technology used to implement the service. Also, the message format should allow for extensions and different bindings to specific transport protocols. SOAP and ebXML Transport are specifications which fulfill these requirements. We expect that the W3C XML Protocol Working Group defines a successor standard. 25. True or False: A Web service can only be written in .NET. False. 26. What does WSDL stand for? Web Services Description Language 27. What property do you have to set to tell the grid which page to go to when using the Pager object? 28. Where on the Internet would you look for Web services? UDDI repositaries like uddi.microsoft.com, IBM UDDI node, UDDI Registries in Google Directory, enthusiast sites like XMethods.net. 29. What tags do you need to add within the asp:datagrid tags to bind columns manually? Column tag and an ASP:databound tag. 30. 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? 31. How is a property designated as read-only? In VB.NET: 32. Public ReadOnly Property PropertyName As ReturnType

33. Get Implementation goes in here 34. End Get End Property

Your Property

in C#
public returntype PropertyName { get{ //property implementation goes here } // Do not write the set implementation }

35. Which control would you use if you needed to make sure the values in two different controls matched? Use the CompareValidator control to compare the values of 2 different controls. 36. True or False: To test a Web service you must create a windows application or Web application to consume this service? False. 37. How many classes can a single .NET DLL contain? Unlimited. 1. Describe the advantages of writing a managed code application instead of unmanaged one. Whats involved in certain piece of code being managed? The advantages include automatic garbage collection, memory management, support for versioning and security. These advantages are provided through .NET FCL and CLR, while with the unmanaged code similar capabilities had to be implemented through third-party libraries or as a part of the application itself. 2. Are COM objects managed or unmanaged? Since COM objects were written before .NET, apparently they are unmanaged. 3. So can a COM object talk to a .NET object? Yes, through Runtime Callable Wrapper (RCW) or PInvoke. 4. How do you generate an RCW from a COM object? Use the Type Library Import utility shipped with SDK. tlbimp COMobject.dll /out:.NETobject.dll or reference the COM library from Visual Studio in your project. 5. I cant import the COM object that I have on my machine. Did you write that object? You can only import your own objects. If you need to use a COM component from another developer, you should obtain a Primary Interop Assembly (PIA) from whoever authored the original object. 6. How do you call unmanaged methods from your .NET code through PInvoke? Supply a DllImport attribute. Declare the methods in your .NET code as static extern. Do not implement the methods as they are implemented in your unmanaged code, youre just providing declarations for method signatures. 7. Can you retrieve complex data types like structs from the PInvoke calls? Yes, just make sure you re-declare that struct, so that managed code knows what to do with it. 8. I want to expose my .NET objects to COM objects. Is that possible? Yes, but few things should be considered first. Classes should implement interfaces explicitly. Managed types must be public. Methods, properties, fields, and events that are exposed to COM must be public. Types must have a public default constructor with no arguments to be activated from COM. Types cannot be abstract. 9. Can you inherit a COM class in a .NET application? The .NET Framework extends the COM model for reusability by adding implementation inheritance. Managed types can derive directly or

indirectly from a COM coclass; more specifically, they can derive from the runtime callable wrapper generated by the runtime. The derived type can expose all the method and properties of the COM object as well as methods and properties implemented in managed code. The resulting object is partly implemented in managed code and partly implemented in unmanaged code. 10. Suppose I call a COM object from a .NET applicaiton, but COM object throws an error. What happens on the .NET end? COM methods report errors by returning HRESULTs; .NET methods report them by throwing exceptions. The runtime handles the transition between the two. Each exception class in the .NET Framework maps to an HRESULT.

COM/COM+ services and components in .NET


1. Explain transaction atomicity. We must ensure that the entire transaction is either committed or rolled back. 2. Explain consistency. We must ensure that the system is always left at the correct state in case of the failure or success of a transaction. 3. Explain integrity. Ensure data integrity by protecting concurrent transactions from seeing or being adversely affected by each others partial and uncommitted results. 4. Explain durability. Make sure that the system can return to its original state in case of a failure. 5. Explain object pooling. With object pooling, COM+ creates objects and keeps them in a pool, where they are ready to be used when the next client makes a request. This improves the performance of a server application that hosts the objects that are frequently used but are expensive to create. 6. Explain JIT activation. The objective of JIT activation is to minimize the amount of time for which an object lives and consumes resources on the server. With JIT activation, the client can hold a reference to an object on the server for a long time, but the server creates the object only when the client calls a method on the object. After the method call is completed, the object is freed and its memory is reclaimed. JIT activation enables applications to scale up as the number of users increases. 7. Explain role-based security. In the role-based security model, access to parts of an application are granted or denied based on the role to which the callers belong. A role defines which members of a Windows domain are allowed to work with what components, methods, or interfaces. 8. Explain queued components. The queued components service enables you to create components that can execute asynchronously or in disconnected mode. Queued components ensure availability of a system even when one or more sub-systems are temporarily unavailable. Consider a scenario where salespeople take their laptop computers to the field and enter orders on the go. Because they are in disconnected mode, these orders can be queued up in a message queue. When salespeople connect back to the network, the orders can be retrieved from the message queue and processed by the order processing components on the server. 9. Explain loosely coupled events. Loosely coupled events enable an object (publisher) to publish an event. Other objects (subscribers) can subscribe to an event. COM+ does not require publishers or subscribers to know about each other. Therefore, loosely coupled events greatly simplify the programming model for distributed applications. 10. Define scalability. The application meets its requirement for efficiency even if the number of users increases. 11. Define reliability. The application generates correct and consistent information all the time. 12. Define availability. Users can depend on using the application when needed.

13. Define security. The application is never disrupted or compromised by the efforts of malicious or ignorant users. 14. Define manageability. Deployment and maintenance of the application is as efficient and painless as possible. 15. Which namespace do the classes, allowing you to support COM functionality, are located? System.EnterpriseServices 16. How do you make a NET component talk to a COM component? To enable the communication between COM and .NET components, the .NET Framework generates a COM Callable Wrapper (CCW). The CCW enables communication between the calling COM code and the managed code. It also handles conversion between the data types, as well as other messages between the COM types and the .NET types.

.NET Windows services development questions


1. Explain Windows service. You often need programs that run continuously in the background. For example, an email server is expected to listen continuously on a network port for incoming email messages, a print spooler is expected to listen continuously to print requests, and so on. 2. Whats the Unix name for a Windows service equivalent? Daemon. 3. So basically a Windows service application is just another executable? Whats different about a Windows service as compared to a regular application? Windows services must support the interface of the Service Control Manager (SCM). A Windows service must be installed in the Windows service database before it can be launched. 4. How is development of a Windows service different from a Windows Forms application? A Windows service typically does not have a user interface, it supports a set of commands and can have a GUI thats built later to allow for easier access to those commands. 5. How do you give a Windows service specific permissions? Windows service always runs under someones identity. Can be System or Administrator account, but if you want to restrict the behavior of a Windows service, the best bet is to create a new user account, assign and deny necessary privileges to that account, and then associate the Windows service with that new account. 6. Can you share processes between Windows services? Yes. 7. Wheres Windows service database located? HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services 8. What does SCM do? SCM is Windows Service Control Manager. Its responsibilities are as follows: o Accepts requests to install and uninstall Windows services from the Windows service database. o To start Windows services either on system startup or requested by the user. o To enumerate installed Windows services. o To maintain status information for currently running Windows services. o To transmits control messages (such as Start, Stop, Pause, and Continue) to available Windows services. o To lock/unlock Windows service database. 9. vice on a box? Use Windows Service Installer, do not go through Add/Remove Programs or MSI file, as you would normally go with applications.

10. When developing a Windows service for .NET, which namespace do you typically look in for required classes? System.ServiceProcess. The classes are ServiceBase, ServiceProcessInstaller, ServiceInstaller and ServiceController. 11. How do you handle Start, Pause, Continue and Stop calls from SCM within your application? By implementing OnStart, OnPause, OnContinue and OnStop methods. 12. Describe the start-up process for a Windows service. Main() is executed to create an instance of a Web service, then Run() to launch it, then OnStart() from within the instance is executed. 13. I want to write a Windows service that cannot be paused, only started and stopped. How do I accomplish that? Set CanPauseAndContinue attribute to false. 14. What application do you use to install a Windows service? installutil.exe 15. I am trying to install my Windows service under NetworkService account, but keep getting an error. The LocalService and NetworkService accounts are only available on Windows XP and Windows Server 2003. These accounts do not exist on Windows 2000 or older operating systems. 16. How can you see which services are running on a Windows box? Admin Tools -> Computer Management -> Services and Application -> Services. You can also open the Computer Management tool by right-clicking on My Computer and selecting Manage from the popup menu. 17. How do you start, pause, continue or stop a Windows service off the command line? net start ServiceName, net pause ServiceName and so on. Also sc.exe provides a command-line interface for Windows services. View the OS documentation or proper book chapters on using sc.exe. 18. Can I write an MMC snap-in for my Windows service? Yes, use classes from the System.Management.Instrumentation namespace. Also see Managing Applications Using WMI from .NET Framework SDK.

Microsoft .NET Framework interview questions


1. What is .NET Framework? 2. Is .NET a runtime service or a development platform? Answer Its bothand actually a lot more. Microsoft .NET is a company-wide initiative. It includes a new way of delivering software and services to businesses and consumers. A part of Microsoft.NET is the .NET Frameworks. The frameworks is the first part of the MS.NET initiate to ship and it was given out to attendees at the PDC in July. The .NET frameworks consists of two parts: the .NET common language runtime and the .NET class library. These two components are packaged together into the .NET Frameworks SDK which will be available for free download from Microsofts MSDN web site later this month. In addition, the SDK also includes command-line compilers for C#, C++, JScript, and VB. You use these compilers to build applications and components. These components require the runtime to execute so this is a development platform. When Visual Studio.NET ships, it will include the .NET SDK and a GUI editor, wizards, tools, and a slew of other things. However, Visual Studio.NET is NOT required to build .NET applications. 3. New features of Framework 1.1 ? 4. What is CLR? How it will work? 5. What is MSIL, IL, CTS? 6. What is JIT and how is works 7. What is strong name? A name that consists of an assemblys identityits simple text name, version number, and culture information (if provided)strengthened by a public key and a digital signature generated over the assembly.

8. What is portable executable (PE) The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR. The specification for the PE/COFF file formats is available at http://www.microsoft.com/whdc/hwdev/hardware/pecoffdown.mspx 9. Which is the base class for .net Class library? Ans: system.object 10. What is Event? Delegate, clear syntax for writing a event delegate// keyword_delegate.cs //
delegate declaration delegate void MyDelegate(int i);

11. class Program 12. { 13. public static void Main() 14. { 15. TakesADelegate(new MyDelegate(DelegateFunction)); 16. } 17. public static void TakesADelegate(MyDelegate SomeFunction) 18. { 19. SomeFunction(21); 20. } 21. public static void DelegateFunction(int i) 22. { 23. System.Console.WriteLine("Called by delegate withnumber: {0}.", i); 24. } }

25. ment DataGrid in .NET? How would you make a combo-box appear in one column of a DataGrid? What are the ways to show data grid inside a data grid for a master details type of tables? 26. If we write any code for DataGrid methods, what is the access specifier used for that methods in the code behind file and why? 27. What is Application Domain? Application domains provide a unit of isolation for the common language runtime. They are created and run inside a process. Application domains are usually created by a runtime host, which is an application responsible for loading the runtime into a process and executing user code within an application domain. The runtime host creates a process and a default application domain, and runs managed code inside it. Runtime hosts include ASP.NET, Microsoft Internet Explorer, and the Windows shell. 28. What is serialization in .NET? What are the ways to control serialization? Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created. o Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects by value from one computer or application domain to another.

XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice. 29. What are the different authentication modes in the .NET environment? 30. <authentication mode="Windows|Forms|Passport|None"> 31. <forms name="name loginUrl="url 32. protection="All|None|Encryption|Validation 33. timeout="30 path="/ > requireSSL=true|false 34. slidingExpiration=true|false>< 35. credentials passwordFormat="Clear|SHA1|MD5>< 36. user name="username password="password"/> 37. </credentials> </forms> 38. <passport redirectUrl="internal"/>
o </authentication>

/li> 39. What is the use of trace utility 40. What is different between User Control and Web Control and Custom Control? 41. What is exception handling? When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method. This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. A catch clause that doesnt name an exception class can handle any exception. Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated withtry statements more nested that than the one that caught the exception. Exceptions that occur during destructor execution are worthspecial mention. If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded. 42. What is Assembly? Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime withthe information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. Assemblies are a fundamental part of programming withthe .NET Framework. An assembly performs the following functions: o It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is,DllMain,WinMain, orMain).

o o

It forms asecurity boundary. An assembly is the unit at which permissions are requested and granted. It forms atype boundary. Every types identity includes the name of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly. It forms areference scope boundary. The assemblys manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends. It forms aversion boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assemblys manifest describes the version dependencies you specify for any dependent assemblies. It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes, can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded. It is the unit at which side-by-side execution is supported. Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in PE files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed. There are several ways to create assemblies. You can use development tools, such as Visual Studio .NET, that you have used in the past to create .dll or .exe files. You can use tools provided in the .NET Framework SDK to create assemblies withmodules created in other development environments. You can also use common language runtime APIs, such as Reflection.Emit, to create dynamic assemblies.

43. s of assemblies? Private, Public/Shared, Satellite 44. What are Satellite Assemblies? How you will create this? How will you get the different language strings? Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated witha given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. For example, English and Japanese editions of the .NET Framework version 1.1 share the same core files. The Japanese .NET Framework version 1.1 adds satellite assemblies withlocalized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files. 45. How will you load dynamic assembly? How will create assemblies at run time? 46. What is Assembly manifest? what all details the assembly manifest will contain. Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assemblys version

requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) withMicrosoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information. It contains Assembly name, Version number, Culture, Strong name information, List of all files in the assembly, Type reference information, Information on referenced assemblies. 47. What are the contents of assembly? In general, a static assembly can consist of four elements: o The assembly manifest, which contains assembly metadata. o Type metadata. o Microsoft intermediate language (MSIL) code that implements the types. o A set of resources. 48. Difference between assembly manifest & metadata assembly manifest -An integral part of every assembly that renders the assembly self-describing. The assembly manifest contains the assemblys metadata. The manifest establishes the assembly identity, specifies the files that make up the assembly implementation, specifies the types and resources that make up the assembly, itemizes the compile-time dependencies on other assemblies, and specifies the set of permissions required for the assembly to run properly. This information is used at run time to resolve references, enforce version binding policy, and validate the integrity of loaded assemblies. The self-describing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible. metadata -Information that describes every element managed by the common language runtime: an assembly, loadable file, type, method, and so on. This can include information required for debugging and garbage collection, as well as security attributes, marshaling data, extended class and member definitions, version binding, and other information required by the runtime. 49. What is Global Assembly Cache (GAC) and what is the purpose of it? (How to make an assembly to public? Steps) Each computer where the common language runtime is installed has a machinewide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache only when you need to. 50. If I have more than one version of one assemblies, then howll I use old version (how/where to specify version number?)in my application? 51. How to find methods of a assembly file (not using ILDASM) Reflection 52. Value type & data types difference. Example from .NET. 53. Integer & struct are value types or reference types in .NET? 54. What is Garbage Collection in .Net? Garbage collection process? The process of transitively tracing through all pointers to actively used objects in order to locate all objects that can be referenced, and then arranging to reuse any heap memory that was not found during this trace. The common language runtime garbage collector also compacts the memory that is in use to reduce the working space needed for the heap. 55. Readonly vs. const? Aconstfield can only be initialized at the declaration of the field. Areadonlyfield can be initialized either at the declaration or in a constructor. Therefore,readonlyfields can have different values depending on the constructor used. Also, while aconstfield is a compile-time constant, thereadonlyfield can be used for runtime constants, as in the following example: public static readonly uint l1 = (uint) DateTime.Now.Ticks; 56.
1.

2. 3.

< . { System.Attribute : MyAttribute public attribute.(> < { public this.myvalue="myvalue;" myvalue) MyAttribute(bool constructors(> 4. //Declaring properties 5. public bool MyProperty 6. { 7. get {return this.myvalue;} 8. set {this.myvalue = value;} 9. } ion to get access to custom attributes. class MainClass { public static void Main() { System.Reflection.MemberInfo info = typeof(MyClass); object[] attributes = info.GetCustomAttributes(); for (int i = 0; i < attributes.Length; i ++) { System.Console.WriteLine(attributes[i]); } } }

10.

2. C++ & C# differences 3. What is the managed and unmanaged code in .net? The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtimes functionality and enable you to write code that benefits from this managed execution environment. Code that you develop witha language compiler that targets the runtime is calledmanaged code; itbenefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services. 4. How do you create threading in .NET? What is the namespace for that? 5. using directive vs using statement You create an instance in ausingstatement to ensure thatDispose is called on the object when theusingstatement is exited. Ausing statement can be exited either when the end of theusingstatement is reached or if, for example, an exception is thrown and control leaves the statement block before the end of the statement. The using directive has two uses.
o o

Create an alias for a namespace (a using alias). Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (ausingdirective).

57. Describe the Managed Execution Process 58. What is Active Directory? What is the namespace used to access the Microsoft Active Directories? 59. Interop Services?

60. What is RCW (Run time Callable Wrappers)? The common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object. 61. What is CCW (COM Callable Wrapper) A proxy object generated by the common language runtime so that existing COM applications can use managed classes, including .NET Framework classes, transparently. 62. How does you handle this COM components developed in other programming languages in .NET? 63. How will you register com+ services? 64. What is use of ContextUtil class? ContextUtil is the preferred class to use for obtaining COM+ context information. 65. What is the new three features of COM+ services, which are not there in COM (MTS) 66. Is the COM architecture same as .Net architecture? What is the difference between them (if at all there is)? For more questions and answers, visit Santhosh

.NET Remoting questions and answers


To satisfy popular demand, heres some basics of the .NET Remoting. 1. Whats a Windows process? Its an application thats running and had been allocated memory. 2. Whats typical about a Windows process in regards to memory allocation? Each process is allocated its own block of available RAM space, no process can access another process code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down. 3. Why do you call it a process? Whats different between process and application in .NET, not common computer usage, terminology? A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application. 4. What distributed process frameworks outside .NET do you know? Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI). 5. What are possible implementations of distributed applications in .NET? .NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services. 6. When would you use .NET Remoting and when Web services? Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.

7. Whats a proxy of the server object in .NET Remoting? Its a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling. 8. What are remotable objects in .NET Remoting? Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed. 9. What are channels in .NET Remoting? Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred. 10. What security measures exist for .NET Remoting in System.Runtime.Remoting? None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level. 11. What is a formatter? A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end. 12. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs? Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable. 13. Whats SingleCall activation mode used for? If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode. 14. Whats Singleton activation mode? A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease. 15. How do you define the lease of the object? By implementing ILease interface when writing the class code. 16. Can you configure a .NET Remoting object via XML file? Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config. 17. How can you automatically generate interface for the remotable object in .NET with Microsoft tools? Use the Soapsuds tool.

Advanced C# interview questions


1. Whats the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time its being operated on, a new instance is created. 2. Can you store multiple data types in System.Array? No. 3. Whats the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow. 4. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. 5. Whats the .NET datatype that allows the retrieval of data by a unique key? HashTable. 6. Whats class SortedList underneath? A sorted HashTable. 7. Will finally block get executed if the exception had not occurred? Yes.

8. Whats the C# equivalent of C++ catch (), which was a catch-all statement for 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 {}. 9. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block. 10. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project. 11. Whats a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers. 12. Whats a multicast delegate? Its a delegate that points to and eventually fires off several methods. 13. Hows 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. 14. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command. 15. Whats 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. 16. What namespaces are necessary to create a localized application? System.Globalization, System.Resources. 17. Whats the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments. 18. How do you generate documentation from the C# file commented properly with a commandline compiler? Compile it with a /doc switch. 19. Whats the difference between <c> and <code> XML documentation tag? Single line code example and multiple-line code example. 20. Is XML case-sensitive? Yes, so <Student> and <student> are different elements. 21. What debugging tools come with the .NET SDK? CorDBG command-line debugger, and DbgCLR graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch. 22. What does the This window show in the debugger? It points to the object thats pointed to by this reference. Objects instance data is shown. 23. What does assert() 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. 24. Whats 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. 25. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities. 26. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor. 27. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.

28. What are three test cases you should go through in unit testing? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly). 29. 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. 30. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources). 31. 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, but its a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines. 32. Whats the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed. 33. What is the wildcard character in SQL? Lets 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%. 34. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no in-between case where something has been updated and something hasnt), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after). 35. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords). 36. 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. 37. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications. 38. What does the parameter Initial Catalog define inside Connection String? The database name to connect to. 39. Whats the data provider name to connect to Access database? Microsoft.Access. 40. What does Dispose method do with the connection object? Deletes it from the memory. 41. 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.

Database programming for the Web interview questions


Q: How would you make the following SQL statement run faster? SELECT * FROM TABLEA WHERE COL1=A AND COL2=B'; A: Make sure that COL1 and COL2 have indexes. Find out which condition will return less values and use that as the first conditonal. Q: What is Data Mining A: Data Minig is the process of sifting through extremely large amounts of Data to find trends or relevent information.

Q: Name the Seven layers in the OSI Model. A: Appication, Presentation, Session, Transport, Network, Data Link, Phyiscal Q: What is one way to view a unix network share on a Windows computer, within explorer A: NFS, The Unix computer can be running a NFS Server Daemon. Q: How would you find all the processes running on your computer. A: Unix, is ps -ef or ps -aux depending on version. Q: What is DHCP A: DHCP is a way to dynamically assign IP address to computers. Dyanmic Host Configuration Protocol Q: What is HTTP Tunneling A: HTTP Tunneling is a security method that encryptes packets traveling throught the internet. Only the intended reciepent should be able to decrypt the packets. Can be used to Create Virtual Private Networks. (VPN) Q: Scenario: You have 9 identical looking balls, however one ball is heavier than the others. You have two chances to use a balance. How do you find out which ball is the heaviest? A: Split into groups of three, randomly choose two groups and use balance on them. If one group is heavier, then discard the other 6 balls. If the two groups are the same weight. The heavier ball must be in the group that was not on the scale. Now randomly choose two balls and test on balance. If they are the same weight, the heaviest ball is on one that was not tested. Else the heaviest ball is already known from the balance.

SQL Server interview questions


1. How do you read transaction logs? 2. How do you reset or reseed the IDENTITY column? 3. How do you persist objects, permissions in tempdb? 4. How do you simulate a deadlock for testing purposes? 5. How do you rename an SQL Server computer? 6. How do you run jobs from T-SQL? 7. How do you restore single tables from backup in SQL Server 7.0/2000? In SQL Server 6.5? 8. Where to get the latest MDAC from? 9. I forgot/lost the sa password. What do I do? 10. I have only the .mdf file backup and no SQL Server database backups. Can I get my database back into SQL Server? 11. How do you add a new column at a specific position (say at the beginning of the table or after the second column) using ALTER TABLE command? 12. How do you change or alter a user defined data type? 13. How do you rename an SQL Server 2000 instance? 14. How do you capture/redirect detailed deadlock information into the error logs? 15. How do you remotely administer SQL Server? 16. What are the effects of switching SQL Server from Mixed mode to Windows only authentication mode? What are the steps required, to not break existing applications? 17. Is there a command to list all the tables and their associated filegroups? 18. How do you ship the stored procedures, user defined functions (UDFs), triggers, views of my application, in an encrypted form to my clients/customers? How do you protect intellectual property?

19. How do you archive data from my tables? Is there a built-in command or tool for this? 20. How do you troubleshoot ODBC timeout expired errors experienced by applications accessing SQL Server databases? 21. How do you restart SQL Server service automatically at regular intervals? 22. What is the T-SQL equivalent of IIF (immediate if/ternary operator) function of other programming languages? 23. How do you programmatically find out when the SQL Server service started? 24. How do you get rid of the time part from the date returned by GETDATE function? 25. How do you upload images or binary files into SQL Server tables? 26. How do you run an SQL script file that is located on the disk, using T-SQL? 27. How do you get the complete error message from T-SQL while error handling? 28. How do you get the first day of the week, last day of the week and last day of the month using TSQL date functions? 29. How do you pass a table name, column name etc. to the stored procedure so that I can dynamically select from a table? 30. Error inside a stored procedure is not being raised to my front-end applications using ADO. But I get the error when I run the procedure from Query Analyzer. 31. How do you suppress error messages in stored procedures/triggers etc. using T-SQL? 32. How do you save the output of a query/stored procedure to a text file? 33. How do you join tables from different databases? 34. How do you join tables from different servers? 35. How do you convert timestamp data to date data (datetime datatype)? 36. Can I invoke/instantiate COM objects from within stored procedures or triggers using T-SQL? 37. Oracle has a rownum to access rows of a table using row number or row id. Is there any equivalent for that in SQL Server? Or How do you generate output with row number in SQL Server? 38. How do you specify a network library like TCP/IP using ADO connect string? 39. How do you generate scripts for repetitive tasks like truncating all the tables in a database, changing owner of all the database objects, disabling constraints on all tables etc? 40. Is there a way to find out when a stored procedure was last updated? 41. How do you find out all the IDENTITY columns of all the tables in a given database? 42. How do you search the code of stored procedures? How do you retrieve the generated GUID value of a newly inserted row? Is there an @@GUID, just like @@IDENTITY?
1. Describe variable scope, class member scope, and reference counting. (Short answers are preferred.) By default variable,class scope is private 2. List some of your favorite programming optimizations, tricks and/or algorithms? Minimise the roundtrips,session variables ,database operation should done thro dataset mostly,minimize the usage of more pictures 3. Describe the use of the Property keyword in .NET, and how it differs from a public variable. It is used to get ,set the values. It is used to assign the value inside the function after assignment only the values goes to the variable 4. What is the fastest method of searching a sorted array? unsorted array? Binary search, linear for unsorted

5. Describe an appropriate usage of User Defined Events. For some function in client side execution 6. Describe your views on exception handling. It is used to show the user corresponding error raised instead of system hanging 7. What is the difference between inheritance and implementing interfaces in .NET? Using inhertance we can achieve only single inheritance By using interface multiple inheritance is acheived 8. List resources utilized when you encounter a problem. Tracing and debugging 9. If you're not cheating, you're not most expert___________ enough. 10. Using your own coding philosophies, please list the following in order of importance and why you ordered them that way: Ans e,c,a,d,b a) Reliability b) Scalability c) Efficiency d) Maintainability e) Security 11. Which is more efficient in an IF statement: Using AND or using ANDALSO? Also describe why you feel this way. Andalso becausing it was short circuiting process based for quick execution. 12. Describe what Garbage Collection is. Also describe the pros and cons in regards to system overhead and programmer efficiency. GC is called by the CLR when the manage heap was filled ,if we want to call manully GC.Collect is used.otherwise finalise and dispose can be used When we dont need the variable value for further process then we can use dispose 13. Why would you want to utilize an interface? To implement multiple inheritance And to give the general sketch what are the function used in the program 14. Place an "X" next to all that you have experience with. Place an 'XX' next to the ones you enjoy working with. ___ VB 3.0 ___ VB 4.0 ___ VB 5.0/6.0 X ___ VB.NET XX ___ C# XX ___ Visual C++ ___ NT 4.0 ___ Windows 2000 X ___ Windows XP X ___ Access X ___ MS SQL Server ___ Oracle ___ SQL (in general) XX ___ HTML XX ___ CGI ___ IIS X ___ ASP

___ ASP.NET XX ___ XML X ___ XSL ___ Turtle Graphics 15. Using OOP methodology, create a class that exhibits any qualities and behaviors that youd like for a 3Demensional item (such as a book, fruit, furniture, etc). Have this particular class inherit from a base class. 16. Examining the classes youve just created - What are the pros, if any, of polymorphism? 17. Again, examining the classes youve just created - What are the cons, if any, of polymorphism? 18. Why would you define a virtual function? 19. What is a string? How does it relate to threading? 20. What is the difference between .NET Remoting and Webservices? List the pros and cons of each. 21. Complete the code for these functions. Read the comment blocks to determine what the function should do. Write these functions so that they may be copied directly into the Visual Studio.NET IDE and compiled. Public Function IsLeapYear(ByVal lYear As Long) As Boolean This function accepts a 4 digit year, and returns TRUE if that year is a leap year End Function

Public Function ListToString(oStrings As Arraylist, sDelimiter As String) As String 'This function accepts an ArrayList of strings and returns a single string 'that is the delimited form of the oStrings collection using sDelimiter as 'the character to seperate each item in the collection. End Function

Public Function StripNumbers(sText As String, sReplaceString As String) As String 'This function accepts a string of characters and does one of two things: '1. If sReplaceString is specified, the numbers are replaced with that string. '2. If sReplaceString is blank, the numbers are removed. 'For example, if sText = "HAPPY2DAY" and sReplaceString is blank, 'this function returns "HAPPYDAY". If sText = "HAPPY2DAY" and 'sReplaceString="X" then this function returns "HAPPYXDAY" 'This function should be optimized for speed. 'Keep in mind sReplaceString could be more than one character. End Function

Optional: Why are 1980 pennies worth more than 1979 pennies? Tony likes indigo but not blue. He likes onions but not turnips; he likes forms but not shapes. According to the same rule does he like tomatoes or avocados?

You might also like