Collections
In this chapter we will deal with C# collections. The .NET framework provides specialized classes for data storage and retrieval. In one of the previous chapters, we have described arrays. Collections are enhancement to the arrays.
There are two distinct collection types in C#. The standard collections, which are found under the System.Collections namespace and the generic collections, under System.Collections.Generic. The generic collections are more flexible and are the preferred way to work with data. The generic collections or generics were introduced in .NET framework 2.0. Generics enhance code reuse, type safety, and performance.
Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters. This approach, pioneered by Ada in 1983, permits writing common functions or types that differ only in the set of types on which they operate when used, thus reducing duplication. (Wikipedia)
ArrayList
ArrayList is a collection from a standard System.Collections namespace. It is a dynamic array. It provides random access to its elements. An ArrayList automatically expands as data is added. Unlike arrays, an ArrayList can hold data of multiple data types. Elements in the ArrayList are accessed via an integer index. Indexes are zero based. Indexing of elements and insertion and deletion at the end of the ArrayList takes constant time. Inserting or deleting an element in the middle of the dynamic array is more costly. It takes linear time.
using System; using System.Collections; public class CSharpApp { class Empty {} static void Main() { ArrayList da = new ArrayList(); da.Add("Visual Basic"); da.Add(344); da.Add(55); da.Add(new Empty()); da.Remove(55); foreach(object el in da) { Console.WriteLine(el); } } }
In the above example, we have created an
ArrayList
collection. We have added some elements to it. They are of various data type, string, int and a class object.using System.Collections;
In order to work with
ArrayList
collection, we need to import System.Collections
namespace.ArrayList da = new ArrayList();
An
ArrayList
collection is created.da.Add("Visual Basic"); da.Add(344); da.Add(55); da.Add(new Empty()); da.Remove(55);
We add five elements to the array with the
Add()
method.da.Remove(55);
We remove one element.
foreach(object el in da) { Console.WriteLine(el); }
We iterate through the array and print its elements to the console.
$ ./arraylist.exe Visual Basic 344 CSharpApp+Empty
Output.
List
A
List
is a strongly typed list of objects that can be accessed by index. It can be found under System.Collections.Generic namespace.using System; using System.Collections.Generic; public class CSharpApp { static void Main() { List<string> langs = new List<string>(); langs.Add("Java"); langs.Add("C#"); langs.Add("C"); langs.Add("C++"); langs.Add("Ruby"); langs.Add("Javascript"); Console.WriteLine(langs.Contains("C#")); Console.WriteLine(langs[1]); Console.WriteLine(langs[2]); langs.Remove("C#"); langs.Remove("C"); Console.WriteLine(langs.Contains("C#")); langs.Insert(4, "Haskell"); langs.Sort(); foreach(string lang in langs) { Console.WriteLine(lang); } } }
In the preceding example, we work with the
List
collection.using System.Collections.Generic;
In order to work with the
List
collection, we need to import the System.Collections.Generic
namespace.List<string> langs = new List<string>();
A generic dynamic array is created. We specify that we will work with strings with the type specified inside <> characters.
langs.Add("Java"); langs.Add("C#"); langs.Add("C"); ...
We add elements to the List using the
Add()
method.Console.WriteLine(langs.Contains("C#"));
We check if the List contains a specific string using the
Contains()
method.Console.WriteLine(langs[1]); Console.WriteLine(langs[2]);
We access the second and the third element of the List using the index notation.
langs.Remove("C#"); langs.Remove("C");
We remove two strings from the List.
langs.Insert(4, "Haskell");
We insert a string at a specific location.
langs.Sort();
We sort the elements using the
Sort()
method.$ ./list.exe True C# C False C++ Haskell Java Javascript Ruby
Outcome of the example.
LinkedList
LinkedList
is a generic doubly linked list in C#. LinkedList only allows sequential access. LinkedList allows for constant-time insertions or removals, but only sequential access of elements. Because linked lists need extra storage for references, they are impractical for lists of small data items such as characters. Unlike dynamic arrays, arbitrary number of items can be added to the linked list (limited by the memory of course) without the need to realocate, which is an expensive operation.using System; using System.Collections.Generic; public class CSharpApp { static void Main() { LinkedList<int> nums = new LinkedList<int>(); nums.AddLast(23); nums.AddLast(34); nums.AddLast(33); nums.AddLast(11); nums.AddLast(6); nums.AddFirst(9); nums.AddFirst(7); LinkedListNode<int> node = nums.Find(6); nums.AddBefore(node, 5); foreach(int num in nums) { Console.WriteLine(num); } } }
This is a
LinkedList
example with some of its methods.LinkedList<int> nums = new LinkedList<int>();
This is an integer
LinkedList
.nums.AddLast(23); ... nums.AddFirst(7);
We populate the linked list using the
AddLast()
and AddFirst()
methods.LinkedListNode<int> node = nums.Find(6); nums.AddBefore(node, 5);
A
LinkedList
consists of nodes. We find a specific node and add an element before it.foreach(int num in nums) { Console.WriteLine(num); }
Printing all elements to the console.
Dictionary
A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory, because for each value there is also a key.
using System; using System.Collections.Generic; public class CSharpApp { static void Main() { Dictionary<string, string> domains = new Dictionary<string, string>(); domains.Add("de", "Germany"); domains.Add("sk", "Slovakia"); domains.Add("us", "United States"); domains.Add("ru", "Russia"); domains.Add("hu", "Hungary"); domains.Add("pl", "Poland"); Console.WriteLine(domains["sk"]); Console.WriteLine(domains["de"]); Console.WriteLine("Dictionary has {0} items", domains.Count); Console.WriteLine("Keys of the dictionary:"); List<string> keys = new List<string>(domains.Keys); foreach(string key in keys) { Console.WriteLine("{0}", key); } Console.WriteLine("Values of the dictionary:"); List<string> vals = new List<string>(domains.Values); foreach(string val in vals) { Console.WriteLine("{0}", val); } Console.WriteLine("Keys and values of the dictionary:"); foreach(KeyValuePair<string, string> kvp in domains) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } } }
We have a dictionary, where we map domain names to their country names.
Dictionary<string, string> domains = new Dictionary<string, string>();
We create a dictionary with string keys and values.
domains.Add("de", "Germany"); domains.Add("sk", "Slovakia"); domains.Add("us", "United States"); ...
We add some data to the dictionary. The first string is the key. The second is the value.
Console.WriteLine(domains["sk"]); Console.WriteLine(domains["de"]);
Here we retrieve two values by their keys.
Console.WriteLine("Dictionary has {0} items", domains.Count);
We print the number of items by referring to the
Count
property.List<string> keys = new List<string>(domains.Keys); foreach(string key in keys) { Console.WriteLine("{0}", key); }
These lines retrieve all keys from the dictionary.
List<string> vals = new List<string>(domains.Values); foreach(string val in vals) { Console.WriteLine("{0}", val); }
These lines retrieve all values from the dictionary.
foreach(KeyValuePair<string, string> kvp in domains) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); }
Finally, we print both keys and values of the dictionary.
$ ./dictionary.exe Slovakia Germany Dictionary has 6 items Keys of the dictionary: de sk us ru hu pl Values of the dictionary: Germany Slovakia United States Russia Hungary Poland Keys and values of the dictionary: Key = de, Value = Germany Key = sk, Value = Slovakia Key = us, Value = United States Key = ru, Value = Russia Key = hu, Value = Hungary Key = pl, Value = Poland
This is the output of the example.
Queues
A
queue
is a First-In-First-Out (FIFO) data structure. The first element added to the queue will be the first one to be removed. Queues may be used to process messages as they appear or serve customers as they come. The first customer which comes should be served first.using System; using System.Collections.Generic; public class CSharpApp { static void Main() { Queue<string> msgs = new Queue<string>(); msgs.Enqueue("Message 1"); msgs.Enqueue("Message 2"); msgs.Enqueue("Message 3"); msgs.Enqueue("Message 4"); msgs.Enqueue("Message 5"); Console.WriteLine(msgs.Dequeue()); Console.WriteLine(msgs.Peek()); Console.WriteLine(msgs.Peek()); Console.WriteLine(); foreach(string msg in msgs) { Console.WriteLine(msg); } } }
In our example, we have a queue with messages.
Queue<string> msgs = new Queue<string>();
A queue of strings is created.
msgs.Enqueue("Message 1"); msgs.Enqueue("Message 2"); ...
The
Enqueue()
adds a message to the end of the queue.Console.WriteLine(msgs.Dequeue());
The
Dequeue()
method removes and returns the item at the beginning of the queue.Console.WriteLine(msgs.Peek());
The
Peek()
method returns the next item from the queue, but does not remove it from the collection.$ ./queue.exe Message 1 Message 2 Message 2 Message 2 Message 3 Message 4 Message 5
The
Dequeue()
method removes the "Message 1" from the collection. The Peek()
method does not. The "Message 2" remains in the collection.Stacks
A stack is a Last-In-First-Out (LIFO) data structure. The last element added to the queue will be the first one to be removed. The C language uses a stack to store local data in a function. The stack is also used when implementing calculators.
using System; using System.Collections.Generic; public class CSharpApp { static void Main() { Stack<int> stc = new Stack<int>(); stc.Push(1); stc.Push(4); stc.Push(3); stc.Push(6); stc.Push(4); Console.WriteLine(stc.Pop()); Console.WriteLine(stc.Peek()); Console.WriteLine(stc.Peek()); Console.WriteLine(); foreach(int item in stc) { Console.WriteLine(item); } } }
We have a simple stack example above.
Stack<int> stc = new Stack<int>();
A
Stack
data structure is created.stc.Push(1); stc.Push(4); ...
The
Push()
method adds an item at the top of the stack.Console.WriteLine(stc.Pop());
The
Pop()
method removes and returns the item from the top of the stack.Console.WriteLine(stc.Peek());
The
Peek()
method returns the item from the top of the stack. It does not remove it.$ ./stack.exe 4 6 6 6 3 4 1
Output.
Constructor types with example programs in C#.NET
A special method of the class that will be automatically invoked when an instance of the class is created is called as constructor. Constructors can be classified into 5 types
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Static Constructor
- Private Constructor
Default Constructor : A constructor without any parameters is called as default constructor. Drawback of default constructor is every instance of the class will be initialized to same values and it is not possible to initialize each instance of the class to different values.Example for Default ConstructorParameterized Constructor : A constructor with at least one parameter is called as parameterized constructor. Advantage of parameterized constructor is you can initialize each instance of the class to different values.
Example for Parameterized Constructor
Example for Parameterized Constructor
using System;namespace ProgramCall
{
class Test1
{
//Private fields of class
int A, B;
//default Constructor
public Test1()
{
A = 10;
B = 20;
}
//Paremetrized Constructor
public Test1(int X, int Y)
{
A = X;
B = Y;
}
//Method to print
public void Print()
{
Console.WriteLine("A = {0}\tB = {1}", A, B);
}
}
class MainClass
{
static void Main()
{
Test1 T1 = new Test1(); //Default Constructor is called
Test1 T2 = new Test1(80, 40); //Parameterized Constructor is called
T1.Print();
T2.Print();
Console.Read();
}
}
}
{
class Test1
{
//Private fields of class
int A, B;
//default Constructor
public Test1()
{
A = 10;
B = 20;
}
//Paremetrized Constructor
public Test1(int X, int Y)
{
A = X;
B = Y;
}
//Method to print
public void Print()
{
Console.WriteLine("A = {0}\tB = {1}", A, B);
}
}
class MainClass
{
static void Main()
{
Test1 T1 = new Test1(); //Default Constructor is called
Test1 T2 = new Test1(80, 40); //Parameterized Constructor is called
T1.Print();
T2.Print();
Console.Read();
}
}
}
Output
A = 10 B = 20
A = 80 B = 40Copy Constructor : A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance.Example for Copy Constructor
using System;namespace ProgramCall
{
class Test2
{
int A, B;
public Test2(int X, int Y)
{
A = X;
B = Y;
}
//Copy Constructor
public Test2(Test2 T)
{
A = T.A;
B = T.B;
}
public void Print()
{
Console.WriteLine("A = {0}\tB = {1}", A, B);
}
}
class CopyConstructor
{
static void Main()
{
Test2 T2 = new Test2(80, 90);
//Invoking copy constructor
Test2 T3 = new Test2(T2);
T2.Print();
T3.Print();
Console.Read();
}
}
}
{
class Test2
{
int A, B;
public Test2(int X, int Y)
{
A = X;
B = Y;
}
//Copy Constructor
public Test2(Test2 T)
{
A = T.A;
B = T.B;
}
public void Print()
{
Console.WriteLine("A = {0}\tB = {1}", A, B);
}
}
class CopyConstructor
{
static void Main()
{
Test2 T2 = new Test2(80, 90);
//Invoking copy constructor
Test2 T3 = new Test2(T2);
T2.Print();
T3.Print();
Console.Read();
}
}
}
Output
A = 80 B = 90
A = 80 B = 90Static Constructor : You can create a constructor as static and when a constructor is created as static, it will be invoked only once for any number of instances of the class and it is during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.Example for Static Constructor
using System;namespace ProgramCall
{
class Test3
{
public Test3()
{
Console.WriteLine("Instance Constructor");
}
static Test3()
{
Console.WriteLine("Static Constructor");
}
}
class StaticConstructor
{
static void Main()
{
//Static Constructor and instance constructor, both are invoked for first instance.
Test3 T1 = new Test3();
//Only instance constructor is invoked.
Test3 T2 = new Test3();
Console.Read();
}
}
}
{
class Test3
{
public Test3()
{
Console.WriteLine("Instance Constructor");
}
static Test3()
{
Console.WriteLine("Static Constructor");
}
}
class StaticConstructor
{
static void Main()
{
//Static Constructor and instance constructor, both are invoked for first instance.
Test3 T1 = new Test3();
//Only instance constructor is invoked.
Test3 T2 = new Test3();
Console.Read();
}
}
}
Output
Static Constructor
Instance Constructor
Instance Constructor
Private Constructor : You can also create a constructor as private. When a class containsat least one private constructor, then it is not possible to create an instance for the class. Private constructor is used to restrict the class from being instantiated when it contains every member as static. Some unique points related to constructors are as follows
- A class can have any number of constructors.
- A constructor doesn’t have any return type even void.
- A static constructor can not be a parameterized constructor.
- Within a class you can create only one static constructor.
Indexers in C# are a simple way to permit a class to be used like an array. The advantage of using indexers rather than exposing an array or generic list object is that internally, you can manage the values presented in any fashion you wish. This means that you can manage the array size, error handling and so forth with a lower likelihood of bugs. It allows you to better manage complex data structures, odd types of class members and so forth, hiding some complexity from other programmers who may not be familiar with a particular requirement. I’ve found indexers to be particularly useful in situations where data is being aggregated from several different sources but needs to be presented as a cohesive group. Below, I’ll present a simple example of a C# indexer and you can take it from there.
First, lets begin with a simple string property that’s accessed via an integer indexer. We’ll assume that there is an array of strings that’s loaded in the class constructor. Here’s what this property looks like…
public string this[int index]
{
get
{
return DataItems[index];
}
set
{
DataItems[index] = value;
}
}
As you can see, we use the this keyword to define the indexer. Also notice that we use brackets [] rather than a parenthesis () in the definition. In this case, our indexer is an integer and we’re expecting a string value to be set or returned by the property. But, the nice thing is that it can be overloaded. So, let’s say that I wanted to be able to send in a string value or an integer value. Here’s how it would be coded…
public string this[string key]
{
get
{
return DataItems[GetIndexForKey(key)];
}
set
{
DataItems[GetIndexForKey(key)] = value;
}
}
In this example, we’re passing in a string value rather than an integer value to determine the return value. A private routine, GetIndexForKey, looks up the internal index value so that it can be set or returned properly in the underlying data. As you can see, overloading indexers can add a lot of flexibility to your code. The indexer could be called either way as seen in these two example lines of code…
IndexTest[1] = "This is a Test";
IndexTest["example"] = "This is a Test";
But, you can take it even further with by having an indexer with multiple parameters. This method is effective for returning individual items within class instances contained within the indexer class or to perform special processing on a the returned value. For example, if you were returning a date as a string value, you could pass in formatting information in addition to the index value, as in this example…
public string this[int index, string formatValue]
{
get
{
return DateItems[index].ToString(formatValue);
}
}
As in other situations, you will need to make sure that each overloaded indexer has an unique signature.
I hope this article has covered the basics of indexers in C# for you
Finalize :
1.Finalize() is called by the runtime
2.Is a destructor, called by Garbage Collector when the object goes out of scope.
3.Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.
Dispose :
1.Dispose() is called by the user
2.Same purpose as finalize, to free unmanaged resources. However, implement this when you are writing a custom class, that will be used by other users.
3.Overriding Dispose() provides a way for the user code to free the unmanaged objects in your custom class.
stack
A stack is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in reverse order of their time of storage, i.e. the latest element stored is the next element to be retrieved. A stack is sometimes referred to as a Last-In-First-Out (LIFO) or First-In-Last-Out (FILO) structure. Elements previously stored cannot be retrieved until the latest element (usually referred to as the 'top' element) has been retrieved.
queue
A queue is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in order of their time of storage, i.e. the first element stored is the next element to be retrieved. A queue is sometimes referred to as a First-In-First-Out (FIFO) or Last-In-Last-Out (LILO) structure. Elements subsequently stored cannot be retrieved until the first element (usually referred to as the 'front' element) has been retrieved.
8 |
Immutable means that once initialized, the state of an object cannot change.
Mutable means it can.
For example - strings in .NET are immutable. Whenever you do an operation on a string (trims, upper casing, etc...) a new string gets created.
In practice, if you want to create an immutable type, you only allow getters on it and do not allow any state changes (so any private field cannot change once the constructor finished running).
|
No comments:
Post a Comment