Monday, November 2, 2009

ASP .Net Interview Question

csharpwithdj.blogspot.com

1.What are steps in an asp .net page lifecycle?


Init() - when the page is instantiated

Load() - when the page is loaded into server memory

PreRender() - the brief moment before the page is displayed to the user as HTML

Unload() - when page finishes loading.

2.What is the main difference between Response.Write() and Response.Output.Write()?

With Response.Outout.Write options are available to you to write the formatted out put.

3.When implementing classes what are the specifics of an abstract method?

An Abstract method does not provide any implementation. The class containing it can not be instantiated it must be inherited. The deriving class must override abstract methods declared in parent class, unless it is an abstract class it self.

4.List all Validation Controls available in asp .net?

RequiredFieldValidator : Checks if a control has a value.

RangeValidator : Checks if the control’s value is within a certain range.

RegularExpressionValidator : Checks whether the value of an input control matches a certain pattern

CompareValidator : Checks a control’s value against a constant or another control value.

CustomValidator : Checks a control’s value against a customized validation logic.

ValidationSummary : Displays a list of all validation errors

5.What data types do the RangeValidator control support?

Integer, String, and Date.

6.Is C# .net case sensitive?

Yes it is.

7.What is the difference between a class and struct ?

A struct is a value type while a class is a reference type. There’s no inheritance with struct.


8.When passing a variable by reference to a method what is the difference between keywords ref and out?

When using the key word ref the variable must be initialize before calling the method,

while initialization is not mandatory when using out.

9.What are specifics for Static class?

Static class is implemented with the Keyword Static in the class definition.

It must contain only static members and methods. Public members of static class can be accessed without the class instantiation. Static class are sealed by default therefore can not be inherited. Static class cannot be instantiated.

10.What part of the code is usually called Code-Behind?

The Server side code is usually called Code-behind as reference to the fact that in a web application it is actually the part of the code handling the large part of the execution.

11.What part of the code is called Inline Code?

The asp .net client side code is usually call inline code. From most browsers it can be

view by choosing 'View source' from the page menu.

12.What is the difference between doing a Dataset.Clone() and Dataset.Copy()?

Dataset.Clone() will copy just the dataset structure including all the datatables,

schemas, relations and constraints; it will not copy the data. Dataset.Copy() will copy

both dataset structure and data.

13.What is the role of Global.asax file?

The Global.asax include its code behind file Global.asax.cs, it is use to implement

application and session level events.

14.What utility is used to manually deploy an assembly?

The GacUtil is a utility tool that comes with visual studio, it is use to deploy an

assembly by adding it into the GAC(Global Assembly Cache).

Ex: Type at the command line prompt

C:\gacutil /i ASPMyComponent.dll

will install ASPMyComponent into the GAC

15.Define MSIL. How is it use in the .Net framework?

MSIL stand for Microsoft Intermediate Language. During the compilation process, code written in any .NET compatible languages(J#, C#, VB,C++) is converted into MSIL. MSIL then create a compatibility bridge among these language before execution by the virtual machine.

16. What are differences between ASP.Net and Classic ASP?

-ASP programming is based on scripting languages like Jscript or VBScript which evolves around a mixture of scripting and HTML. ASP .net is base on an advance structured compiled language.

-ASP .net gives the option of separating the code behind (compiled code) from the design code or client code (HTML).

-ASP .net with visual studio .net provides an advanced application and session state

management, while ASP performs poorly at providing it.

-ASP has a poor error handling capability compare to ASP .net which has it much completed and much advanced.

-ASP does not have a built-in mechanism for XML while ASP .net comes with a full XML capability support.

-ASP .net has a fully distributed data source support which is missing from classic ASP

17.What property is use to set alternate color scheme in a Repeater control?

AlternatingItemTemplate.

18.What is the base class for Web Forms?

The System.Web.UI.Page class.

19.What are the meaning of terms boxing and un-boxing?

Boxing: Implicit conversion of a value type into a reference type.

Un-Boxing: Explicit conversion of a reference type into a value type. Can also be call casting.

20.Give a brief description of how the heap and stack are managed in .Net.

Stack and heap are memory sections of the .net application. The CLR(Common Language Runtime) is in charge of managing those sections.

Value type variables are stored in the stack where storing order is Last in first out.

When a variable is out of scope it basically fall off the stack.

Refence type variable are stored on the heap where storing order is First in first out.

When a variable becomes out of scope it is mark for collection.

The GC(Garbage Collector) is the part of the CLR responsible for cleaning up the heap releasing resources occupied by Reference type variables.

21.What is the difference between login controls and Forms authentication?

Login control provides form authentication. If we implement for authentication through form authentication then we do it through code. On the other hand, login control allows the easy implementation...............
22.What is Fragment Caching in ASP.NET?

.Fragment caching allows to cache specific portions of the page rather than the whole page. It is done by implementing the page in different parts............

23.What is partial classess in .net?

When there is a need to keep the business logic separate from the User Interface or when there is some class which is big enough to have multiple number of developers............
24.Explain how to pass a querystring from an .asp page to aspx page.

.From HTML in asppage:Test Query String

From server side code: ...............
25.What is a ViewState?

.If a site happens to not maintain a ViewState, then if a user has entered some information in a large form with many input fields and the page is refreshes, then the values filled up in the form are lost...........

26.What is the difference between src and Code-Behind?

.With the ‘src’ attribute, the source code files are deployed and are compiled by the JIT as needed.

Though the code is available to everyone with an access to the server (NOT anyone on the web)................

27.What is the difference between URL and URI?

.A URL (Uniform Resource Locator) is the address of some resource on the Web. A resource is nothing but a page of a site. There are other type of resources than Web pages, but that's the easiest conceptually...........

28.What is the Pre-Compilation feature of ASP.NET 2.0?

.Previously, in ASP.NET, the pages and the code used to be compiled dynamically and then cached so as to make the requests to access the page extremely efficient............

29.How can we create custom controls in ASP.NET?

.Custom controls are user defined controls. They can be created by grouping existing controls, by deriving the control from System.Web.UI.WebControls..........

30.What is an application domain?

.It's a way in CLR to maintain a boundary between various applications to ensure that they do not interfere in working of any other application...........

31.Explain the two different types of remote object creation mode in .NET. [Hint SAO and CAO]

.SAO Server Activated Object (call mode): lasts the lifetime of the server. They are activated as SingleCall/Singleton objects. It makes objects stateless...........

32.Describe SAO architecture of Remoting.

.Remoting has at least three sections:-

1. Server

2. Client: This connects to the hosted remoting object

3. Common Interface between client and the server .i.e. the channel..........

33.Explain Singleton architecture of Remoting.

.Singleton architecture is to be used when all the applications have to use or share same data...........

34.Define LeaseTime, SponsorshipTime, RenewOnCallTime, LeaseManagePollTime.

.The LeaseTime property protects the object so that the garbage collector does not destroy it as remoting objects are beyond the scope of the garbage collector. Every object created has a default leasetime for which it will be activated..........

35.Briefly explain how to specify remoting parameters using config files.

.The remoting parameters can be specified through both programming and in config files. All the settings defined in config files are placed under ...........

36.What is marshalling? Explain types of marshalling.

.Marshaling is a process of transforming or serializing data from one application domain and exporting it to another application domain...........

37.What is ObjRef object in remoting?

.ObjRef is a searializable object returned by Marshal() that knows about location of the remote object, host name, port number, and object name........

38.Explain the steps of acquiring a proxy object in web services.

.Every service listed has a URI pointing to the service's DISCO or WSDL document, which is needed to access the webservice and its 'webmethod" methods..........

39.Explain the steps to create a web services and consume it.

.Create a new website by selecting "ASP.NET Web Site" and giving it a suitable name. service.cs file appears inside the solution with a default webmethod named as "HelloWorld()"........
40.Explain the difference between cache object and application object.

.Application Object: Application variable/object stores an Object with a scope of availability of the entire Application unless explicitly destroyed.............
41.What is Cache Callback in Cache?

.The cache object has dependencies e.g. relationships to the file it stores. Cache items remove the object when these dependencies change. As a work around we would need to simply execute a callback method............

42.What is Scavenging?

.A process where items are removed from cache in order to free the memory based on their priority. A property called "CacheItemPriority" is used to figure out the priority of each item inside the cache...........

43.Explain the types of Caching using Cache object of ASP.NET.

.Page output: Is used to fetch information or data at page level. It is best used when the site is mainly static. Used by declaring the output page directive............

44.Show with an example how to Cache different version of same page using ASP.NET Cache object.

.The ways to cache different versions on the same page using ASP.NET cache object is using OutputCache object............

45.Explain how to implement Fragment Cache.

.Fragment cache is to store user controls individually within a web form in cache instead of the whole webform as such. The idea is to simply have different cache parameters for different user controls.............

46.Explain the various modes of storing ASP.NET session.

.Types of sessions: InProc: The default way to use sessions. InProc is the fastest way to store and access sessions...........

47.What are the benefits and limitations of using hidden fields?

.Advantages: Easy to implement, Hidden fields are supported by all browsers, Enables faster access of information because data is stored on client side............

48.What are the benefits and limitations of using Hidden Frames?

.Advantages: Hidden frames allow you to cache more than one data field, The ability to cache and access data items stored in different hidden forms...........

49.What are benefits and limitations of using Cookies?

.Advantages: They are simple to use. Light in size, thus occupy less memory. Stores server information on client side. Data need not to be sent back to server........

50.What is QueryString and what are benefits and limitations of using querystring?

.Querystring is way to transfer information from one page to another through the URL........
51.What is Absolute and Sliding expiration in .NET?

.Absolute and sliding expiration are two Time based expiration strategies. Absolute Expiration: Cache in this case expires at a fixed specified date or time..............

52.Explain the concepts and capabilities of cross page posting.

.Cross-page posting is done at the control level. It is possible to create a page that posts to different pages depending on what button the user clicks on. It is handled by done by changing the postbackurl property of the controls..........

53.Explain how to access ViewState value of this page in the next page.

.PreviousPage property is set to the page property of the nest page to access the viewstate value of the page in the next page. Page poster = this.PreviousPage;..........

54.What is SQL Cache Dependency in ASP.NET?

.SQL Cache Dependency in ASP.NET: It is the mechanism where the cache object gets invalidated when the related data or the related resource is modified.........

55.Explain the concepts of Post Cache Substitution in .NET

.Post Cache Substitution: It works opposite to fragment caching. The entire page is cached, except what is to be kept dynamic. When [OutputCache] attribute is used, the page is cached............

56.Explain the use of localization and Globalization.

.Users of different countries, use different languages and others settings like currency, and dates. Therefore, applications are needed to be configurable as per the required settings based on cultures, regions, countries........

57.Explain the concepts of CODE Page approach. What are the disadvantages of this approach?

.Code Page was used before Unicode came into existence. It was a technique to represent characters in different languages..........

58.What are resource files and explain how do we generate resource files?

.Resource files are files in XML format. They contain all the resources needed by an application. These files can be used to store string, bitmaps, icons, fonts........
59.What are Satellite assemblies and how to generate Satellite assemblies?

.To support the feature of multiple languages, we need to create different modules that are customized on the basis of localization. These assemblies created on the basis of different modules are knows as satellite assemblies...........

60.Define AL.EXE and RESGEN.EXE.

.Al.exe: It embeds the resources into a satellite assembly. It takes the resources in .resources binary format.......

61.Explain the concepts of resource manager class.

.ResourceManager class: It provides convenient access to resources that are culture-correct. The access is provided at run time.........

62.What is Windows communication foundation, WCF?

.WCF is a framework that builds applications that can inter-communicate based on service oriented architecture consuming secure and reliable web services.............

63.Explain the important principle of SOA.

.A service-oriented architecture is collection of services which communicate with one another other......

64.Explain the components of WCF - Service class, Hosting environment, END point.

.WCF Service is composed of three components: Service class: It implements the service needed, Host environment: is an environment that hosts the developed service.............

65.Difference between WCF and Web Services.

.WCF can create services similar in concept to ASMX, but has much more capabilities. WCF is much more efficient than ASP.Net coz it is implemented on pipeline............

66.What are different bindings supported by WCF?

.BasicHttpBinding, WSHttpBinding, WSDualHttpBinding.......

67.What is duplex contract in WCF?

.Duplex contract: It enables clients and servers to communicate with each other. The calls can be initiated independently of the other one.............

68.Explain the different transaction isolation levels in WCF.

.Read Uncommitted: - Also known as Dirty isolation level. It makes sure that corrupt Data cannot be read. This is the lowest isolation level............

69.What are Volatile and Dead letter queues?

.Volatile Queues: There are scenarios in the project when you want the message to deliver in proper time. The timely delivery of message is very more important and to ensure they are not lost is important too. Volatile queues are used for such purposes.............

70.What is Windows workflow foundation?

.Windows Workflow Foundation (WF): It is a platform for building, managing and executing workflow-enabled applications, for designing and implementing a programming model ..........

71.Explain the types of Workflow in Windows Workflow Foundation.

.There are 3 types of workflows in WWF: Sequential Workflow: The sequential workflow style executes a set of contained activities in order, one by one and does not provide an option to go back to any step...........

72.What are XOML files? Explain their uses.

.XOML is an acronym for Extensible Object Markup Language. XOML files are the markup files. They are used to declare the workflow and are then compiled with the file containing the implementation logic..............





C# Interview Question

1. What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

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


3. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
 The first one performs a deep copy of the array, the second one is shallow.

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

5. What’s the .NET datatype that allows the retrieval of data by a unique key?
HashTable.

6. What’s class SortedList underneath?
 A sorted HashTable.

7. Will finally block get executed if the exception had not occurred?
Yes.

8. What’s 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. What’s a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

12. What’s a multicast delegate?
 It’s a delegate that points to and eventually fires off several methods.

13. How’s 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. What’s 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. What’s 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 command-line compiler?
Compile it with a /doc switch.

19. What’s the difference between and XML documentation tag?
Single line code example and multiple-line code example.

20. Is XML case-sensitive?
Yes, so and 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 that’s pointed to by this reference. Object’s 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. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

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 it’s 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. What’s 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?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

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 hasn’t), 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. What’s 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.

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

43. Why does DllImport not work for me?
 All methods marked with the DllImport attribute must be marked as public static extern.

44. Why does my Windows application pop up a console window every time I run it? 
 Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.

45. Why do I get an error (CS1006) when trying to declare a method without specifying a return type?
If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)

46. Why do I get a syntax error when trying to declare a variable called checked? 
 The word checked is a keyword in C#.

47. Why do I get a security exception when I try to run my C# app?
 Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.

48. Why do I get a CS5001: does not have an entry point defined error when compiling? 
 The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }

49. What optimizations does the C# compiler perform when you use the /optimize+ compiler option? 
 The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.

50. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)?
The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } public static void Main() {} }

51. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? 
 Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.

52. What is the difference between a struct and a class in C#?
From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.

53. My switch statement works differently than in C++! Why? 
 C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:

switch(x)

{

case 0: // do something

case 1: // do something as continuation of case 0

default: // do something in common with

//0, 1 and everything else

break;

}

To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):

class Test

{

public static void Main() {

int x = 3;

switch(x)

{

case 0: // do something

goto case 1;

case 1: // do something in common with 0

goto default;

default: // do something in common with 0, 1, and anything else

break;

}

}

}

54. Is there regular expression (regex) support available to C# developers? 
 Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.

55. Is there any sample C# code for simple threading? 
 Yes:

using System;

using System.Threading;

class ThreadTest

{

public void runme()

{

Console.WriteLine("Runme Called");

}

public static void Main(String[] args)

{

ThreadTest b = new ThreadTest();

Thread t = new Thread(new ThreadStart(b.runme));

t.Start();

}

}

56. Is there an equivalent of exit() for quitting a C# .NET application? 
 Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.

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

58. Is there a way of specifying which block or loop to break out of when working with nested loops? 
 The easiest way is to use goto:

using System;

class BreakExample

{

public static void Main(String[] args) {

for(int i=0; i<3; i++)

{

Console.WriteLine("Pass {0}: ", i);

for( int j=0 ; j<100 ; j++ )

{

if ( j == 10)

goto done;

Console.WriteLine("{0} ", j);

}

Console.WriteLine("This will not print");

}

done:

Console.WriteLine("Loops complete.");

}

}

59. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace? 
 There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.

60. What is the modifier protected internal in C#?
The Protected Internal can be accessed by Members of the Assembly or the inheriting class, and of course, within the class itself. In VB.NET, the equivalent of protected internal is protected friend.The access of this modifier is limited to the current assembly or the types derived from the defining class in the current
assembly.

Collection in C#

csharpwithdj.blogspot.com
The .NET Framework has powerful support for Collections. Collections are enumerable data structures that can be assessed using indexes or keys. This article discusses Collections in .NET with code examples.


The System.Collections namespace

The System.Collections namespace provides a lot of classes, methods and properties to interact with the varying data structures that are supported by it. The interfaces that are defined in this namespace include:

• IEnumerable

• IEnumerator

• ICollection

• IList

• IDictionary

The following are the classes that are derived from the ICollection interface.

• System.Collections.Stack

• System.Collections.Queue

• System.Collections.BitArray

• System.Collections.Specialized.NameValueCollection

The IDictionary interface represents collections that have name value pairs. The collections that inherit the IDictionary interface include:

• System.Collections.SortedList

• System.Collections.Hashtable

• System.Collections.Specialized.HybridDictionary

• System.Collections.Specialized.ListDictionary

The IList interface represents collections that only have value. The following are the classes that extend this interface.

• System.Array

• System.Collections.ArrayList

• System.Collections.Specialized.StringCollection

The IEnumerable Interface

An enumerator is an object that provides a forward, read-only cursor for a set of items. The IEnumerable interface has one method called the GetEnumerator() method. This method returns an object that implements the IEnumerator interface. The code snippet below illustrates how an enumerator can be used to iterate though a list or collection of items.

Listing 1

String names[]=new String[2] {”Joydip”,”Jini”};

for(IEnumerator e =names.GetEnumerator();e.MoveNext();Response.Write(e.Current));

Note that the GetEnumerator() method returns an enumerator object each time it is called. Further, the loop contains the Response.Write statement in its re-initializer portion, which is perfectly valid. The condition being evaluated is whether the MoveNext() method returns a value of true. The MoveNext() method returns true as long as there are items in the collection. The Current property returns the current object and is automatically typecast to string by making a call to the ToString() method implicitly.

The foreach method can also be used in this case, as it calls the enumerator implicitly. The above code can be re-written using a foreach loop as follows:

Listing 2

String names[]=new String[2] {”Joydip”,”Jini”};

foreach(string str in names)

Response.Write(str);

ArrayList

The ArrayList class is a dynamic array of heterogeneous objects. Note that in an array we can store only objects of the same type. In an ArrayList, however, we can have different type of objects; these in turn would be stored as object type only. We can have an ArrayList object that stores integer, float, string, etc., but all these objects would only be stored as object type. An ArrayList uses its indexes to refer to a particular object stored in its collection. The Count property gives the total number of items stored in the ArrayList object. The Capacity property gets or sets the number of items that the ArrayList object can contain. Objects are added using the Add() method of the ArrayList and removed using its Remove() method. An example of usage of an ArrayList is given below.

Listing 3

using System;
using System.Collections;
class Test
{

static void Main()

{

int i = 100;
double d = 20.5;
ArrayList arrayList = new ArrayList();
arrayList.Add("Joydip");
arrayList.Add(i);
arrayList.Add(d);
for (int index = 0; index
Console.WriteLine(arrayList[index]);
}

}

It is to be noted here that the initial capacity of an ArrayList is 16, which is increased once the 17th item is stored onto it. This repeated memory allocation and copying of the items can be quite expensive in some situations. For performance reasons we can set the initial capacity of the object of an ArrayList by using the Capacity property or an overloaded constructor of the ArrayList class. This is shown in the example below.

Listing 4

using System;

using System.Collections;

class Test

{

static void Main()

{

int i = 100;

double d = 20.5;
ArrayList arrayList = new ArrayList();

arrayList.Capacity = 2;

arrayList.Add("Joydip");

arrayList.Add(i);

arrayList.Add(d);

for (int index = 0; index

Console.WriteLine(arrayList[index]);

}

}

StringCollection

The StringCollection class implements the IList interface and is like an ArrayList of strings. The following code example shows how we can work with a StringCollection class.

Listing 5

using System;

using System.Collections;

using System.Collections.Specialized;

class Test

{

static void Main()

{

StringCollection stringList = newStringCollection();

stringList.Add("Manashi");

stringList.Add("Joydip");

stringList.Add("Jini");

stringList.Add("Piku");

foreach (string str in stringList)

{

Console.WriteLine(str);

}

}

}

StringDictionary

Similar to the StringCollection class we have the StringDictionary class, which is just a Hashtable that has its keys as strings only. Remember that a Hashtable can contain any object type in its key. The following code shows how we can work with a StringDictionary class.

Listing 6

using System;
using System.Collections;

using System.Collections.Specialized;

class Test

{

static void Main()

{

StringDictionary stringList = newStringDictionary();

stringList.Add("A", "Manashi");

stringList.Add("B","Joydip");

stringList.Add("C","Jini");

stringList.Add("D","Piku");
foreach (string str in stringList.Values)

{

Console.WriteLine(str);

}



}

}

Stack

The Stack class is one that provides a Last-in-First-out (LIFO) collection of items of the System.Object type. The last added item is always at the top of the Stack and is also the first one to be removed. The following code sample shows how we can use a Stack class for LIFO operation on its collection of items.

Listing 7

using System;

using System.Collections;

class Test

{

static void Main()

{

Stack stackObject = new Stack();

stackObject.Push("Joydip");

stackObject.Push("Steve");

stackObject.Push("Jini");

while (stackObject.Count > 0)

Console.WriteLine(stackObject.Pop());

Console.ReadLine();

}

}

The Push() method is responsible for storing items in the Stack and the method Pop() removes them one at a time from the top of the Stack.

Queue

Unlike the Stack class, the Queue is a data structure that provides a First-in-First-out collection of items of the System.Object type. The newly added items are stored at the end or the rear of the Queue and items are deleted from the front of the Queue. The following code shows how the Queue class can be used.

Listing 8

using System;
using System.Collections;

class Test

{

static void Main()

{

Queue queueObject = new Queue();

queueObject.Enqueue("Joydip");

queueObject.Enqueue("Steve");

queueObject.Enqueue("Jini");

while (queueObject.Count > 0)

Console.WriteLine(queueObject.Dequeue());

Console.ReadLine();

}

}

The Enqueue() method is responsible for storing items at the rear of the Queue and the method Dequeue() removes them one at a time from the front of the Queue.

BitArray

The BitArray class can be used to store bits in an array. They can be set to true or false, depending on the parameter supplied at the time of creating the BitArray object. The following is an example of its usage.

BitArray bitArray = new BitArray(5,false);

Or

BitArray bitArray = new BitArray(5,true);

Similar to the other collections discussed above, the BitArray class also contains the Count property to get the number of items stored in this collection of bit values. The following methods of the BitArray class allow logical bit operation.

• And

• Or

• Not

• Xor

Hashtable

The Hashtable provides a faster way of storage and retrieval of items of the object type. The Hashtable class provides support for key based searching. These keys are unique hash codes that are unique to a specific type. The GetHashCode() method of the Hashtable class returns the hash code for an object instance. The following code snippet shows how we can use a Hashtable class.

Listing 9

using System;
using System.Collections;

class Test

{

static void Main()

{

Hashtable hashTable = new Hashtable();

hashTable.Add(1, "Joydip");

hashTable.Add(2, "Manashi");

hashTable.Add(3, "Jini");

hashTable.Add(4, "Piku");

Console.WriteLine("The keysare:--");

foreach (int k in hashTable.Keys)

{

Console.WriteLine(k);

}

Console.WriteLine("Please enter the keyto search");

int p = int.Parse(Console.ReadLine());

Console.WriteLine(hashTable[3].ToString());

}

}

To remove an item from the Hashtable class, the Remove() method is used. The statement hashTable.Remove(3) would remove the item “Jini” from the Hashtable object created in the above code. The code shown above can also be written as shown below to display the contents of the Hashtable object using IDictionaryEnumerator.

Listing 10

using System;

using System.Collections;

class Test

{

static void Main()

{

Hashtable hashTable = new Hashtable();

hashTable.Add(1, "Joydip");

hashTable.Add(2, "Manashi");

hashTable.Add(3, "Jini");

hashTable.Add(4, "Piku");

Console.WriteLine("The keysare:--");

IDictionaryEnumerator en =hashTable.GetEnumerator();

string str = String.Empty;

while (en.MoveNext())

{

str = en.Value.ToString();

Console.WriteLine(str);

}

}

}

SortedList

The SortedList class allows items of the System.Object type to be placed in the collection using key value pairs and, at the same time, supports sorting. The following code shows how we can use a SortedList.

Listing 11

using System;

using System.Collections;

using System.Collections.Specialized;

class Test

{

static void Main()

{

SortedList sortedList = new SortedList();

sortedList.Add(1, "Manashi");

sortedList.Add(3, "Joydip");

sortedList.Add(2, "Jini");

sortedList.Add(4, "Piku");

Console.WriteLine("Displaying thenames");

foreach (string str in sortedList.Values)

{

Console.WriteLine(str);

}

}

}

The output of the above code is:

Manashi

Jini

Joydip

Piku

The same code can be written using IDictionaryEnumerator to display all the items of the SortedList object, as shown below.

Listing 12

using System;

using System.Collections;

using System.Collections.Specialized;

class Test

{

static void Main()

{

SortedList sortedList = new SortedList();

sortedList.Add(1, "Manashi");

sortedList.Add(3, "Joydip");

sortedList.Add(2, "Jini");

sortedList.Add(4, "Piku");

Console.WriteLine("Displaying thenames");

IDictionaryEnumerator en = sortedList.GetEnumerator();

string str = String.Empty;

while (en.MoveNext())

{

str = en.Value.ToString();

Console.WriteLine(str);

}

}

}

Type Safe Collections

Type safe collections are those that comprise of a known type. It would support indexing as an array and has a lot of benefits. A strong typed collection is implemented using any of the following classes.

• CollectionBase

• ReadOnlyCollectionBase

• DictionaryBase

The following are the advantages of using strong typed collections.

• Supports indexing

• Supports enumeration

• Supports dynamic resizing

• Supports serialization

Implementing a Custom Collection Class

The following section shows how we can implement a custom collection class. The following code shows how we can use the "design a custom collection class" by sub-classing the CollectionBase class.

Listing 13

using System;

using System.Collections;

public class Product: CollectionBase

{

public Product this[int index]

{

get

{

return ((Product)(List[index]));

}

set

{

List[index] = value;

}

}

public bool Contains(Product product)

{

return List.Contains(product);

}

public int Add(Product Product)

{

return List.Add(Product);

}

public void Insert(int index, Product product)

{

List.Insert(index, product);

}

public void Remove(Product product)

{

List.Remove(Product);

}

}

The following code shows how we can use the "design a custom collection class" by sub-classing the DictionaryBase class.

Listing 14

using System;

using System.Collections;


public class Product: DictionaryBase

{

public Product this[int index]

{

get

{

return ((Product)(Dictionary[index]));

}

set

{

Dictionary[index] = value;

}

}


public bool Contains(Product product)

{

return Dictionary.Contains(product);

}


public int Add(Product Product)

{

return Dictionary.Add(Product);

}


public void Insert(int index, Product product)

{

Dictionary.Insert(index, product);

}


public void Remove(Product product)

{

Dictionary.Remove(Product);

}

}


Suggested Readings

http://www.15seconds.com/issue/030429.htm

http://www.csharphelp.com/archives/archive183.html

http://www.ondotnet.com/pub/a/dotnet/2003/03/10/collections.html

Conclusion

Though Collections are quite powerful, they should be used judiciously. One should always choose the right type of collection when working with them, as collections can degrade performance due to the overhead involved in boxing and unboxing when used with value types. Try and always choose the simplest collection possible that will provide the functionality required.