• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C# » Advanced Csharp

Operator Overloading in C#

By Dinesh Thakur

Another important and exciting feature object-oriented programming is Operator overloading. C# supports the concept of operator overloading.

Operator overloading is a concept in which operator can defined to work with the userdefined data types such as structs and classes in the same way as the pre-defined data types.

Consider an example:

 

Overloading on ‘+’ operator

 

using System;

public class Item

{

pub1ic int i;

public Item( int j)

{

i = j;

}

public static Item operator + ( Item x , Item y)

-{

system.console.writeLine(“operator +” + x.i +” “+ y.i);

Item z = new Item(x.i+y.i);

return z;

}

}

public class Test

{

public static void Main()

{

Item a = new Item(l0);

Item b = new Item(5);

Item c;

c = a + b ;

system.console.writeLine(c.i);

}

}

OUTPUT:

Operator + 10 5

15

The word operator as the name of a function, is legal and the only way to overload operators. We follow this word with the operator we want to overload and then the parameters we will call the operator with. + is a binary operator and will need two Item’s, one on its left and the other on its right. Then at beginning, we give the return value. of the operator. In our case we want a + to add two Item’s and return a third Item where i will be the sum of the individual i’s. Thus a+b will call the operator + with x being equal to a and y to b. Thus x.i will have a value 10 and y.i, 5. We are creating a new object z and in the constructor passing 15 i.e. 10 + 5. Thus the i of z will be 15 which is being returned. a + b will now be replaced by the object whose i has a value 15 and c will be equal to this object. Thus c.i will be equal to 15.

There are many operators that cannot be overloaded. Which are listed below:

• Conditional Operator                    & &, II

• Compound Assignment                +=, -=, *=, 1=, %=

• Other Operators                            [], 0, = , ?:, ->, new, sizeof, typesof, is, as

Multiple Calling of Overloaded Operator.

 

using system;

public class Item

{

pub1ic int i;

public Item( int j)

{

i = j;

}

public static Item operator + ( Item x , Item y)

{

system.console.writeLine(“operator +” + x.i +u ” + y.i);

Item z = new Item(x.i+y.i);

return z;

}

}

public class Test

{

public static void Main()

{

Item a = new Item(lO);

Item b = new Item(5);

Item c = new Item(2);

Item d;

d = a’+ b + c ;

system.Console.writeLine(d.i);

}

}

OUTPUT:

Operator + 10 5

Operator + 15 2

17

There is only change d = a + b + c from above example. C# gets easily confused with complex statements so it does not read all of it. It sees two operators on the same line. In this case, the same plus. An internal rule tells it to read the plus left to right i.e. it will only see a + b. It will call the operator + with x.i as 10 and y.i as 5 because a’s i is 10 and obi’s i is 5. This will create a temporary object like Item whose i is 15, lets call it zz. The object z is very different from zz. C# then evaluates zz + c. Thus x.i will display 15 and y.i will have the value of c.i i.e. 2. To support multiple invocations of the operator on a single line, the code does not change.

Versioning a .NET Assembly

By Dinesh Thakur

Application development as the name suggest is a development process. With time, new functionality is added to current applications and hence different versions of the application come to existence. Application development for quite sometime has been focused towards component oriented development. Hence an upgrade of the application definitely means an upgrade of the components. These components need to be versioned along with the application. Often components alone can face an upgrade-offering new functionality. When this happens, existing clients face a problem when the component they reference is upgraded. Net assemblies attempt to solve this problem by embedding the version information into the assembly itself. With the advanced capabilities of Windows 2000, two different assemblies can be loaded into the memory side-by-side.

we shall take a look at how developers can set version numbers for their .Net Assemblies and how these assemblies can be loaded side-by-side.

Versioning a .NET Assembly

An assembly version is a number, which basically consist of four parts. These four parts are

 

1. Major

2. Minor

3. Revision

4. Build

                  Versioning a .NET Assembly

Major/Minor Number: If there is a change in major or minor number, it indicates that the assembly is incompatible with the previous version of that assembly.

Revision Number: If there is a change in revision number, it indicates that the assembly may be compatible with the previous version of that assembly.

Build Number: If there is a change in build number, it indicates that a very minor change has been made to the assembly.

Version numbers for an assembly are set in AssemblyInfo.cs file (located in solution explorer of VS.NET).

The assemblyinfo.cs file contains assembly attributes for setting various metadata values for the assembly like company name, copyright statement and kind. The file also contains an assembly version attribute, which can be used to set the version number of the assembly.

 

Events in C#

By Dinesh Thakur

In object-oriented languages, objects expose encapsulated functions called methods. Methods are encapsulated functions which run when they are invoked.

Sometimes, however, we think of the process of method invocation more grandly. In such a case, the method invocation is termed an ‘event’, and the running of the method is the ‘handling’ of the event. An standard example of an event is a user’s selection of a button on a graphical user interface; this action may trigger a number of methods to ‘handle’ it

Events provide a way for a class or object to notify other classes or objects when something of interest happens. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

Even modeling is fully based the delegate model of C# language. According to the event modeling, publishers send out their event only to subscribers who have subscribed to receive the specific event.

                          publishers send out their event only to subscribers who have subscribed to receive the specific event.

Let us look at how events are declare in C# syntax:

 

[modifier] event [type] [Event identifier];

In the above syntax, the modifier is any allowed scope modifier. The type must be delegate and the Event identifier is any valid identifier which you will refer in you program.

What distinguishes events from other method invocations is not, however, that they must   generated externally. Any internal change in the state of a program can be used as an event. Rather, what distinguishes events is that they are backed by a particular ‘subscription notification’ model. An arbitrary class must be able to ‘subscribe to’ (or declare its interest in) a particular event, and then receive a ‘notification’ (ie. have one of its methods run) whenever the event occurs.

Events have the following properties:

• The publisher determines when an event is raised, the subscribers determine what action is taken is response to the event.

• An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.

• Events that the have no subscriber are never called.

• Events are commonly used to signal user actions such as button clicks or menu selection in graphical user interface.

• When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised.

• Events can be used to synchronize threads.

• In the .NET framework class library, events are based on the Event Handler delegate and the EventArgs base class.

Delegates (in particular multicast delegates) are essential in realizing this subscription notification model.

Here is the simple user defined event shown in sample example.

 

Simple userdefined Event.

 

using system;

public delegate void Edelegate();

public class sample

{

public event Edelegate eve; II Event declaration

public void first ()

{ Console.writeLine (“I am First”); }

public void second ()

{ console.writeLine (“I am second”); }

public void Third ()

{Console.writeLine (“I am Third”); }

public void eveCall ()

{ if (eve!=null) eve (); }

}

class Demo

{ pubic static void Main ()

{

sample s = new sample ();

S.eve + = new Edelegate (s.first);

S.evecall ();

console.writeLine (U “);

S.eve + = new Edelegate (S.second);

S.evecal1 ();

console.writeLine(U— ..-.-.–“);

S.eve + = new Edelegate (s.Third);

S.evecal1 ();

}

}

 

OUTPUT:

 

I am First         I am First

I am First         I am Second

I am Second    I am Third

 

Predefined Event of Timer.

 

using system;

using system.collections;

using system.Text;

using System.Timers;

 

class EventTest

{

 

static int counter = 0;

static string str = “This string will appear one letter at

a time.”;

 

static void Main(string[] args)

{

Timer myTimer = new Timer(lOO);

myTimer.Elapsed +=new ElapsedEventHandler(writeChar);

myTimer.Start();

console.ReadLine();

}

 

static void writechar(object source, ElapsedEventArgs e)

{

console.write (str[counter++ % str.Length]);

}

}

OUTPUT: (program wills tenninate by pressing any key)

This string will appear one letter at a time. This string will appear one letter at a time.

This string wills appea.

Tips for Events

The code above demonstrates some points about event-handling which are not enforced by the language architecture, bl,lt are used throughout the .Net framework as good practice.

1. When you want to raise an event in code, you don’t tend to trigger the class’s event object directly. Rather, you call a ‘protected, virtual’ method to trigger it (cf. the onMyEvent method above).

2. By convention, when events are raised they pass two objects to their subscribers. The first is a reference to the class raising the event; the second is an instance of the System.EventArgs class which contains any arbitrary data about the event

3. If an event is not interested in passing data to subscribers, then its defining delegate will still reference an EventArgs object (but a null value will be passed by the event).

If an event should pass data to its subscribers, however, then it is standard to use a specific class which derives from the EventArgs class to hold this data.

 

4. When you write a class which inherits from an event-raising base class, you can ‘intercept’ an event by overriding the method used to raise it. The following code illustrates such an intercept – classes which subscribe to the event will never receive notifications about it.

 

protected override void onMyEvent(EventArgs args)

{

console.writeLine(“hello”);

}

 

If you want subscribers to continue to receive notifications despite such an ‘intercepting’ method, however, then you can call the base class method as in the following:

 

protected override void onMyEvent(EventArgs args)

{

console.writeLine(“hello”);

base.onMyEvent(args);

}

Delegates in C#

By Dinesh Thakur

Delegate is a method template which used to implement the concept of function pointer.

 

The C and C++ languages are having the concept of function pointer. This was even more useful when programming for the Microsoft Windows operating systems because the Win32 library relies on the concept of callback functions. Callback functions are used in Microsoft Windows programming to process messages. For this reason and because of their functionality, callback functions were carried out in the .NET Framework but they were defined with the name of delegate.

~ Concept

A delegate is a special type of user-defined variable that is declared globally, like a class.

In fact, a delegate is created like an interface but as a method. Based on this, a delegate interface, a delegate is not defined. Its role is to show what a useful method would look like.To support this concept, a delegate can provide all the necessary information that would be used on a method. This includes a return type, no argument or one or more Argument.

Delegate Declaration and Instantiation

Delegates can be specified in their own namespace, or else can ‘be specified within other class. In each case, the declaration specifies a new class, which inherits from System.MulticastDelegate.

Each delegate is limited to referencing methods of a particular kind only. The type is indicated by the delegate declaration – the input parameters and return type given in the delegate declaration must be shared by the methods its delegate instances reference. To illustrate this: a delegate specified as below can be used to refer only to methods which have a single String input and no return value:

 

public delegate void print (String s);

 

Suppose, for instance, that a class contains the following method:

 

public void realMethod (String myString)

{

// method code

}

Another method in this class could then instantiate the ‘Print’ delegate in the following way, so that it holds a reference to ‘realMethod’:

 

print delegatevariable = new print(realMethod);

We can note two important points about this example. Firstly, the unqualified method passed to the delegate constructor is implicitly recognised as a method of the instance passing it. That is, the code is equivalent to:

 

Print delegatevariable = new print (this.realMethod);

We can, however, in the same way pass to the delegate constructor the methods of other class instances, or even static class methods. In the case of the former, the instance must exist at the time the method reference is passed. In the case of the latter (exemplified below), the class need never be instantiated.

 

Print delegatevariable = new

print(ExampleClass.exampleMethod);

 

Use of delegate

 

using System;

//delegate declaration

delegate int operation(int x, int y);

class MathOpr

{

public static int Add(int a,

{

return(a + b); }

public static int Sub(int a,

{

return( a – b); }

public static int Mul(int a,

{

return( a * b);

}

}

class Test

{

public static void Main () {

}

//delegate instances

operation opr1 = new operation (Mathopr.Add);

operation opr2 = new operation (Mathopr.sub);

operation opr3 = new operation (Mathopr.Mul);

 

//invoking of delegates

int ans1 = opr1(200, 100);

int ans2 = opr2(200, 100);

int ans3 = opr3(20,10);

 

Console.writeLine(“\n Addition :”+ ans1);

console.writeLine(“\n Subtraction :”+ ans2);

Console.writeLine(“\n Multiplication :”+ ans3);

}

}

 

OUTPUT:

Adiition: 300

Subtraction: 100

Multiplication: 200

Multicast Delegates

The second thing to note about the example is that all delegates can be constructed in this fashion, to create a delegate instance which refers to. a single method. However, as we noted before, some delegates-termed ‘multicast delegates‘ – can simultaneously reference multiple methods. These delegates must-like our Print delegate – specify a ‘void’ return type•

One manipulates the references of multicast delegates by using addition and subtraction.

The following code gives some examples:

print s = null;

s = s + new print (realMethod);

s += new print (otherRealMethod);

The – and – = operators are used in the same way to remove method references from a delegate.

The following code gives an example of the use of multicast delegates.

Use of Multicast delegates

 

using system;

delegate void Multiel();

class MD

{

static public void Hello()

{

console.writeLine(“Hello”);

}

static public void show()

{

console.writeLine(” Hi”);

}

}

class Test

{

public static void Main()

{

//delegate instances

Multioel Ml = new Multioel(Mo.Hello);

Multioel M2 = new Multioel(Mo.hello);

}

/combine the delegates

Multioel M3 = Ml + M2;

Multioel M4 = M2 + Ml;

//extracting the delegates

Multioel M5 = M3 – M2;

Multioel M6 = M4 – Ml;

//invoking delegates

M3 () ;

M4();

M5();

M6();

}

}

 

OUTPUT:

Hello

Hi

Hi

Hello

hello

Hi

Delegates vs. Interface

Delegates and interfaces are similar in that they enable the aspiration of specification and implementation. Multiple independent authors can produce implementations that are compatible with an interface specification. Similarly, a delegate specifies the signature of a method, and authors can write methods that are compatible with the delegate specification. When should you use interfaces, and when should you use delegates?

Delegates are useful when

• A single method is being called.

• A class may want to have multiple implementations of the method specification.

• It is desirable to allow using a static method to implement the specification.

• An event like design pattern is desired.

• The caller has no need to know or obtain the object that the method is defined on.

• The provider of the implementation wants to “hand out” the implementation of the specification to only a few selected components.

• Easy composition is desired

Interfaces are useful when:

• The specification defines a set of related methods that will be called.

, • A class typically implements the specification only one.

• The caller of the interface wants to cast to or from the interface to obtain interface or classes.

Indexers in C#

By Dinesh Thakur

An indexer is a member that enables objects to be indexed in the same as an array.

If properties are ‘virtual fields‘, indexers are more like ‘virtual arrays‘. Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties except that their accessors take parameters. They allow a class to emulate an array, where the elements of this array are actually dynamically generated by function calls.

An indexer is declared like a property except that the name of the member is this followed by a parameter list written between the delimeters [ and ]. The paramaters are available in the accessor(s) of the indexer. Similar to properties, indexers can be read-write, readonly, and write only and the accessor of an indexer can be virtual.

 

The following piece of code defines a class to hold a list of runners in an athletics race. The runners are held in lane order, and an indexer is exposed which allows the list to be both read from and written to. The indexer deals gracefully with cases in which the lane number passed to it is either too high or too low.

 

class RaceDetails

{

private string[] lanes;

public RaceDetails()

{

this.lanes = new strings[8];

}

public string this[int i]

{

get

{

return (i>=0 && i<8) ? this.lanes[i] : “error”;

 

}

set

{

if (i>=0 && i<8)

this.lanes[i] = value;

}}

}

 

 

The following simple code illustrates use being made of the class just defined. The name of the person in the race’s first lane is set, and then this name is sent to a console window.

 

RaceDetails rd = new RaceDetails();

rd[0] = “fred”;

Console.writeLine (“lane One :” + rd[0]) ;

 

As can be seen from the example, an indexer is defined in a similar way to a property. One important difference is in the indexer’s signature; the word ‘this’ is used in place of a and after this word indexing elements are provided.

~ Concept

Indexers aren’t differentiated by name, and a class cannot declare two indexers with the same signature. However, this does not entail that a class is limited to just one indexer. Different indexers can have different types and numbers of indexing elements (these being equivalent to method parameters, except that each indexer must have at least one indexing element, and the ‘ref and ‘out’ modifiers cannot be used).

Because indexing elements are not limited to integers, the original description of indexers as ‘virtual arrays’ actually rather undersells them. For example, where the indexing elements include strings, indexers present themselves more like hash tables.

The following code shows an implementation for the RaceDetails class of an indexer whose indexing element is a string. Using this indexer it is possible to refer to a lane using the name of the person currently filling that lane.

 

public string this[string s]

{

get

{

Int laneNum = getposition(s);

return (laneNum<0) ? “error” : this.lanes[laneNum];

}

set

{

int laneNum = getposition(s);

if (laneNum>=0) this.lanes[laneNum] = value;

}

}

private int getposition(string myName)

{

for (int x=0; x<lanes.Length; x++)

{

if (myName==lanes[x]) return x;

}

return -1;

}

The following piece of code gives an example of the kind of use one might make of this string indexer.

 

rd[“fred”] = “j ill”;

After the execution of this code, the name “fred” will be replace with name the “jill” in object array ‘rd’. The string indexer will return index number of “fred” where “jill” will be aced.

The following example shows how to declare a private array field, myArray, and an. sing the indexer’ allows direct access to the instance b [i] The alternative to using the indexer is to declare the array as a public member and access its membersmyArray [i] directly.

 

Indexer

 

using System;

class indexerclass

{

private int[] myArray = new int [100];

public int this [int index] //indexer declaration

{ 

get

{

// Check the index limits

if (index < 0 //dex >,:, = 100)

return 0;

else

return myArray [index];

}

set

{

if (! (index < 0 Ilindex > = 100)

myArray [index] = value;

}

}

}

public class Mainclass

{

public static void Main()

{

Indexerclass b = new IndexerClass();

// call the indexer to initialize the elements # 3 and # 5.

b[3] = 256;

b(5] = 1024;

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

{

Console.writeLine (“element” {0} = {1}”, i, b[i]);

}

}

}

 

OUTPUT:

 

Element # 0 = 0

Element # 1 = 0

Element # 2 = 0

Element # 3 = 256

Element # 4 = 0

Element # 5 = 1024

Element # 6 = 0

Element # 7 = 0

Element # 8 = 0

Element # 9 = 0

Element # 10 = 0

 

Notice that when an indexer’s access in evaluated (for example in a Console.Writer statement) the get accessor is invoked. Therefore, if no get accessor exists a compile-time error occurs.

 

Comparison between Properties and Indexers

 

Indexers are similar to properties. Except for the difference shown in the following table, all of the rules defined for property accessors apply to indexer accessor as well.

                         Comparison between Properties and Indexers

Properties in C#

By Dinesh Thakur

Property is a feature to add more smartness to data fields for get and set the value.

Properties are named members of classes, structs and interfaces. They provide a flexible mechanism to read, write, or compute the values of private fields through accessors. Properties can be thought of as virtual fields. From the outside, a class’ property looks just like a field. But from the inside, the property is generated using the actual class fields.

Property declarations take just those modifiers taken by methods. Unlike languages like Java,C# provides dedicated support for accession and mutation of these properties. Suppose, for instance, that a type contains an internal field called ‘age’. With the following code one could specify a property Age, providing accessors and mutators to this internal field

 

public int Age

{

get

{

return this.age;

}

set

{

this.age = value;

}

}

Notice that the term ‘value’ is used in the above .piece of code. This variable always holds

the value passed to the ‘set’ block.· For instance, the execution of the following line of ode (assuming the appropriate class instance) would automatically set ‘value’ in the ‘set’ block to 4.

person.Age = 4;

This property Age can be described as ‘read-write’ since it can be both read from and written to. To make a property ‘write-only’ one simply does not specify a ‘get’ block; to make it ‘readonly’ one does not specify a ‘set’ block. The following piece of code demonstrates the read-only property ‘Adult’:

 

public bool Adult

{

get

{

if (this.age<18)

       return false;

else

return true;

}

}

A property declared using the static modifiers is classified as a static property; otherwise, it is classified as an instance property. Like other static members, a static property is not associated with a specific instance and cannot be referenced through an instance. Instead, it is associated with the type and can only be referenced an instance. Instead, it is associated with the type and can only be referenced through the type name. For example, in the following statements:

 

Button okButton = new Button();

// using an instance property

string s = okButton.caption;

the caption property is associated with the instance okButton. If caption is as a static property, the class name (Button) must be used instead :

// using static property

strings = Button. Caption;

An instance of a class can be accessed using this in the accessors of an instance property, but it is an error to use this in the accessors of a static property. It is an error to use a virtual, abstract, or override modifier on an accessor of a static property.

The following example demonstrates instances, static and read-only properties. It accepts the name of the employee from the keyboard, increments number of Emp by 1, and displays the Employee name and number.

 

Use of property.

 

using system;

public class Employee

{

public static int numberofEmp;

private static int counter;

private string name;

public string Name

{

   get

         {

   return name;

         }

   set

       {

         name = value;

}

}

public static int Counter

{

get

{

return counter;

}

set

{

counter = value;

}

}

public Employee()

{

Counter = ++ Counter + numberofEmp;

}

}

public class MainClass

{

public static void Main()

{

Employee.numberofEmp = 100;

Employee e1 = new Employee();

e1.Name = “deepika”;

console.writeline (“Employee number: {O}”, Employee.counter);

console.writeline (“Employee name: {O}”, e1.Name);

}

}

 

OUTPUT:

 

Employee number: 101

Employee name: Deepika

Accessors

The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations take the following forms:

 

set {accessor body}

get {accessor body}

where, accessor body is a block that contains the statements to be executed when the accessor is invoked.

 

The get Accessor

 

The body of the get accessor is similar to that of a method. It must return a value of the property type. The execution of the get accessor is.equivalent to reading the value of the field.

The following is a get accessor that returns the value of private field name :

 

private string name; II the name field

public string Name II the Name property

{

get

{

return name;

}

}

When you reference the property, except as the target of an assignment, the .get accessor is invoked to read the value of the property. For example:

Emp1oyee el = new Employee ();

–

–

console.write (el.Name); II The get accessor is invoked here

The get accessor must terminate is a return or throw statement and control can not flow off the accessor body.

The set Accessor

The set accessor is similar to a method that returns void. It uses an implicit parameter called value, whose type is the type of the property. In the following example, a set accessor is added the Name property.

public string Name

{

       get

     {

             return name;

       }

       set

     {

             name = value;

       }

}

When you assign a value to the property, the set accessor is invoked with an argument that provides the new value. For example:

 

e1 .Name = “Deepika”, // The set accessor is invoked here

It is an error to use the implicit parameter name (value) for a local variable declaration in a set accessor.

A property is classified according to the accessors used as follows:

• A property with a get accessor only is called a read-only property. You can not assign a value to a read-only property.

• A property with a set accessor only is called write-only property. You can not reference a write only property except as a target of an assignment.

• A property with both get and set accessors is a read-write property.

In a property declaration, both the get and set accessor must be declared inside the body of the property.

What is SYSTEM.COLLECTION CLASSES in C#?

By Dinesh Thakur

The Collection namespace of System contains many classes and interfaces, which provides to define various collections of objects. These interfaces and classes are useful for every programmer to develop big or large applications.

 

The .NET Framework provides a rich suite of collection classes, including Array, ArrayList, NameValueCollection, StringCollection, Queue, Stack, and BitArray.

 

Arrays in C# are implemented as instance of System.Array class, and are just one type known as collection classes.

System.Array

 

The Array class has a number of useful methods which extend the capabilities of arrays and make them smarter than arrays seen in other languages.

                   System.Array class, and are just one type known as collection classes

Two useful static methods of Array are Sort( ) and Reverse( ).These are fully supported for the built-in C# types such as string. Example demonstrates the use of these two methods to manipulate String objects

 

Using Array.Sort and Array.Reverse

 

using System;

using System.collections;

public class Tester

{

public static void printMyArray(object[] Arr)

{

foreach (object obj in Arr)

console.writeline(“value: {O}”, obj);

 

Console.writeline(“\n”);

}

static void Main()

{

String[] Arr1 ={“world”, “is”, “Beautiful”};

console.writeline(“Original array is :”);

printMyArray(Arr01);

Array.Reverse(Arr1);

Console.writeline(“After reverse array is :”);

printMyArray(Arr1);

 

String [] Arr2 ={“see”,”it” ,”from” ,”your” ,”heart” ,”eyes”};

 

console.writeline(“Original array is :”);

printMyArray(Arr2);

Array.sort(Arr2);

console.writeline(“After sort array is :”);

printMyArray(Arr2);

}

}

 

OUTPUT:

 

Original Array is:

Value: World

Value: is

Value: Beautiful

After Reveres Array is:

Value: Beautiful

 

Value: is

Value: World

 

Original Array is:

Value: See

Value: it

Value: from

Value: your

Value: heart

Value: eyes

 

After Sort array is:

Value: eyes

Value: from

Value: heart

Value: it

Value: See

Value: your

 

The .NET Framework provides standard interfaces for enumerating, comparing, and creating collections. The key collection interfaces are listed.

                    key collection interfaces are listed

The System.Array class inherits from IList, ICollection, and IEnumerable interfaces, but doesn’t support some of more advanced features of IList and represents, a list of items with a fixed size.

ArrayLists

The classic problem with the Array type is its fixed size. If you do not know in advance how many objects an array will hold, you run the risk of declaring either too small an array (and running out of room) or too large an array (and wasting memory).

Your program might be asking the user for input, or gathering input from a web site. it finds objects (strings, books, values, etc.) you will add them to the array, but you have no idea how many objects you’ll collect in any given session. The classic fixed-size array is not a good choice, as you can’t predict how large an array you’ll need.

The ArrayList class is an array whose size is dynamically increased as required. ArrayLists provide a number of useful methods and properties for their manipulation.

When you create an ArrayList, you do not define how many objects it will contain. You add to the ArrayList using the Add( ) method, and the list takes care of its own internal bookkeeping, as illustrated in simple.

 

Working with an ArrayList

 

using system;

using system.collections;

public class Tester

{

static void Main( )

{

ArrayList number = new ArrayList( );

 

//adding the elements to ArrayList

foreach(int num in new

int[10]{10,9,10,23,45,56,9,12,78,64})

{

number.Add(num);

}

//adding another item out of loop

Number.add(34);

//remove first element whose value is 9

Number.remove(9);

//remove the element of 7th position

Number.removeat(6);

//display the content of arraylist

Console.writeline(“:element of arraylist”);

For(int i=0;i!=number.count;i++)

{

Int num =(int)number[i];

Console.write(num + “,”);

}

//sort the existing elements of ArrayList

number.sort();

console.writeLine(“\nsorted List”);

.for(int i=O;i!=number.count;i++)

{

int num =(int)number[i];

console.write(num+”,”);

}

}

}

 

OUTPUT:

 

Elements of ArrayList

10,10,23,45,56,9,78,64,34

Sorted List

9,10,10,23,34,45,56,64,78

Queue

A queue represents a first-in, first-out (FIFO) collection. The classic analogy is to a line at a ticket window. The first person in line ought to be the first person to come off the line to buy a ticket.

A queue is a good collection to use when you are managing a limited resource. For example, you might want to send messages to a resource which can only handle one message at a time.

You would then create a message queue so that you can say to your clients: “Your message is important to us. Messages are handled in the order in which they are received.”

You can add elements to your queue with the Enqueue command and you can take them off the queue with Dequeue or by using an enumerator.

 

Working with a queue

 

using System;

using system.collections;

public class Tester

{

static void Main( )

{

Queue number = new Queue( );

 

//adding the elements to Queue

foreach(int num in new

int[lO]{lO,9,lO,23,45,56,9,12,78,64})

{

number.Enqueue(num);

}

//adding another item out of loop

number.Enqueue(34)

 

// remove first element

number.Dequeue();

 

II view the first element in the

II Queue but do not remove.

Console.writeLine(“\n(peek) \t{O}”, number.peek( ) );

 

//display the content of Queue

console.writeLine(“\ncontents of Queue”);

printvalues(number);

 

}

public static voidprintvalues( IEnumerable mycollection )

{

IEnumerator myEnumerator = mycollection.GetEnumerator( );

while ( myEnumerator.MoveNext( ) )

console.write( “{O} “,myEnumerator.current );

Console.writeLine( );

}

}

 

OUTPUT:

 

(peek)     9

Contents of Queue:

9 10 23 45 56 9 12 78 64 34

Stacks

A stack is a last-in, first-out (LIFO) collection, like a stack of dishes at a buffet table, or a stack of coins on your desk. You add a dish on top, and that is the first dish you take off   the stack.

The principal methods for adding to and removing from a stack are Push( )and Pop( ); Stack also offers a Peek( ) method, very much like Queue.

The ArrayList, Queue, and Stack types contain overloaded CopyTo( ) and ToArray( ) methods for copying their elements to an array. In the case of a Stack, the CopyTo( ) method will copy its elements to an existing one-dimensional array, overwriting the contents of the array beginning at the index you specify. The ToArray( ) method returns a new array with the contents of the stack’s elements.

 

Working with a Stack

 

using System;

using System.collections;

public class Tester

{

static void Main( )

{

stack intStack = new Stack( );

 

II populate the array

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

{

intStack.push(i*5);

}

// Display the stack.

console.write( “intStack values:\t” );

printvalues( intStack );

 

// Remove an element from the stack

Console.writeLine( “\n(pop)\t{O}”, intstack.pop( ) );

 

// Display the stack

Console.write( “intStack values:\t” );

printvalues( intStack );

 

// Remove another element from the Stack

Console.writeLine( “\n(pop)\t{O}”, intStack.pop( ) );

 

// display the Stack

console.write( “intstack values:\t” );

printvalues( intStack );

 

// view the first element in the

// Stack but do not remove.

Conso1e.writeLine ( “\n(peek) \t{O}”, intStack .Peek( ) );

 

// Display the Stack

Console.write( “intStack values:\t” );

printvalues( intStack );

 

}

public static void printvalues( IEnumerable mycollection )

{

IEnumerator myEnumerator = myCollection.GetEnumerator( );

while ( myEnumerator.MoveNext( ) )

console.write( ”{0} “,myEnumerator.current );

console.writeLine( );

}

}

 

OUTPUT:

 

intStack values: 35 30 25 20 15 10 5 0

(Pop) 35

intStack values: 30 25 20 15 10 5 0

(Pop) 30

intStack values: 25 20 15 10 5 0

(Peek) 25

intStack values: 25 20 15 10 5 0

Hashtables

A hashtable is a dictionary optimized for fast retrieval. In a Hashtable, each value is stored in a “bucket.” The bucket is numbered, much like an offset into an array.

Because the key may not be an integer, it must be possible to translate the key (e.g., “Massachusetts”) into a bucket number. Each key must provide a hash code, a GetHashCode ( ) method will accomplish this magic.

You will remember that everything in C# derives from object. The object class provides a virtual method GetHashCode( ), which the derived types are free to inherit as is or to override. A trivial implementation of a GetHashCode( ) function for a string might  simply add up the Unicode values of each character in the string and then use the modulus operator to return a value between 0 and the number of buckets in the Hashtable. It is not necessary to write such a method for the string type, however, as the CLR provides one for you.

When you insert the values (the state capitals) into the Hashtable, the Hashtable calls GetHashCode( ) on each key we provide. This method returns an int, which identifies the bucket into which the state capital is placed.

It is possible, of course, for more than one key to return the same bucket number. This is called a collision. There are a number of ways to handle a collision. The most common solution, and the one adopted by the CLR, is simply to have each bucket maintain an ordered list of values. When you retrieve a value from the Hashtable, you provide- a key. Once again the Hashtable calls GetHashCode( ) on the key and uses the returned int to find the appropriate bucket. If there is only one value, it is returned. If there is more than one value, a binary search of the bucket’s contents is performed. Because there are few values, this search is typically very fast. see an example

 

Working with a HashTable

 

using System;

using System.collections;

 

// a simple class to store in the array

public class Tester

{

static void Main( )

{

// Create and initialize a new Hashtable.

Hashtable hashTable = new Hashtable( );

hashTable.Add(“000440312”, “Jesse Liberty”);

hashTable.Add(“OOOl23933″, ‘~Stacey Liberty”);

hashTable.Add(“000145938”, “John Galt”);

hashTable.Add(“000773394”, “Ayn Rand”);

// access a particular item

console.writeLine(“{O} “,hashTable[“000145938”]);

}

}

 

OUTPUT:

 

John Galt

SortedList

Some times you might want to provide a mapping where the type you map from isn’t int but rather some other type (string, double). The SortedList class provides this functionality by internally maintaining two objects arrays- one for keys, one for values.

The key array is always sorted.

In contrast to other collection classes, you don’t have control of where the element live in a SortedList. A SortedList can’t contain duplicate keys. however, if you use the squre bracket notation to add a key/value pair, then its ok.

When use a foreach statement to iterate a SortedList, you get back a DictionaryEntry which provides access to the elements in both arrays thru the Key property and Value property.

 

using System;

using System.collections;

public class Tester

{

 

static void Main( )

{

       SortedList map = new SortedList();

       string[] keys = {“these”,”are”,”the”,”keys”};

 

//adding the elements to sortedList

for(int i=O;i!=keys.Length;i++)

{

string k = keys[i];

int v = i;

map[k] = v;

}

console.writeLine(“\ncontent of SortedList”);

foreach(dictionaryEntry element in map)

{

string k = (string) element.Key;

int v = (int)element.value;

console.writeLine(“key: {O},\tvalue: {l}”,k,v);

}

}

}

 

OUTPUT:

 

Content of SortedList

 

key: are, Value: 1

key: keys, Value: 3

key: the, Value: 2

key: these, Value: 0

Primary Sidebar

C# Tutorials

C# Tutorials

  • C# - .NET Languages Types
  • C# - Dot Net
  • C# - Dot Net Framework
  • C# - Inheritance Types
  • C# - Features
  • C# - CTS
  • C# - CLS
  • C# - CLR
  • C# - Console
  • C# - MSIL
  • C# - Base Class Library
  • C# - Web Forms Creation
  • C# - C# Vs C++
  • C# - Statements Types
  • C# - JIT
  • C# - CLI
  • C# - Controls Types
  • C# - String Types
  • C# - Execution Model

Other Links

  • C# - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW