Dot Net, .Net, C#, Faq
Dot Net, .Net, C#, Faq
Dot Net, .Net, C#, Faq
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?
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?
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.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.
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
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.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.
If you are a C++ programmer, you might like to check out my C# FAQ.
3. Assemblies
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.
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.
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
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; } }
5. Garbage Collection
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.
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.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.
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.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.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.
7. Attributes
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.
{ 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 ); } }
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.
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.
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.
Then, to apply the permission set to a code group, do something like this:
caspol -cg 1.3 SamplePermSet
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.
Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.
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.
BSTR
When you've built the component, you should get a typelibrary. Run the TLBIMP utility on the typelibary, like this:
tlbimp cppcomserver.tlb
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() ); } }
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
[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; } }
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 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.
11. Miscellaneous
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 ); } }
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.
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.
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.
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
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.
13.1 Threads
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.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.
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
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.
(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.
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?
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
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?
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
immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++."
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.
2. Types
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 ); } }
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
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
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.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.
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.
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.
4. Exceptions
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.
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.
{ 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 ); } } }
6. Miscellaneous
// true
} }
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.
However consider using this more aesthetically pleasing (but functionally identical) formatting:
using( obj1 ) using( obj2 ) { ... }
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:
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.
7. C# 2.0
instead of this:
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'.
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.
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 ==?
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?
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?
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
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).
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.
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.
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.
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.
version of \uxxxx) \Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)
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.
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.
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).
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.
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
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.
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;
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 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#.)
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);
// // // // //
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).
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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?