.NET

Conversions

Epoch (UNIX) Time Conversion

static public class EpochTime
    {
        static public int GetCurrentEpochTime()
        {
            TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
            int currentEpochTime = (int)t.TotalSeconds;
            return currentEpochTime;
        }
        static public int ConvertToEpochTime(DateTime localDateTime)
        {
            TimeSpan t = (localDateTime.ToUniversalTime() - new DateTime(1970, 1, 1));
            int epochTime = (int)t.TotalSeconds;
            return epochTime;
        }
        static public DateTime ConvertToLocalDateTime(int epochTime)
        {
            DateTime dateTime1970 = new DateTime(1970, 1, 1);
            DateTime epochDateTime = dateTime1970.AddSeconds(epochTime);
            return epochDateTime.ToLocalTime();
        }
        static public DateTime ConvertToUtcDateTime(int epochTime)
        {
            DateTime dateTime1970 = new DateTime(1970, 1, 1);
            DateTime epochDateTime = dateTime1970.AddSeconds(epochTime);
            return epochDateTime;
        }
    }

Searching

How to check whether an element exists in a list

using System.Collections.Generic;
// List of Value Types
List list = new List(new int[] { 1, 2, 3 });
bool found = list.Contains(1);  // found == TRUE
found = list.Contains(4);       // found == FALSE
// List of Reference Types - Does not work as expected
class SomeClass
{
 string m_Id;
 private SomeClass() { }
 public SomeClass(string id)
 {
  this.m_Id = id;
 }
}
List list =
  new List(new SomeClass[] { new SomeClass("100") });
SomeClass lookupValue = new SomeClass("100");
bool found = list.Contains(lookupValue);      // found == FALSE
// Contains() method does NOT work as expected because Contains()
// does a comparison of lookupValue object with the elements in
// the list by Reference, not by internal values represented by
// the object (m_Id in our example).
// To correct this behavior we will need to override Equals()
// method of our class
// List of Reference Types - Works as expected after override of Equals()
class SomeClass
{
 string m_Id;
 private SomeClass() { }
 public SomeClass(string id)
 {
  this.m_Id = id;
 }
 public override bool Equals(object obj)
 {
  if (obj == null || !(obj is SomeClass))
   return false;
  return this.Equals(obj as SomeClass);
 }
 public bool Equals(SomeClass someClass)
 {
  return someClass.m_Id == this.m_Id;
 }
 // When Equals is overridden, it is also recommended that
 // GetHashCode() be overridden.
 // GetHashCode() provides a hash value for proper handling
 // of an object contained in data structures such as a Dictionary
 public override int GetHashCode()
 {
  return Int32.Parse(this.m_Id);
 }
}
// Contains() works as expected now
List list =
  new List(new SomeClass[] { new SomeClass("100") });
SomeClass lookupValue = new SomeClass("100");
bool found = list.Contains(lookupValue);      // found == TRUE
SomeClass lookupValue2 = new SomeClass("200");
found = list.Contains(lookupValue2);          // found == FALSE


Searching text using Regular Expressions

string stringToSearch = @"Name=""John""\nName = ""Tim""";
string nameGroup = "namegroup";
const string regExPattern =
  String.Format( @"\s*Name\s*=\s*\""(?<{0}>.*)\""\s*",
     nameGroup);
Regex regex = new Regex(regExPattern,
  RegexOptions.IgnoreCase | RegexOptions.Multiline);
MatchCollection matches = regex.Matches(stringToSearch);
   
if (matches != null && matches.Count > 0)
{
  foreach (Match match in matches)
  {
    if (match.Groups[nameGroup] != null)
    {
       Group group = match.Groups[nameGroup];
       foreach (Capture capture in group.Captures)
       {
          // capture.Value
       }
    }
  }
}

// parsing user id out of an oracle connection string
// "user id=user1;password=userpass;data source=tnsname"
string userIdGroup = "UserIdGroup";
userId = string.Empty;
string expr = String.Format(@"(user\s+id)\s*=\s*(?<{0}>(\w+))", userIdGroup);
Regex regex = new Regex(expr, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(url);
if (matches != null && matches.Count > 0)
{
foreach (Match match in matches)
{
    if (match.Groups[userIdGroup] != null)
    {
       Group group = match.Groups[userIdGroup];
       foreach (Capture capture in group.Captures)
      {
         userId = capture.Value;
         return;
      }
    }
}
}


 // split based on RegEx
 // "a@bc.com";
 //  "a@bc.com, de@f.com"
 // "a@bc.com; de@f.com"
 // "a@bc.com; de@f.com,gl@m.com;z.yz.com"
 static public List<string> SplitEmailAddressList(string listStr)
{
    string expr = @"\s*;\s*|\s*,\s*";
    Regex regex = new Regex(expr);
    return new List<string>(regex.Split(listStr));
}

Sorting

How to sort a list of objects using a Comparison Delegate

using System.Collections.Generic;
using System.Diagnostics;
Coordinate c1 = new Coordinate(4, 2);
Coordinate c2 = new Coordinate(2, 1);
Coordinate c3 = new Coordinate(-2, 8);
List list = new List();
list.Add(c1);
list.Add(c2);
list.Add(c3);
// Coordinate.Compare is method we define to do the comparison
list.Sort(new Comparison(Coordinate.Compare));
Debug.Assert(list[0] == c3);
Debug.Assert(list[1] == c2);
Debug.Assert(list[2] == c1);
// This is how our class is defined
public class Coordinate
{
  int m_x;
  int m_y;
  private Coordinate()
  {
  }
  public Coordinate(int x, int y)
  {
    this.m_x = x;
    this.m_y = y;
  }
  public override bool Equals(object obj)
  {
    if (obj == null || !(obj is Coordinate))
      return false;
    return (obj as Coordinate).m_x == this.m_x &&
          (obj as Coordinate).m_y == this.m_y;
  }
  // Sort coordinates with the left-most coordinates first
  static public int Compare(Coordinate a, Coordinate b)
  {
    if (a.m_x < b.m_x)
      return -1;
    else if (a.m_x > b.m_x)
      return 1;
    else
      return 0;
  }
}

How to sort a list of objects using an IComparer Class

using System.Collections.Generic;
// Create a list of persons (i.e. list of custom class objects)
List<Person> personList = new List<Person>();
Person jane = new Person("Jane Doe", new DateTime(1983, 7, 4));
Person bill = new Person("Bill Smith", new DateTime(1980, 12, 25));
personList.AddRange(new Person[] {jane, bill});
// personList is sorted by birthdate, in ascending order
// See PersonBirthDateComparer below
personList.Sort(new PersonBirthDateComparer(false));
// personList is sorted by birthdate, in descending order
personList.Sort(new PersonBirthDateComparer(true));
// This is how our custom Person class is defined
public class Person
{
  readonly string m_Name;
  readonly DateTime m_Birthdate;
  private Person(){}
  public Person(string name, DateTime birthDate)
  {
    this.m_Name = name;
    this.m_Birthdate = birthDate;
  }
  public string Name
  {
    get { return m_Name; }
  }
  public DateTime Birthdate
  {
    get { return m_Birthdate; }
  }
}
// This class defines the sorting logic for our custom class (Person)
public class PersonBirthDateComparer : IComparer<Person>
{
  readonly bool m_DescendingOrder = false;
  public PersonBirthDateComparer(bool descendingOrder)
  {
    this.m_DescendingOrder = descendingOrder;
  }
  public int Compare(Person x, Person y)
  {
    int compareResult = DateTime.Compare(x.Birthdate, y.Birthdate);
    if (this.m_DescendingOrder)
    {
      if (compareResult < 1)
        compareResult = 1;
      else if (compareResult > 1)
        compareResult = -1;
    }
    return compareResult;
  }
}

String Operations

How to build large strings

// StringBuilder class is a more efficient way to build strings
// than building a string using the .NET String class
StringBuilder sb = new StringBuilder();
foreach (string address in addressList)
{
  sb.AppendLine(address);
}

How to check if a string starts or ends with a certain string

string s1 = "abc";
bool ret = s1.StartsWith("a");
ret = s1.EndsWith("c");

How to compare strings

string s1 = "abc";
string s2 = "ABC";
// result == -1 meaning s1 is less than s2
int result = String.Compare(s1, s2);
// result == 1 meaning s2 is greater than s1
result = String.Compare(s2, s1);
// compare s1 and s2 in case-insensitive manner
// result == 0 meaning s1 is equal to s2
result = String.Compare(s1, s2, true);

How to convert a string to a number

int intVal =
  int.Parse("123", System.Globalization.CultureInfo.CurrentCulture);
float floatVal =
  float.Parse("123.45", System.Globalization.CultureInfo.CurrentCulture);
decimal decimalVal =
  Decimal.Parse("123.45", System.Globalization.CultureInfo.CurrentCulture);
// TryParse method checks whether conversion is possible
bool parseSuccess = Decimal.TryParse("123.45", out decimalVal);

How to create a string of repeated characters

string eightyAsterisks = new string('*', 80);

How to get a Substring from a String

string s = "ABC";
string secondAndThirdChar = s.Substring(1, 2);
// secondAndThirdChar == "BC"
// WARNING:
// The first parameter to Substring is the zero-based
// start index for substring
// The second parameter to Substring is the Length of
// the requested substring
// The zero-based start index plus the requested length
// must fall within the original string
// Otherwise, an exception is thrown
// The following will throw an ArgumentOutOfRangeException
// string secondAndThirdChar = s.Substring(1, 3);

Threading

How to execute a time-consuming operation on a separate thread

using System.Threading;
// Method executed on the MAIN (UI) thread
void PerformWork()
{
  const Int64 question = 20;
  FactorialCalc factorialCalc = new FactorialCalc(question);
  Thread thread = new Thread(TheWork);
  thread.Start(factorialCalc);
  thread.Join();    // block main thread until the worker thread is done
  MessageBox.Show(String.Format("The factorial of {0} is {1}.",
                  question, factorialCalc.Answer));
}
// Method executed on a different, worker thread
void TheWork(object data)
{
  if (data is FactorialCalc)
  {
    FactorialCalc factorialCalc = data as FactorialCalc;
    factorialCalc.Calculate();
  }
}
// Helper class to calculate factorial
class FactorialCalc
{
  readonly Int64 m_Question;
  Int64 m_Answer;
  private FactorialCalc(){}
  public FactorialCalc(Int64 question)
  {
    this.m_Question = question;
  }
  public Int64 Answer
  {
    get { return m_Answer; }
  }
  // this is the time-consuming method that will be called from a worker thread
  public void Calculate()
  {
    this.m_Answer = this.CalculateHelper(this.m_Question);
  }
  Int64 CalculateHelper(Int64 number)
  {
    if (number > 0)
      return number * CalculateHelper(number - 1);
    else
      return 1;
  }
}

List Processing

How to check whether an element exists in a list

using System.Collections.Generic;

// List of Value Types
List list = new List(new int[] { 1, 2, 3 });
bool found = list.Contains(1);  // found == TRUE
found = list.Contains(4);       // found == FALSE

// List of Reference Types - Does not work as expected
class SomeClass
{
 string m_Id;

 private SomeClass() { }
 public SomeClass(string id)
 {
  this.m_Id = id;
 }
}

List list =
  new List(new SomeClass[] { new SomeClass("100") });
SomeClass lookupValue = new SomeClass("100");
bool found = list.Contains(lookupValue);      // found == FALSE

// Contains() method does NOT work as expected because Contains()
// does a comparison of lookupValue object with the elements in
// the list by Reference, not by internal values represented by
// the object (m_Id in our example).

// To correct this behavior we will need to override Equals()
// method of our class

// List of Reference Types - Works as expected after override of Equals()
class SomeClass
{
 string m_Id;

 private SomeClass() { }
 public SomeClass(string id)
 {
  this.m_Id = id;
 }

 public override bool Equals(object obj)
 {
  if (obj == null || !(obj is SomeClass))
   return false;
  return this.Equals(obj as SomeClass);
 }

 public bool Equals(SomeClass someClass)
 {
  return someClass.m_Id == this.m_Id;
 }

 // When Equals is overridden, it is also recommended that
 // GetHashCode() be overridden.
 // GetHashCode() provides a hash value for proper handling
 // of an object contained in data structures such as a Dictionary
 public override int GetHashCode()
 {
  return Int32.Parse(this.m_Id);
 }
}

// Contains() works as expected now
List list =
  new List(new SomeClass[] { new SomeClass("100") });
SomeClass lookupValue = new SomeClass("100");
bool found = list.Contains(lookupValue);      // found == TRUE

SomeClass lookupValue2 = new SomeClass("200");
found = list.Contains(lookupValue2);          // found == FALSE


File System

Iterating through files in a directory

/// <summary>
/// Walks through files in the given directory
///   calls the fileFoundCallback
/// </summary>
public class FileIterator
{
public delegate void FileFoundCallback(string filePath);
static public void WalkDirectoryTree(
System.IO.DirectoryInfo root, List<string> desiredExtensions,
    FileFoundCallback fileFoundCallback)
{
  List<System.IO.FileInfo> files = new List<FileInfo>();
  System.IO.DirectoryInfo[] subDirs = null;
  // First, process all the files directly under this folder
  foreach (string desiredExtention in desiredExtensions)
  {
     files.AddRange(root.GetFiles(desiredExtention));
  }
  if (files != null)
  {
    foreach (System.IO.FileInfo fi in files)
    {
      if (fileFoundCallback != null)
        fileFoundCallback(fi.FullName);
    }
    // Now find all the subdirectories under this directory.
    subDirs = root.GetDirectories();
    foreach (System.IO.DirectoryInfo dirInfo in subDirs)
    {
      // Resursive call for each subdirectory.
      WalkDirectoryTree(dirInfo, desiredExtensions,
         fileFoundCallback);
    }
  }
}
}


LINQ

Using LINQ to filter data class Person
{
  public string FirstName {get; set;}
}
Person[] people = new Person[] {
                      new Person() {FirstName = "Bob"},
                      new Person() {FirstName = "Bruce"},
                      new Person() {FirstName = "Jim"}
                      };
// all people whose first name starts with "B"
var bPeople = from p in people

Xml

Creating Xml Fragments

using System.Linq;
using System.Xml.Linq;
string [] todoList = new string [] {"grocery", "laundry"};
XElement data = new XElement("TodoList",
  from t in todoList
  select new XElement("Todo", new XAttribute("Task", t));
// XmlWriter and Reader can be used to read/write XElement
XElement data = XElement.Load(reader);
todoList = (from t in data.DescendantsAndSelf("Todo")
             select new string (t.Attribute("Task")).ToList();

Retrieving data from an Xml Document

XPathDocument xPathDocument = new XPathDocument(xmlFilePath);
XPathNavigator xPathNavigator = xPathDocument.CreateNavigator();
// Sample Data:
// <CustomerList><Customer name="John"><Address>123 Ash
//  Street</Address></Customer></CustomerList>
// To get customer name - value of an attribute of an XML Node Element
XPathNodeIterator nodesText = xPathNavigator.Select(//CustomerList/Customer/@name);
// To get street address - value of an XML Node Element)
// XPathNodeIterator nodesText =
//    xPathNavigator.Select("//CustomerList/Customer/Address");
while (nodesText.MoveNext())
{
    // nodesText.Current.Value
    // nodesText.Current.Name
}

Web

Sending email using SmtpClient
public class EmailSender
{
 #region Data
 string Host;
 int Port;
 string Username;
 string Password;
 string From;
 int TimeoutInSeconds;
 bool UseSSL;
 List<string> TO;
 List<string> CC;
 List<string> BCC;
 string Subject;
 string Body;
 #endregion
 #region Constructor
 public EmailSender(
     string host,
     int port,
     string username,
     string password,
     string from,
     int timeoutInSeconds,
     bool useSSL,
     List<string> to,
     List<string> cc,
     List<string> bcc,
     string subject,
     string body)
 {
     this.Host = host;
     this.Port = port;
     this.Username = username;
     this.Password = password;
     this.From = from;
     this.TimeoutInSeconds = timeoutInSeconds;
     this.UseSSL = useSSL;
     this.TO = to;
     this.CC = cc;
     this.BCC = bcc;
     this.Subject = subject;
     this.Body = body;
 }
 #endregion
 #region Public API
 public void SendNow()
 {
     SmtpClient smtpClient = new SmtpClient(Host, Port);
     smtpClient.Timeout = this.TimeoutInSeconds * 1000;
     smtpClient.EnableSsl = this.UseSSL;    
     smtpClient.Credentials = new NetworkCredential(this.Username, this.Password, "");
     MailMessage mailMessage = new MailMessage();
     mailMessage.From = new MailAddress(this.From);
     AssignAddresses(mailMessage.To, this.TO);
     AssignAddresses(mailMessage.CC, this.CC);
     AssignAddresses(mailMessage.Bcc, this.BCC);
     mailMessage.Subject = this.Subject;
     mailMessage.Body = this.Body;
     smtpClient.Send(mailMessage);
 }
 void AssignAddresses(MailAddressCollection addressCollection, List<string> emails)
 {
     foreach (string email in emails)
     {
  MailAddress mailAddress = new MailAddress(email);
  addressCollection.Add(mailAddress);
     }
 }
 #endregion
}
ASP.Net Forms Authentication
Web.Config (root Directory)Aspx pages under admin directory of a website are being secured. Specify where the login page is. Accessing any aspx page under admin directory without login redirects to admin/Login.aspx.
  <system.web>
    <authentication mode="Forms">
      <forms loginUrl="admin/Login.aspx" name=".ASPXFORMSAUTH"/>
    </authentication>
  </system.web>
Web.Config (admin Directory)Specify in web.config of the directory being secured.
  <system.web>
    <authorization>
      <deny users="?" />
    </authorization>
  </system.web>
Login
Create a Login.aspx page under the admin directory that solicits username password. On submit, authenticate as follows:
 if ((LoginName.Text == "whatevername") &&
                    (LoginPassword.Text == "whateverpassword"))
  {
    // tell Forms Authentication module the user is authenticated
    FormsAuthentication.RedirectFromLoginPage
     (LoginName.Text, false);
  }
Signout  FormsAuthentication.SignOut();
  Response.Redirect("Login.aspx");
Who is logged in?  Welcome.Text = "Hello, " + Context.User.Identity.Name;
CSS - Stylesheets - CSS Design Reference
  • By Element Type
  • By Id (#stylename)
  • By Class (.MyClass)

ASP.Net Debugging
  •  Debugging can be turned on in web.config file
  • Use Trace.axd to view program trace at the bottom of regular aspx page
  • Debugger breakpoint programmatically - System.Diagnostics.Debugger.Break()
WCF

How to create a service proxy at a client using Windows Communication Foundation (WCF) when service contract is available

using System.ServiceModel;
// ABCs of the endpoint
// Specify where and how the service can be reached
// A: Address
EndpointAddress endPointAddress =
  new EndpointAddress("net.tcp://localhost:9000/TipService");
// B: Binding
// Use classic RPC calls over TCP; this can be basicHttpBinding
// Binding must match the binding used by the host
System.ServiceModel.Channels.Binding binding = new NetTcpBinding();
// C: Service Contract is specified as ITipService parameter (see below)
// to ChannelFactory
// Create a proxy on the client side to talk to the real service
ITipService tipServiceProxy =
  ChannelFactory<ITipService>.CreateChannel(binding, endPointAddress);
...
// Make a call using the proxy
decimal tip = tipServiceProxy.CalulateTip(55.25M);
///
/// This is the Service Contract that is referenced in the code above
/// Lives in a shared assembly
/// This is the API for the TipService
///
[ServiceContract(Namespace = "http://www.razzaq.org/pub/2008/18")]
public interface ITipService
{
  [OperationContract]
  decimal CalulateTip(decimal billAmount);
}

How to programmatically host a service using Windows Communication Foundation (WCF)
using System.ServiceModel


using System.ServiceModel;
// Create a Service Host for the Tip Service
// Note: The concrete type of service is being passed as an
// argument to the ServiceHost constructor
// Lives in the SERVICE LAYER
using (ServiceHost host = new ServiceHost(typeof(ServiceLayer.TipService)))
{
  // ABCs for the endpoint where the service can be reached
  // A: Address
  string address = "net.tcp://localhost:9000/TipService";
  // B: Binding
  // Use classic RPC calls over TCP
  System.ServiceModel.Channels.Binding binding =  new NetTcpBinding();
  // C: Contract
  Type serviceContract = typeof(ServiceLayer.ITipService);
  // Add EndPoint where this service can be reached
  host.AddServiceEndpoint(serviceContract, binding, address);
  // Start the service on the specified Endpoint(s)
  host.Open();
  // Display service status
  Console.WriteLine(
    String.Format("MockServiceHost is hosting \"ITipService\" on {0}",
    address));
  Console.WriteLine("Press ENTER to terminate...");
  // block this thread from terminating so that the host can live on
  Console.ReadLine();
}
///
/// This is the Service Contract that is referenced in the code above
/// Lives in a shared assembly
/// This is the API for the TipService
///
[ServiceContract(Namespace = "http://www.razzaq.org/pub/2008/18")]
public interface ITipService
{
  [OperationContract]
  decimal CalulateTip(decimal billAmount);
}
///
/// Uses code in business layer
/// Concrete implementation of the service interface
/// Lives in the SERVICE LAYER
///
public class TipService : ITipService
{
  public decimal CalulateTip(decimal billAmount)
  {
    // A Service simply wraps the business functionality for use
    // by a Client
    // Here we are using the business object (see TipCalculatorBO below)
    // to do the real work of calculating the tip
    TipCalculatorBO tipCalculatorBO = new TipCalculatorBO(billAmount);
    return tipCalculatorBO.Tip;
  }
}
  ///
  /// Uses code in the data layer
  /// This class implements a Business Object (aka business logic)
  /// Lives in the BUSINESS LAYER
  ///
  public class TipCalculatorBO
  {
    private decimal m_BillAmount = 0M;
    protected TipCalculatorBO()
    {
    }
    public TipCalculatorBO(decimal billAmount)
    {
      this.m_BillAmount = billAmount;
    }
    public decimal Tip
    {
      get
      {
        TipPercentageLookupDTO tipPercentageLookupDTO =
          new TipPercentageLookupDTO();
        return tipPercentageLookupDTO.TipPercentage * this.m_BillAmount;
      }
    }
  }
  ///
  /// Implements a Data Tranfer Object that retrieves
  /// information from some persistent storage
  /// Lives in the DATA LAYER
  ///
  public class TipPercentageLookupDTO
  {
    private decimal m_TipPercentage;
    public TipPercentageLookupDTO()
    {
      // This would be retrieved from some persistent storage
      // such as a database table
      m_TipPercentage = 0.20M;
    }
    public decimal TipPercentage
    {
      get
      {
      return this.m_TipPercentage;
      }
    }
  }

Windows Forms

How to get appSettings value from App.Config

using System.Configuration;
// someKeyValue will be set to "CorrespondingValue"
string someKeyValue = ConfigurationManager.AppSettings["SomeKey"];
<?xml version="1.0" encoding="utf-8" ?>
<!--Sample App.Config-->
<configuration>
  <appSettings>
    <add key="SomeKey" value="CorrespondingValue"/>
  </appSettings>
</configuration>

Full path of the directory from which an application is started

using System.Windows.Forms;
string appStartupPath = Application.StartupPath;
Open a document from an application 

using System.Diagnostics;
string documentPath = @"C:\temp\expense.xls";
Process.Start(documentPath);

C# Language

Tips
  1. Always use properties instead of data members for protected and public members. Public data members and public properties are not binary compatible
  2. Avoid object casts. Use is and as operators to work with objects. is and as are successful with objects of derived types when tested for base type. as returns null if the object is not of specified type. To deteremine exact type use object.GetType()
  3. Use readonly constants instead of static constants to avoid breaking binary compatability of binaries. static constants are literally replaced in code at compile time. readonly constants are referenced at compile time but initialized at runtime
  4. Use ConditionalAttributes to include/exclude code from execution. The attribute [Conditional("DEBUG")] is applied to a method with no parameters and no return value. Based on whether the environment variable is defined, the method and the call to the method is included in JITted code. The assembly contains the entire code
  5. OverrideToString() member of a user-defined type. To support more customizable ToString() display, implement System.IFormattable interface where custom string formats are defined and implemented. Lacking these, the client code will need to implement and use a class that implements IFormatProvider and companion class that implements ICustomFormater.
Reference: Effective C# (Covers C# 4.0): 50 Specific Ways to Improve Your C# (2nd Edition) (Effective Software Development Series)

Class Indexer
// AnyClass contains some data
// AnyClass provides an index to look up a particular value
// from the contained data
//
public class AnyClass
{
  string [] data = { "red", "green", "blue" };
  // This special property makes this class index-able
  public string this[int index]
  {
    get
    {
      return data[index];
    }
  }
}
// Using the class defined above
AnyClass anyClass = new AnyClass();
int index = 1;
// using an index to query the class for value
//   indexValue is set to "green"
string indexValue = anyClass[index];

Dynamically create objects using type (class) names

// Address class is defined in some other assembly
string typeName = "SomeOtherAssembly.Address, SomeOtherAssembly";
Type type = Type.GetType(typeName);
IAddress address =
  (IAddress) Activator.CreateInstance(type,
                                 new object[] {"Ian", "Ireland" });
// IAddress interface is defined in a common assembly
public interface IAddress
{
  string Name { get; }
  string Country { get; }
}
// Address class is defined in a separate assembly: SomeOtherAssembly.dll
public class Address : IAddress
{
  string m_Name;
  string m_Country;
  public string Name
  {
    get { return m_Name; }
    set { m_Name = value; }
  }
  public string Country
  {
    get { return m_Country; }
    set { m_Country = value; }
  }
  private Address()
  {
  }
  public Address(string name, string country)
  {
    this.m_Name = name;
    this.m_Country = country;
  }
}
How to serialize and deserialize an object

using System.Xml.Serialization;
using System.IO;
// Prepare a class for serialization
public class SomeClass
{
 string m_Data;
 // MUST DEFINE A PUBLIC ACCESSOR FOR m_Data
 // OTHERWISE, m_Data will NOT be Serialized
 public string Data
 {
  get { return m_Data; }
  set { m_Data = value; }
 }
 private SomeClass()
 {
 }
 public SomeClass(string data)
 {
  this.m_Data = data;
 }
 // Override to do an object comparision by contained value
 public override bool Equals(object obj)
 {
  if (obj == null || !(obj is SomeClass))
   return false;
  return (obj as SomeClass).m_Data == this.m_Data;
 }
 // Serialize and Deserialize methods can be written as
 // GENERIC methods in a Utility class and used to
 // serialize and deserialize any class
 static public string Serialize(SomeClass someClass)
 {
  XmlSerializer xmlSerializer =
   new XmlSerializer(typeof(SomeClass));
  StringWriter stringWriter = new StringWriter();
  xmlSerializer.Serialize(stringWriter, someClass);
  stringWriter.Close();
  return stringWriter.ToString();
 }
 static public SomeClass Deserialize(string xml)
 {
  XmlSerializer xmlSerializer =
   new XmlSerializer(typeof(SomeClass));
  StringReader stringReader = new StringReader(xml);
  return xmlSerializer.Deserialize(stringReader) as SomeClass;
 }
}

// Test the class above
SomeClass someClassOriginal = new SomeClass("abc");
string someClassSerialized =
 SomeClass.Serialize(someClassOriginal);
SomeClass someClassDeserialized =
 SomeClass.Deserialize(someClassSerialized);
bool areEqual =
 someClassOriginal.Equals(someClassDeserialized); // areEqual == TRUE
// XML representation of a SomeClass object
//  The value of someClassSerialized variable above
//
<?xml version=\"1.0\" encoding=\"utf-16\"?>
  <SomeClass
        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance/"
        xmlns:xsd=\"http://www.w3.org/2001/XMLSchema/">
    <Data>abc</Data>
  </SomeClass>

Readonly class data member readonly

class SomeClass
{
  // readonly fields may only be assigned values in the constructor (see below)
  readonly int m_SomeData;
  // or at the time a readonly field is declared
  readonly int m_SomeOtherData = 5;
  public SomeClass(int someData)
  {
    m_SomeData = someData;
  }
}
Code Profiling and Inspection

ANTS Profiler
Code profiling tool to find slow performing areas of code or to find memory and resource leaks.
http://www.red-gate.com/products/ANTS_Profiler/features.htm

dotTrace
Code profiling tool to find slow performing areas of code or to find memory and resource leaks.
http://www.jetbrains.com/profiler/

Reflector
Tool to inspect .NET assemblies and understand inner workings of the .NET code.
http://www.red-gate.com/products/reflector/

Xml Notepad
XML Notepad 2007 provides a simple intuitive user interface for browsing and editing XML documents. It is better to view/edit an XML document with an XML editor than with a text editor to avoid inadvertent XML format errors.
http://www.microsoft.com/downloads/details.aspx?familyid=72d6aa49-787d-4118-ba5f-4f30fe913628&displaylang=en

Enterprise Logging
If an application uses Enterprise Logging Block or similar, there may be configurable options available in app.config or web.config files to dump additional logging information to a file, the Windows Event Viewer or some other listener.
http://msdn.microsoft.com/en-us/library/cc309506.aspx

Network Diagnostics

netstat
Run from Window Command line. Displays protocol statistics and current TCP/IP network connections.
ipconfig
Shows IP (Internet Protocol) configuration for a machine.

Fiddler
A HTTP Debugging Proxy which logs all HTTP traffic between your computer and the Internet. Allows inspection and manipulation of HTTP traffic.
http://www.fiddlertool.com/fiddler/

WireShark
Lower level network traffic and network protocol analyzer.
http://www.wireshark.org/

Windows Diagnostics

msconfig
Run from Window Command line. System Configuration Utility which lets you inspect Windows Startup and INI files.

eventvwr
Run from Window Command line. eventvwr is the Windows Event Viewer. Many applications, specially Windows Services, log errors and diagnostic messages in the Event Viewer.

compmgmt.msc
Run from Window Command line. This is the consolidated Computer Management applet. Allows access to configuration of various Windows Components such as MSMQ, Internet Information Server (IIS), Windows Services, Event Viewer, Devices and more.