Category Archives: C#

Chapter 11 – Files and Serialization

SAMS CSHARP 4.0 (Page 194)

* Create, Read and Write Files

Two modes to access files: TEXT and BINARY.

In Text mode, raw contents are converted to System.Text.

Chapter 10 — Collections

SAMS CSHARP 4.0 (Page 172) 03/03/2011, 10:43 PM

* Initialize a Connection

List<int> list = new List<int>() {1, 2, 3, 4,5 };

Dictionary<int, string> dict = new Dictionary<int, string> )() {
{1, “one”},
{2, “two”}
};

* Iterate over a collection independently of its implementation

You want to access all of a collection’s objects independently from how the collection is implemented.

Rather than looping using index or key, use FOREACH.

Chapter 9 – Generics

SAMS CSHARP 4.0 (Page 156)

* Create a Generic List

user List<T> to create a list of T type objects.

class Person {
public string Name {get; set;}
public string Address {get; set; }
};

static void Main(string[] args) {
List<Person> people = new List<Person>();
// declare a list of Person-typed objects
people.Add(new Person() {Name=”Bruce”, Address=”4007 BB Lane”});

Person p = people[0]; . // No casting is needed
}

*** Use Generics instead of ArrayList can avoid boxing and unboxing.

* Create Generic Method

You need a method that can be called to perform the same work on different types of arguments.

define a generic method:

private static void Sawsp<T> (ref T a, ref T b) {
T temp = a;
a = b;
b = temp;
}

to call this method:

Swap<int> (ref aInt, ref bInt); or
Swap<string> (ref aString, ref bString); or

* Create a Generic Interface

//declare generic interface of T

interface IUnique<T> {
T Id { get; }
}

//implement interface with specific types
class MyObject : IUnique<int>
{
private int _id;
//implementation of interface’s method
public int Id
{
get { return _id; }
}
}

class MyOtherObject : IUnique<string> {
private string _id;
public string Id
{
get { return _id; }
}
}

TUPLES – New in C# 4

Group multiple values (can be different type) together and use them together.

Example 1:

example 2: (practical use)