Wednesday, December 22, 2010

Associative Commutative and Distributive Laws

Associative Commutative and Distributive Laws

Tuesday, December 21, 2010

Generics in Depth

Collections and Dictionaries


Download Source Code here

The System.Collections and System.Collections.Specialized namespaces contain a number
of classes to meet varying requirements for storing groups of related objects.



Collections
A collection is any class that allows for gathering items into lists and for iterating
through those items. The .NET Framework includes the following collection classes:
 ArrayList A simple collection that can store any type of object. ArrayList
instances expand to any required capacity.
Queue A first-in, first-out (FIFO) collection. You might use a Queue on a messaging
server to store messages temporarily before processing or to track customer orders
that need to be processed on a first-come, first-serve basis.
 Stack A last-in, first-out (LIFO) collection. You might use a Stack to track
changes so that the most recent change can be undone.
StringCollection Like ArrayList, except values are strongly typed as strings, and
StringCollection does not support sorting.
BitArray A collection of boolean values.

ArrayList

Use the ArrayList class (in the System.Collections namespace) to add objects that can
be accessed directly using a zero-based index or accessed in a series using a foreach
loop. The capacity of an ArrayList expands as required. The following example shows
how to use the ArrayList.Add method to add different types of objects to a single array,
and then access each object using a foreach loop:

' VB
Dim al As New ArrayList()
al.Add("Hello")
al.Add("World")
al.Add(5)
al.Add(New FileStream("delemete", FileMode.Create))
Console.WriteLine("The array has " + al.Count.ToString + " items:")
For Each s As Object In al
Console.WriteLine(s.ToString())
Next

// C#
ArrayList al = new ArrayList();
al.Add("Hello");
al.Add("World");
al.Add(5);
al.Add(new FileStream("delemete", FileMode.Create));
Console.WriteLine("The array has " + al.Count + " items:");
foreach (object s in al)
Console.WriteLine(s.ToString());

This console application displays the following:

The array has 4 items:
Hello
World
5
System.IO.FileStream

In practice, you generally add items of a single type to an ArrayList. This allows you to
call the Sort method to sort the objects using their IComparable implementation. You
can also use the Remove method to remove an object you previously added and use
the Insert method to add an element at the specified location in the zero-based index.
The following code sample demonstrates this:

' VB
Dim al As New ArrayList()
al.Add("Hello")
al.Add("World")
al.Add("this")
al.Add("is")
al.Add("a")
al.Add("test")
al.Remove("test")
al.Insert(4, "not")
al.Sort()
For Each s As Object In al
Console.WriteLine(s.ToString())
Next

// C#
ArrayList al = new ArrayList();
al.Add("Hello");
al.Add("World");
al.Add("this");
al.Add("is");
al.Add("a");
al.Add("test");
al.Remove("test");
al.Insert(4, "not");
al.Sort();
foreach (object s in al)
Console.WriteLine(s.ToString());

This code sample results in the following display. Notice that the items are sorted
alphabetically (using the string IComparable implementation) and “test” has been
removed:

A
Hello
is
not
this
World

Queue and Stack

The Queue and Stack classes (in the System.Collections namespace) store objects that
can be retrieved and removed in a single step. Queue uses a FIFO sequence, while
Stack uses a LIFO sequence. The Queue class uses the Enqueue and Dequeue methods
to add and remove objects, while the Stack class uses Push and Pop. The following
code demonstrates the differences between the two classes:

' VB
Dim q As New Queue()
q.Enqueue("Hello")
q.Enqueue("world")
q.Enqueue("just testing")
Console.WriteLine("Queue demonstration:")
For i As Integer = 1 To 3
Console.WriteLine(q.Dequeue().ToString())
Next
Dim s As New Stack()
s.Push("Hello")
s.Push("world")
s.Push("just testing")
Console.WriteLine("Stack demonstration:")
For i As Integer = 1 To 3
Console.WriteLine(s.Pop().ToString())
Next

// C#
Queue q = new Queue();
q.Enqueue("Hello");
q.Enqueue("world");
q.Enqueue("just testing");
Console.WriteLine("Queue demonstration:");
for (int i = 1; i <= 3; i++)
Console.WriteLine(q.Dequeue().ToString());
Stack s = new Stack();
s.Push("Hello");
s.Push("world");
s.Push("just testing");
Console.WriteLine("Stack demonstration:");
for (int i = 1; i <= 3; i++)
Console.WriteLine(s.Pop().ToString());

The application produces the following output:

Queue demonstration:
Hello
world
just testing
Stack demonstration:
just testing
world
Hello

You can also use Queue.Peek and Stack.Peek to access an object without removing it
from the stack. Use Queue.Clear and Stack.Clear to remove all objects from the stack.

BitArray and BitVector32
BitArray is an array of boolean values, where each item in the array is either true or
false. While BitArray can grow to any size, BitVector32 (a structure) is limited to exactly
32 bits. If you need to store boolean values, use BitVector32 anytime you require 32 or
fewer items, and use BitArray for anything larger.

Dictionaries
Dictionaries map keys to values. For example, you might map an employee ID
number to the object that represents the employee, or you might map a product ID to
the object that represents the product. The .NET Framework includes the following
dictionary classes:
Hashtable A dictionary of name/value pairs that can be retrieved by name or
index
 SortedList A dictionary that is sorted automatically by the key
 StringDictionary A hashtable with name/value pairs implemented as strongly
typed strings
 ListDictionary A dictionary optimized for a small list of objects with fewer than
10 items
HybridDictionary A dictionary that uses a ListDictionary for storage when the
number of items is small and automatically switches to a Hashtable as the list grows
 NameValueCollection A dictionary of name/value pairs of strings that allows
retrieval by name or index

SortedList (in the System.Collections namespace) is a dictionary that consists of key/
value pairs. Both the key and the value can be any object. SortedList is sorted automatically
by the key. For example, the following code sample creates a SortedList instance
with three key/value pairs. It then displays the definitions for Queue, SortedList, and
Stack, in that order:

' VB
Dim sl As New SortedList()
sl.Add("Stack", "Represents a LIFO collection of objects.")
sl.Add("Queue", "Represents a FIFO collection of objects.")
sl.Add("SortedList", "Represents a collection of key/value pairs.")
For Each de As DictionaryEntry In sl
Console.WriteLine(de.Value)
Next

// C#
SortedList sl = new SortedList();
sl.Add("Stack", "Represents a LIFO collection of objects.");
sl.Add("Queue", "Represents a FIFO collection of objects.");
sl.Add("SortedList", "Represents a collection of key/value pairs.");
foreach (DictionaryEntry de in sl)
Console.WriteLine(de.Value);

Notice that SortedList is an array of DictionaryEntry objects. As the previous code sample
demonstrates, you can access the objects you originally added to the SortedList
using the DictionaryEntry.Value property. You can access the key using the Dictionary-
Entry.Key property.

You can also access values directly by accessing the SortedList as a collection. The following
code sample (which builds upon the previous code sample) displays the
definition for Queue twice. Queue is the first entry in the zero-based index because the
SortedList instance automatically sorted the keys alphabetically:

' VB
Console.WriteLine(sl("Queue"))
Console.WriteLine(sl.GetByIndex(0))
// C#
Console.WriteLine(sl["Queue"]);
Console.WriteLine(sl.GetByIndex(0));

The ListDictionary class (in the System.Collections.Specialized namespace) also
provides similar functionality, and is optimized to perform best with lists of fewer
than 10 items. HybridDictionary (also in the System.Collections.Specialized namespace)
provides the same performance as ListDictionary with small lists, but it scales better
when the list is expanded.
While SortedList can take an object of any type as its value (but only strings as keys),
the StringDictionary class (in the System.Collections.Specialized namespace) provides
similar functionality, without the automatic sorting, and requires both the keys and
the values to be strings.
NameValueCollection also provides similar functionality, but it allows you to use either
a string or an integer index for the key. In addition, you can store multiple string values
for a single key. The following code sample demonstrates this by displaying two
definitions for the terms stack and queue:

' VB
Dim sl As New NameValueCollection()
sl.Add("Stack", "Represents a LIFO collection of objects.")
sl.Add("Stack", "A pile of pancakes.")
sl.Add("Queue", "Represents a FIFO collection of objects.")
sl.Add("Queue", "In England, a line.")
sl.Add("SortedList", "Represents a collection of key/value pairs.")
For Each s As String In sl.GetValues(0)
Console.WriteLine(s)
Next
For Each s As String In sl.GetValues("Queue")
Console.WriteLine(s)
Next

// C#
NameValueCollection sl = new NameValueCollection();
sl.Add("Stack", "Represents a LIFO collection of objects.");
sl.Add("Stack", "A pile of pancakes.");
sl.Add("Queue", "Represents a FIFO collection of objects.");
sl.Add("Queue", "In England, a line.");
sl.Add("SortedList", "Represents a collection of key/value pairs.");
foreach (string s in sl.GetValues(0))
Console.WriteLine(s);
foreach (string s in sl.GetValues("Queue"))
Console.WriteLine(s);

Generic Collections :
Collections like ArrayList, Queue, and Stack use the Object base class to allow them to
work with any type. However, accessing the collection usually requires you to cast
from the base Object type to the correct type. Not only does this make development
tedious and more error-prone, but it hurts performance

Using generics, you can create strongly typed collections for any class, including custom
classes. This simplifies development within the Visual Studio editor, helps ensure
appropriate use of types, and can improve performance by reducing the need to cast
Generics Overview
Many of the collections in the .NET Framework support adding objects of any type,
such as ArrayList. Others, like StringCollection, are strongly typed. Strongly typed
classes are easier to develop with because the Visual Studio designer can list and
validate members automatically. In addition, you do not need to cast classes to more
specific types, and you are protected from casting to an inappropriate type.
Generics provide many of the benefits of strongly typed collections, but they can work
with any type that meets the requirements. In addition, using generics can improve performance
by reducing the number of casting operations required. Table 4-1 lists the most
useful generic collection classes and the corresponding nongeneric collection type.

Generic Collection Classes
List<T> ArrayList, StringCollection
Dictionary<T,U> Hashtable, ListDictionary, HybridDictionary,OrderedDictionary, NameValueCollection, StringDictionary
Queue<T> Queue
Stack<T> Stack
SortedList<T,U> SortedList
Collection<T> CollectionBase
ReadOnlyCollection<T> ReadOnlyCollectionBase

Generic SortedList<T,U> Collection
The following code sample creates a generic SortedList<T,U> using strings as the keys
and integers as the values. As you type this code into the Visual Studio editor, notice
that it prompts you to enter string and integer parameters for the SortedList.Add
method as if SortedList.Add were strongly typed:
' VB
Dim sl As New SortedList(Of String, Integer)()
sl.Add("One", 1)
sl.Add("Two", 2)
sl.Add("Three", 3)
For Each i As Integer In sl.Values
Console.WriteLine(i.ToString())
Next

// C#
SortedList<string, int> sl = new SortedList<string,int>();
sl.Add("One", 1);
sl.Add("Two", 2);
sl.Add("Three", 3);
foreach (int i in sl.Values)
Console.WriteLine(i.ToString());

In Visual Basic, specify the type arguments for the generic class using the constructor
parameters by specifying the Of keyword. In C#, specify the type arguments using
angle brackets before the constructor parameters.

Using Generics with Custom Classes

You can use generics with custom classes as well. Consider the following class declaration:
' VB
Public Class person
Private firstName As String
Private lastName As String
Public Sub New(ByVal _firstName As String, ByVal _lastName As String)
firstName = _firstName
lastName = _lastName
End Sub
Public Overloads Overrides Function ToString() As String
Return firstName + " " + lastName
End Function
End Class

// C#
public class person
{
string firstName;
string lastName;
public person(string _firstName, string _lastName)
{
firstName = _firstName;
lastName = _lastName;
}
override public string ToString()
{
return firstName + " " + lastName;
}
}

You can use the SortedList<T,U> generic class with the custom class exactly as you
would use it with an integer, as the following code sample demonstrates:
' VB
Dim sl As New SortedList(Of String, person)()
sl.Add("One", New person("Mark", "Hanson"))
sl.Add("Two", New person("Kim", "Akers"))
sl.Add("Three", New person("Zsolt", "Ambrus"))
For Each p As person In sl.Values
Console.WriteLine(p.ToString())
Next

// C#
SortedList<string, person> sl = new SortedList<string,person>();
sl.Add("One", new person("Mark", "Hanson"));
sl.Add("Two", new person("Kim", "Akers"));
sl.Add("Three", new person("Zsolt", "Ambrus"));
foreach (person p in sl.Values)
Console.WriteLine(p.ToString());
Generic Queue<T> and Stack<T> Collections
Similarly, the following code sample demonstrates using the generic versions of both
Queue and Stack with the person class:

' VB
Dim q As New Queue(Of person)()
q.Enqueue(New person("Mark", "Hanson"))
q.Enqueue(New person("Kim", "Akers"))
q.Enqueue(New person("Zsolt", "Ambrus"))
Console.WriteLine("Queue demonstration:")
For i As Integer = 1 To 3
Console.WriteLine(q.Dequeue().ToString())
Next
Dim s As New Stack(Of person)()
s.Push(New person("Mark", "Hanson"))
s.Push(New person("Kim", "Akers"))
s.Push(New person("Zsolt", "Ambrus"))
Console.WriteLine("Stack demonstration:")
For i As Integer = 1 To 3
Console.WriteLine(s.Pop().ToString())
Next

// C#
Queue<person> q = new Queue<person>();
q.Enqueue(new person("Mark", "Hanson"));
q.Enqueue(new person("Kim", "Akers"));
q.Enqueue(new person("Zsolt", "Ambrus"));
Console.WriteLine("Queue demonstration:");
for (int i = 1; i <= 3; i++)
Console.WriteLine(q.Dequeue().ToString());
Stack<person> s = new Stack<person>();
s.Push(new person("Mark", "Hanson"));
s.Push(new person("Kim", "Akers"));
s.Push(new person("Zsolt", "Ambrus"));
Console.WriteLine("Stack demonstration:");
for (int i = 1; i <= 3; i++)
Console.WriteLine(s.Pop().ToString());

Generic List<T> Collection
Some aspects of generic collections might require specific interfaces to be implemented
by the type you specify. For example, calling List.Sort without any parameters
requires the type to support the IComparable interface. The following code sample
expands the person class to support the IComparable interface and the required
CompareTo method and allows it to be sorted in a List<T> generic collection using the
person’s first and last name:
' VB
Public Class person
Implements IComparable
Private firstName As String
Private lastName As String
Public Function CompareTo(ByVal obj As Object) _
As Integer Implements System.IComparable.CompareTo
Dim otherPerson As person = DirectCast(obj, person)
If Me.lastName <> otherPerson.lastName Then
Return Me.lastName.CompareTo(otherPerson.lastName)
Else
Return Me.firstName.CompareTo(otherPerson.firstName)
End If
End Function
Public Sub New(ByVal _firstName As String, ByVal _lastName As String)
firstName = _firstName
lastName = _lastName
End Sub
Public Overrides Function ToString() As String
Return firstName + " " + lastName
End Function
End Class

// C#
public class person : IComparable
{
string firstName;
string lastName;
public int CompareTo(object obj)
{
person otherPerson = (person)obj;
if (this.lastName != otherPerson.lastName)
return this.lastName.CompareTo(otherPerson.lastName);
else
return this.firstName.CompareTo(otherPerson.firstName);
}
public person(string _firstName, string _lastName)
{
firstName = _firstName;
lastName = _lastName;
}
override public string ToString()
{
return firstName + " " + lastName;
}
}
After adding the IComparable interface to the person class, you now can sort it in a
generic List<T>, as the following code sample demonstrates:
' VB
Dim l As New List(Of person)()
l.Add(New person("Mark", "Hanson"))
l.Add(New person("Kim", "Akers"))
l.Add(New person("Zsolt", "Ambrus"))
l.Sort()
For Each p As person In l
Console.WriteLine(p.ToString())
Next
// C#
List<person> l = new List<person>();
l.Add(new person("Mark", "Hanson"));
l.Add(new person("Kim", "Akers"));
l.Add(new person("Zsolt", "Ambrus"));
l.Sort();
foreach (person p in l)
Console.WriteLine(p.ToString());

With the IComparable interface implemented, you could also use the person class as
the key in a generic SortedList<T,U> or SortedDictionary<T,U> class.

Monday, December 20, 2010

Input/Output

Working with the File System
Enumerating Drives:
To list all the drives connected to a computer, use the static DriveInfo.GetDrives
method (in the System.IO namespace) to retrieve a collection of DriveInfo objects.
example, the following loop outputs a list of all drives to the console:

' VB
For Each di As DriveInfo In DriveInfo.GetDrives()
Console.WriteLine(" {0} ({1})", di.Name, di.DriveType)
Next

// C#
foreach (DriveInfo di in DriveInfo.GetDrives())
Console.WriteLine(" {0} ({1})", di.Name, di.DriveType);

DriveInfo has the following properties:
1. AvailableFreeSpace Indicates the amount of available free space on a drive
 2.DriveFormat Gets the name of the file system, such as NTFS or FAT32
3. DriveType Gets the drive type
4. IsReady Indicates whether a drive is ready
5. Name Gets the name of a drive
6. RootDirectory Gets the root directory of a drive
7. TotalFreeSpace Gets the total amount of free space available on a drive
8. TotalSize Gets the total size of storage space on a drive
9. VolumeLabel Gets or sets the volume label of a drive

Managing Files and Folders

The .NET Framework provides classes that you can use to browse files and folders, create
new folders, and manage files

Browsing Folders

You can use the DirectoryInfo class to browse folders and files. First, create an instance
of DirectoryInfo by specifying the folder to browse.
Then, call the DirectoryInfo.Get-Directories or DirectoryInfo.GetFiles method.
The following example displays the files and folders in the C:\Windows\folder.
' VB

Dim dir As New DirectoryInfo("C:\Windows")
Console.WriteLine("Folders:")

For Each dirInfo As DirectoryInfo In dir.GetDirectories()
Console.WriteLine(dirInfo.Name)
Next

Console.WriteLine("Files:")

For Each fi As FileInfo In dir.GetFiles()

Console.WriteLine(fi.Name)
Next

// C#
DirectoryInfo dir = new DirectoryInfo(@"C:\Windows");

Console.WriteLine("Folders:");

foreach (DirectoryInfo dirInfo in dir.GetDirectories())

Console.WriteLine(dirInfo.Name);
Console.WriteLine("\nFiles:");

foreach (FileInfo fi in dir.GetFiles())
Console.WriteLine(fi.Name);

Creating Folders

To create folders, create an instance of DirectoryInfo and then call the DirectoryInfo
.Create method. You can check the boolean DirectoryInfo.Exists property to determine
if a folder already exists. The following sample checks for the existence of a folder and
creates it if it doesn’t already exist, although the Common Language Runtime (CLR)
does not throw an exception if you attempt to create a folder that already exists.

' VB

File.CreateText("mynewfile.txt")
File.Copy("mynewfile.txt", "newfile2.txt")
File.Move("newfile2.txt", "newfile3.txt")

// C#

File.CreateText("mynewfile.txt");
File.Copy("mynewfile.txt", "newfile2.txt");
File.Move("newfile2.txt", "newfile3.txt");

Alternatively, you can create an instance of the FileInfo class representing the file and
call the Create, CreateText, CopyTo, MoveTo, and Delete methods. The following code
performs the same functions as the previous sample:

' VB

Dim fi As New FileInfo("mynewfile.txt")
fi.CreateText()
fi.CopyTo("newfile2.txt")
Dim fi2 As New FileInfo("newfile2.txt")
fi2.MoveTo("newfile3.txt")

// C#
FileInfo fi = new FileInfo("mynewfile.txt");
fi.CreateText();
fi.CopyTo("newfile2.txt");
FileInfo fi2 = new FileInfo("newfile2.txt");
fi2.MoveTo("newfile3.txt");
To delete a file, create an instance of the FileInfo class and then call FileInfo.Delete.

Sunday, December 19, 2010

Generics in .NET

Download Generics Source Code 

Generics  are part of the type system of the CLR that allow you to define a type while leaving

some details unspecified. Instead of specifying the types of certain parameters or
members, you can allow code that uses your generic class to specify those types. This
allows consumer code to tailor your class to meet specific needs of the consumer code.

The .NET Framework includes several generic classes in the
System.Collections.Generic
namespace, including
work similarly to their nongeneric counterparts in
improved performance and type safety.

Why Use Generics?
Generics offer two significant advantages over using the
object class:
��
to and from the
and then attempt to cast that
the error. Instead, the application throws an exception at run time. Using generics
allows the compiler to catch this type of bug before your program runs. In
addition, you can specify constraints to limit the classes used in a generic,
enabling the compiler to detect an incompatible type being called for by consumer
code.
Reduced run-time errors The compiler cannot detect type errors when you castObject class. For example, if you cast a string to an Object classObject to an integer, the compiler does not catch
��
doesn’t require casting or boxing, so run-time performance improves

How to Create a Generic Type
First, examine the following classes. Classes
tasks, but
Obj and Gen perform exactly the sameObj uses the Object class to enable any type to be stored in its field, while
Gen
uses generics:
' VB
Class Obj

Public V1 As Object
Public V2 As Object
    Public Sub New(ByVal _V1 As Object, ByVal _V2 As Object)
          V1 = _V1
           V2 = _V2
    End Sub
End Class

Class Gen(Of T, U)

    Public V1 As T
    Public V2 As U
    Public Sub New(ByVal _V1 As T, ByVal _V2 As U)
        V1 = _V1
        V2 = _V2
    End Sub
End Class

// C#
class Obj
{
       public Object t;
        public Object u;
        public Obj(Object _t, Object _u)
        {
            t = _t;
            u = _u;
         }
}

class Gen<T, U>
{
           public T t;
           public U u;
           public Gen(T _t, U _u)
          {
               t = _t;
               u = _u;
           }
}

As you can see, the
field members of type
Obj class has two members of type Object. The Gen class has twoT and U. The consuming code determines the types for T and
U
. Depending on how the consuming code uses the Gen class, T and U could be a
string
There is a significant limitation to creating a generic class (without constraints, as discussed
in the section “How to Use Constraints,” later in this chapter): Generic code is
valid only if it compiles for every possible constructed instance of the generic,
whether an
of the base
, an int, a custom class, or any combination thereof.Int, a string, or any other class. Essentially, you are limited to the capabilitiesObject class when writing generic code. Therefore, you could call the
ToString
or the
because the consuming code declares a specific type for the generic.

How to Consume a Generic Type
When you consume a generic type, you must specify the types for any generics used.
Consider the following Console application code, which uses the
Gen and Obj classes:
' VB
' Add two Strings using the Obj class
Dim oa As Obj = New Obj("Hello, ", "World!")
Console.WriteLine(CType(oa.V1, String) + CType(oa.V2, String))

' Add two Strings using the Gen class
Dim ga As New Gen(Of String, String)("Hello, ", "World!")
Console.WriteLine(ga.V1 + ga.V2)

' Add a Double and an Integer using the Obj class
Dim ob As Obj = New Obj(10.125, 2005)
Console.WriteLine(CType(ob.V1, Double) + CType(ob.V2, Integer))

' Add a Double and an Integer using the Gen class
Dim gb As New Gen(Of Double, Integer)(10.125, 2005)
Console.WriteLine(gb.V1 + gb.V2)

// C#

// Add two strings using the Obj class
Obj oa = new Obj("Hello, ", "World!");
Console.WriteLine((string)oa.t + (string)oa.u);

// Add two strings using the Gen class
Gen<string, string> ga = new Gen<string, string>("Hello, ", "World!");
Console.WriteLine(ga.t + ga.u);

// Add a double and an int using the Obj class
Obj ob = new Obj(10.125, 2005);
Console.WriteLine((double)ob.t + (int)ob.u);

// Add a double and an int using the Gen class
Gen<double, int> gb = new Gen<double, int>(10.125, 2005);
Console.WriteLine(gb.t + gb.u);
If you run that code in a Console application, the
the same results. However, the code that uses the
because it does not require boxing and unboxing to and from the
and unboxing are discussed in the section “What Are Boxing and Unboxing?” later in
this chapter.) In addition, developers would have a much easier time using the
Obj and Gen classes produce exactlyGen class actually works fasterObject class. (BoxingGen
class. First, developers would not have to cast manually from the
appropriate types. Second, type errors would be caught at compile time rather than at
run time. To demonstrate that benefit, consider the following code, which contains an
error (shown in bold):
Object class to the
' VB
' Add a Double and an Integer using the Gen class

Dim gb As New Gen(Of Double, Integer)(10.125, 2005)
Console.WriteLine(gb.V1 + gb.V2)

' Add a Double and an Integer using the Obj class

Dim ob As Obj = New Obj(10.125, 2005)
Console.WriteLine(CType(ob.V1,
 
// C#

// Add a double and an int using the Gen class

Gen<double, int> gc = new Gen<double, int>(10.125, 2005);
Console.WriteLine(gc.t + gc.u);

// Add a double and an int using the Obj class
Obj oc = new Obj(10.125, 2005);
Console.WriteLine((int)oc.t + (int)oc.u);
Integer) + CType(ob.V2, Integer))
Real time example:

Class1.cs
=======
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace
{

{



{
t=_t;
u= _u;
}
}
WebApplication1public class Gen<T,U>public T t;public U u;public void gen(T _t,U _u)public class Obj{



{
a = _a;
b = _b;
}
}
public object a;public object b;public void obj(object _a, object _b)public class compareGen<T> where T : IComparable{



{
t1 = _t1;
t2 = _t2;
}

{

{

}
public T t1;public T t2;public void compGen(T _t1, T _t2)public T Max()if (t2.CompareTo(t1) < 0)return t1;else{

}
}
}
}
return t2;


Default.aspx.cs:
============
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace
{
WebApplication1public partial class _Default : System.Web.UI.Page{

{

ob.obj(
Response.Write((

he.gen(
Response.Write(

ri.gen(
Response.Write(
}

{

compare.t1 =
compare.t2 =
TextBox3.Text = compare.Max().ToString();
}

{

strin.t1 = TextBox1.Text;
strin.t2 = TextBox3.Text;
TextBox3.Text = strin.Max();
}
}
}
protected void Page_Load(object sender, EventArgs e)Obj ob = new Obj();"Hello", "World!");string)ob.a + (string)ob.b);Gen<string, string> he = new Gen<string, string>();"Myworld", "Hello");"\n"+he.u + he.t);Gen<string, int> ri = new Gen<string, int>();"My number is: ", 420);"\n"+ri.t + ri.u);protected void Button1_Click(object sender, EventArgs e)compareGen<int> compare = new compareGen<int>();Convert.ToInt32(TextBox1.Text);Convert.ToInt32(TextBox2.Text);protected void Button2_Click(object sender, EventArgs e)compareGen<string> strin = new compareGen<string>();

Output:
HelloWorld!
HelloMyworld
My number is: 420
Comparing Two numbers by using IComparable interface in Gerneric Class
 
How to Use Constraints
Generics would be extremely limited if you could only write code that would compile
for any class, because you would be limited to the capabilities of the base
To overcome this limitation, use constraints to place requirements on the types that
consuming code can substitute for your generic parameter.
Generics support four types of constraints:
��
generic type argument

Interface Allows only types that implement specific interfaces to be used as a
��
be used as a generic type argument

Base class Allows only types that match or inherit from a specific base class to
��
to implement a parameterless constructor

Constructor Requires types that are used as the type argument for your generic
��
your generic to be either a reference or a value type
Reference or value type Requires types that are used as the type argument for
Reference or value type Requires types that are used as the type argument forAs clause in Visual Basic or the where clause in C# to apply a constraint to aIComparable interface:
' VB
Class CompGen(Of T As IComparable)
Public t1 As T
Public t2 As T
Public Sub New(ByVal _t1 As T, ByVal _t2 As T)
t1 = _t1
t2 = _t2
End Sub
Public Function Max() As T
If t2.CompareTo(t1) < 0 Then
Return t1
Else
Return t2
End If
End Function
End Class
// C#
class CompGen<T>
where T : IComparable
{
public T t1;
public T t2;
public CompGen(T _t1, T _t2)
{
t1 = _t1;
t2 = _t2;
}
public T Max()
{
if (t2.CompareTo(t1) < 0)
return t1;
else
return t2;
}
}
The preceding class compiles correctly. However, if you remove the As/where clause,
the compiler returns an error indicating that generic type T does not contain
a definition for CompareTo. By constraining the generic to classes that implement
IComparable
 , you guarantee that the CompareTo method will always be available.
public object a;public object b;public void obj(object _a, object _b)
or GetHashCode method within your class, but you could not use the + operator> operator. These same restrictions do not apply to the consuming code
Improved performance Casting requires boxing and unboxing, which steals processor time and slows performance. Using generics
Dictionary, Queue, SortedDictionary, and SortedList. These classesSystem.Collections, but they offer

Thursday, December 16, 2010

JavaScript Reference Site

http://javascript.gakaa.com/

JavaScript Basics

javascript to check opened window is closed or not

var win = window.open('http://www.yahoo.com');
alert(win.closed);

return boolean

javascript view webpages' HTML source

<input type="button" value="View" onclick="window.location = 'view-source:'+ 'http://www.royh.cn/'" />
Firefox only?

javascript get user selected text

IE version:
document.selection.createRange().duplicate().text;

Firefox version:
document.getSelection();

For all browser selected():
<input type="button" onclick="alert(selected())" />
<script type="text/javascript">
    function selected(){
        if (document.selection) return document.selection.createRange().duplicate().text;
        else return document.getSelection();
    }
</script>


 

Clipboard(Copy and Paste) in ASP.NET

javascript clipboardData Description

 

The clipboardData object (accessible as a property of a window or frame object) is a temporary container that scripts in IE 5 and later for Windows can use to transfer text data, particularly during script-controlled operations that simulate cutting, copying, and pasting, or that control dragging. Your script controls what data is stored in the clipboardData object, such as just the text of an element, an element's entire HTML, or the URL of an image. For example, a page for children could display simple icon images of several different kinds of animals. If the user starts dragging the dog icon, the script initiated by the img element's onDragStart event handler stores a custom attribute value of that element (perhaps the URL of a pretty dog photo) into the clipboardData object. When the user drops the icon into the designated area, the onDrop event handler's function reads the clipboardData object's data and loads the photo image into position on the page.
Data stored in this object survives navigation to other pages within the same domain and protocol. Therefore, you can use it to pass text data (including arrays that have been converted to strings by the Array.join( ) method) from one page to another without using cookies or location.search strings. But this is not the system clipboard (for security reasons).
For more information on transferring data via this object and the event.dataTransfer object, visit http://msdn.microsoft.com/workshop/author/datatransfer/overview.asp.
HTML Equivalent
None.
Object Model Reference
[window.]clipboardData
Object-Specific Properties
dropEffecteffectAllowed
Object-Specific Methods
clearData( )getData( )setData( )
Object-Specific Event Handler Properties
None.

 


javascript clipboardData setData( )

 

setData(dataFormat, stringData)
  
Stores string data in the clipboardData object. Returns Boolean true if the assignment is successful
Parameters

dataFormat
A string specifying the format for the data to be read. Earlier plans to allow multiple data types appear to have fallen through. As of IE 6, the only reliable format is Text. While the method accepts URL as a format, reading a set value in that format is not successful.
stringData
Any string value, including strings that contain HTML tags.
Returned Value
Boolean value: true | false.

javascript clipboardData getData( )

getData(dataFormat)
  
Returns a copy of data from the clipboardData object. The clipboardData contents remain intact for subsequent reading in other script statements.
Parameters

dataFormat
A string specifying the format for the data to be read. Earlier plans to allow multiple data types appear to have fallen through. As of IE 6, the only reliable format is Text.
Returned Value
String.

javascript clipboardData clearData( )

clearData([dataFormat])
  
Removes data from the clipboardData object.
Parameters

dataFormat
An optional string specifying a single format for the data to be removed. Earlier plans to allow multiple data types appear to have fallen through. As of IE 6, the only reliable format is Text. Omitting the parameter removes all data of all types.
Returned Value
None.

javascript clipboardData dropEffect, effectAllowed

These two properties belong to the clipboardData object by inheritance from the dataTransfer object, to which they genuinely apply. Ignore these properties for the clipboardData object.

 Example :

function SaveClipboardData(con) //Copy Clipboard Data from control... con is the control
        {
           var data = con.innerText ? con.innerText : con.textContent;
           window.clipboardData.setData("Text", data);
           alert(data);
        }
        function CopyToTextBox() //Inserting ClipBoard Data into TextBox
        {
            var data = window.clipboardData.getData("Text");
            alert("Clipboard Paste = \n\n" + data);
            var txt = document.getElementById('<%= txtEmailBody.ClientID %>');//TextBox
            var mosPos = 0;
            if (document.selection)
            {
                txt.focus();
                var range = document.selection.createRange();
                range.text = data;
            }
            else if (txt.selectionStart != null)
            {
                mosPos = txt.selectionStart;
                var strFirst = txt.value.substring(0, mosPos);
                var strLast = txt.value.substring(mosPos);
                if (txt.value == "")
                {
                    txt.value = data;
                    txt.focus();
                    con.className = "variable_selected";
                }
                else
                {
                    txt.value = strFirst + data + strLast;
                    txt.focus();
                    con.className = "variable_selected";
                }
            }
        }