C# System API : System ex 1

1 Activator.CreateInstance(Type classType)

 

using System;
using System.Reflection;
using System.IO;

public class MainClass
{
  public static int Main(string[] args)
  {
    Assembly a = null;
    try
    {
      a = Assembly.Load("YourLibraryName");
    }
    catch(FileNotFoundException e)
    {Console.WriteLine(e.Message);}
  
    Type classType = a.GetType("YourLibraryName.ClassName");

    object obj = Activator.CreateInstance(classType);
  
    MethodInfo mi = classType.GetMethod("MethodName");

    mi.Invoke(obj, null);

    object[] paramArray = new object[2];    
    paramArray[0] = "Fred";
    paramArray[1] = 4;
    mi = classType.GetMethod("MethodName2");
    mi.Invoke(obj, paramArray);

    return 0;
  }
}

2new AppDomainSetup()

 
using System;

class MainClass
{
    public static void Main()
    {
        AppDomainSetup setupInfo = new AppDomainSetup();


        setupInfo.ApplicationBase = @"C:\MyRootDirectory";
        setupInfo.ConfigurationFile = "MyApp.config";
        setupInfo.PrivateBinPath = "bin;plugins;external";

        AppDomain newDomain = AppDomain.CreateDomain("My New AppDomain", null, setupInfo);

    }
}
3AppDomainSetup.PrivateBinPath
 

using System;

class Test
{
    public static void Main()
    {
        AppDomainSetup setupInfo = new AppDomainSetup();

        setupInfo.ApplicationBase = @"C:\MyRootDirectory";
        setupInfo.ConfigurationFile = "MyApp.config";
        setupInfo.PrivateBinPath = "bin;plugins;external";

        AppDomain newDomain = 
            AppDomain.CreateDomain("My New AppDomain", null, setupInfo);
    }
}
AppDomainSetup.ConfigurationFile
 


using System;

class Test
{
    public static void Main()
    {
        AppDomainSetup setupInfo = new AppDomainSetup();

        setupInfo.ApplicationBase = @"C:\MyRootDirectory";
        setupInfo.ConfigurationFile = "MyApp.config";
        setupInfo.PrivateBinPath = "bin;plugins;external";

        AppDomain newDomain = 
            AppDomain.CreateDomain("My New AppDomain", null, setupInfo);
    }
}

5AppDomainSetup.ApplicationBase

 
using System;

class MainClass
{
    public static void Main()
    {
        AppDomainSetup setupInfo = new AppDomainSetup();


        setupInfo.ApplicationBase = @"C:\MyRootDirectory";
        setupInfo.ConfigurationFile = "MyApp.config";
        setupInfo.PrivateBinPath = "bin;plugins;external";

        AppDomain newDomain = AppDomain.CreateDomain("My New AppDomain", null, setupInfo);

    }
}

  

6new ArgumentException()

 

using System;
using System.Collections.Generic;
using System.Text;

public struct Point : IComparable {
    private int x, y;
    public Point(int xPos, int yPos) {
        x = xPos;
        y = yPos;
    }
    public static Point operator +(Point p1, Point p2) { return new Point(p1.x + p2.x, p1.y + p2.y); }
    public static Point operator -(Point p1, Point p2) { return new Point(p1.x - p2.x, p1.y - p2.y); }
    public static bool operator ==(Point p1, Point p2) { return p1.Equals(p2); }
    public static bool operator !=(Point p1, Point p2) { return !p1.Equals(p2); }
    public static bool operator <(Point p1, Point p2) { return (p1.CompareTo(p2) < 0); }
    public static bool operator >(Point p1, Point p2) { return (p1.CompareTo(p2) > 0); }
    public static bool operator <=(Point p1, Point p2) { return (p1.CompareTo(p2) <= 0); }
    public static bool operator >=(Point p1, Point p2) { return (p1.CompareTo(p2) >= 0); }
    public static Point operator ++(Point p1) { return new Point(p1.x + 1, p1.y + 1); }
    public static Point operator --(Point p1) { return new Point(p1.x - 1, p1.y - 1); }
    public override bool Equals(object o) {
        if (o is Point) {
            if (((Point)o).x == this.x &&
                ((Point)o).y == this.y)
                return true;
        }
        return false;
    }

    public override int GetHashCode() { return this.ToString().GetHashCode(); }
    public override string ToString() {
        return string.Format("[{0}, {1}]", this.x, this.y);
    }
    public int CompareTo(object obj) {
        if (obj is Point) {
            Point p = (Point)obj;
            if (this.x > p.x && this.y > p.y)
                return 1;
            if (this.x < p.x && this.y < p.y)
                return -1;
            else
                return 0;
        } else
            throw new ArgumentException();
    }
    public static Point Add(Point p1, Point p2) { return p1 + p2; }
    public static Point Subtract(Point p1, Point p2) { return p1 - p2; }
}
class Program {
    static void Main(string[] args) {
        Point ptOne = new Point(100, 100);
        Point ptTwo = new Point(40, 40);
        Console.WriteLine("ptOne = {0}", ptOne);
        Console.WriteLine("ptTwo = {0}", ptTwo);
        Console.WriteLine("ptOne + ptTwo: {0} ", ptOne + ptTwo);
        Console.WriteLine("Point.Add(ptOne, ptTwo): {0} ", Point.Add(ptOne, ptTwo));

        Console.WriteLine("ptOne - ptTwo: {0} ", ptOne - ptTwo);
        Console.WriteLine("Point.Subtract(ptOne, ptTwo): {0} ", Point.Subtract(ptOne, ptTwo));

        Point ptThree = new Point(90, 5);
        Console.WriteLine("ptThree = {0}", ptThree);
        Console.WriteLine("ptThree += ptTwo: {0}", ptThree += ptTwo);

        Point ptFour = new Point(0, 500);
        Console.WriteLine("ptFour = {0}", ptFour);
        Console.WriteLine("ptFour -= ptThree: {0}", ptFour -= ptThree);

        Point ptFive = new Point(10, 10);
        Console.WriteLine("ptFive = {0}", ptFive);
        Console.WriteLine("++ptFive = {0}", ++ptFive);
        Console.WriteLine("--ptFive = {0}", --ptFive);

        Console.WriteLine("ptOne == ptTwo : {0}", ptOne == ptTwo);
        Console.WriteLine("ptOne != ptTwo : {0}", ptOne != ptTwo);
        Console.WriteLine("ptOne < ptTwo : {0}", ptOne < ptTwo);
        Console.WriteLine("ptOne > ptTwo : {0}", ptOne > ptTwo);
    }
}
7extends Attribute
 
using System;


public class MainClass 
{

    public static void Main() 
    {

        UnitTest u;

        Console.Write("Class1 UnitTest attribute: ");
        u = (UnitTest) Attribute.GetCustomAttribute(typeof(Class1), typeof(UnitTest));
        Console.WriteLine(u.Written());
        Console.Write("Class2 UnitTest attribute: ");
        u = (UnitTest) Attribute.GetCustomAttribute(typeof(Class2), typeof(UnitTest));
        Console.WriteLine(u.Written());

    }

}


public class UnitTest : Attribute
{
    bool bWritten;

    public bool Written()
    {
        return bWritten;
    }

    public UnitTest(bool Written)
    {
        bWritten = Written;
    }
}

// apply the UnitTest attribute to two classes
[UnitTest(true)]
public class Class1
{
}

[UnitTest(false)]
public class Class2
{
}

8Attribute.Value

 
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
public class MainClass {
    public static void Main() {
        XElement firstParticipant;
        XDocument xDocument  = new XDocument(
          new XElement("Books", firstParticipant =
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XAttribute("experience", "first-time"),
              new XElement("FirstName", "J"),
              new XElement("LastName", "R"))));

        Console.WriteLine(xDocument);
        firstParticipant.Attribute("experience").Value = "beginner";
        Console.WriteLine(xDocument);
    }
}

Attribute.Remove()

 
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
public class MainClass {
    public static void Main() {
        XElement firstParticipant;
        XDocument xDocument = new XDocument(
          new XElement("Books", firstParticipant =
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XElement("FirstName", "J"),
              new XElement("LastName", "R"))));
        Console.WriteLine(xDocument);
        firstParticipant.Attribute("type").Remove();
        Console.WriteLine(xDocument);
    }
}

10 Attribute.GetCustomAttribute(Type t, Type tR);

 

using System;  
using System.Reflection; 
  
[AttributeUsage(AttributeTargets.All)] 
public class MyAttribute : Attribute { 
  public string remark;
 
  public string supplement; 
 
  public MyAttribute(string comment) { 
    remark = comment; 
    supplement = "None"; 
  } 
 
  public string Remark { 
    get { 
      return remark; 
    } 
  } 
}  
 
[MyAttribute("This class uses an attribute.", 
                 supplement = "This is additional info.")] 
class UseAttrib { 
} 
 
class MainClass {  
  public static void Main() {  
    Type t = typeof(UseAttrib); 
 
    Console.Write("Attributes in " + t.Name + ": "); 
 
    object[] attribs = t.GetCustomAttributes(false);  
    foreach(object o in attribs) { 
      Console.WriteLine(o); 
    } 
 
    // Retrieve the MyAttribute. 
    Type tRemAtt = typeof(MyAttribute); 
    MyAttribute ra = (MyAttribute) 
          Attribute.GetCustomAttribute(t, tRemAtt); 
 
    Console.Write("Remark: "); 
    Console.WriteLine(ra.remark); 
 
    Console.Write("Supplement: "); 
    Console.WriteLine(ra.supplement); 
  }  
}

11 AttributeUsage(AttributeTargets)

using System;

[AttributeUsage(AttributeTargets.Class)]
public class RandomSupplier : Attribute
{
  public RandomSupplier()
  {
  }
}

[AttributeUsage(AttributeTargets.Method )]
public class RandomMethod : Attribute
{
  public RandomMethod()
  {
  }
}

[RandomSupplier]
public class OriginalRandom
{
  [RandomMethod]
  public int GetRandom()
  {
    return 5;
  }
}

using System;

[RandomSupplier]
public class NewRandom
{
  [RandomMethod]
  public int ImprovedRandom()
  {
    Random r = new Random();
    return r.Next(1, 100);
  }
}

public class AnotherClass
{
  public int NotRandom()
  {
    return 1;
  }
}

using System;
using System.Reflection;

class MainClass 
{

  public static void Main(string[] args) 
  {

    RandomSupplier rs;
    RandomMethod rm;

    foreach(string s in args)
    {
      Assembly a = Assembly.LoadFrom(s);

      foreach(Type t in a.GetTypes())
      {
        rs = (RandomSupplier) Attribute.GetCustomAttribute(
         t, typeof(RandomSupplier));
        if(rs != null)
        {
          Console.WriteLine("Found RandomSupplier class {0} in {1}",
           t, s);
          foreach(MethodInfo m in t.GetMethods())
          {
            rm = (RandomMethod) Attribute.GetCustomAttribute(
             m, typeof(RandomMethod));
            if(rm != null)
            {
              Console.WriteLine("Found RandomMethod method {0}"
               , m.Name );
            }
          }        
        }
      }
    }

  }

}

12 Boolean.FalseString

 
using System;

class MainClass
{
    public static void Main(string[] args)
    {
    Console.WriteLine("bool.FalseString: {0}",bool.FalseString);
    Console.WriteLine("bool.TrueString: {0}",bool.TrueString);
    }

}

13 Boolean.Parse(String value)

 
using System;

class MainClass
{
    public static void Main(string[] args)
    {
    bool myBool = bool.Parse("True");
    Console.WriteLine("-> Value of myBool: {0}", myBool);
    }
}

14 ConsoleKey.Backspace

 

using System;
using System.Collections.Generic;

class MainClass
{
    public static void Main()
    {
        ConsoleKeyInfo key;

        List<char> input = new List<char>(); 

        do{
          key = Console.ReadKey(true);
          if (key.Key == ConsoleKey.F1)
          {
             Console.WriteLine("F1");
          }
          if (key.Key == ConsoleKey.Backspace)
          {
              if (input.Count > 0)
              {
                  input.RemoveAt(input.Count - 1);

                  Console.Write(key.KeyChar);
              }
          }else if (key.Key == ConsoleKey.Escape){
                Console.Clear();
                Console.WriteLine("Input: {0}\n\n",new String(input.ToArray()));
                input.Clear();
          }else if (key.Key >= ConsoleKey.A && key.Key <= ConsoleKey.Z){
                input.Add(key.KeyChar); 
                Console.Write(key.KeyChar);
           }
      } while (key.Key != ConsoleKey.X || key.Modifiers != ConsoleModifiers.Alt);
  }
}

   

15 ConsoleKey.F1

 


using System;
using System.Collections.Generic;

class MainClass
{
    public static void Main()
    {
        ConsoleKeyInfo key;

        List<char> input = new List<char>(); 

        do{
          key = Console.ReadKey(true);
          if (key.Key == ConsoleKey.F1)
          {
             Console.WriteLine("F1");
          }
          if (key.Key == ConsoleKey.Backspace)
          {
              if (input.Count > 0)
              {
                  input.RemoveAt(input.Count - 1);

                  Console.Write(key.KeyChar);
              }
          }else if (key.Key == ConsoleKey.Escape){
                Console.Clear();
                Console.WriteLine("Input: {0}\n\n",new String(input.ToArray()));
                input.Clear();
          }else if (key.Key >= ConsoleKey.A && key.Key <= ConsoleKey.Z){
                input.Add(key.KeyChar); 
                Console.Write(key.KeyChar);
           }
      } while (key.Key != ConsoleKey.X || key.Modifiers != ConsoleModifiers.Alt);
  }
}

16 ConsoleKey.Escape

 

using System;
using System.Collections.Generic;

class MainClass
{
    public static void Main()
    {
        ConsoleKeyInfo key;

        List<char> input = new List<char>(); 

        do{
          key = Console.ReadKey(true);
          if (key.Key == ConsoleKey.F1)
          {
             Console.WriteLine("F1");
          }
          if (key.Key == ConsoleKey.Backspace)
          {
              if (input.Count > 0)
              {
                  input.RemoveAt(input.Count - 1);

                  Console.Write(key.KeyChar);
              }
          }else if (key.Key == ConsoleKey.Escape){
                Console.Clear();
                Console.WriteLine("Input: {0}\n\n",new String(input.ToArray()));
                input.Clear();
          }else if (key.Key >= ConsoleKey.A && key.Key <= ConsoleKey.Z){
                input.Add(key.KeyChar); 
                Console.Write(key.KeyChar);
           }
      } while (key.Key != ConsoleKey.X || key.Modifiers != ConsoleModifiers.Alt);
  }
}
17 ConsoleModifiers.Alt
 

using System;
using System.Collections.Generic;

class MainClass
{
    public static void Main()
    {
        ConsoleKeyInfo key;

        List<char> input = new List<char>(); 

        do{
          key = Console.ReadKey(true);
          if (key.Key == ConsoleKey.F1)
          {
             Console.WriteLine("F1");
          }
          if (key.Key == ConsoleKey.Backspace)
          {
              if (input.Count > 0)
              {
                  input.RemoveAt(input.Count - 1);

                  Console.Write(key.KeyChar);
              }
          }else if (key.Key == ConsoleKey.Escape){
                Console.Clear();
                Console.WriteLine("Input: {0}\n\n",new String(input.ToArray()));
                input.Clear();
          }else if (key.Key >= ConsoleKey.A && key.Key <= ConsoleKey.Z){
                input.Add(key.KeyChar); 
                Console.Write(key.KeyChar);
           }
      } while (key.Key != ConsoleKey.X || key.Modifiers != ConsoleModifiers.Alt);
  }
}

  

18 DateTimeOffset.Offset

 
using System;
public class MainClass {
    public static void Main() {

        DateTimeOffset local = DateTimeOffset.Now;
        DateTimeOffset utc = local.ToUniversalTime();

        Console.WriteLine(local.Offset);   // -06:00:00 (in Central America)
        Console.WriteLine(utc.Offset);     // 00:00:00

        Console.WriteLine(local == utc);                 // True
        //To include the Offset in the comparison, you must use the EqualsExact method:
        Console.WriteLine(local.EqualsExact(utc));      // False
    }
}

19 Decimal.MaxValue

 



using System;
class Test {

  public static void Main() {
       // First, print out the minimum values
       Console.WriteLine("System Minimums\n");
       Console.WriteLine( "MinSByte {0}", System.SByte.MinValue);
       Console.WriteLine( "MinByte {0}", System.Byte.MinValue);
       Console.WriteLine( "MinInt16 {0}", System.Int16.MinValue);
       Console.WriteLine( "MinUInt16 {0}", System.UInt16.MinValue);
       Console.WriteLine( "MinInt32 {0}", System.Int32.MinValue);
       Console.WriteLine( "MinUInt32 {0}", System.UInt32.MinValue);
       Console.WriteLine( "MinInt64 {0}", System.Int64.MinValue);
       Console.WriteLine( "MinUInt64 {0}", System.UInt64.MinValue);
       Console.WriteLine( "MinChar {0}", System.Char.MinValue);
       Console.WriteLine( "MinSingle {0}", System.Single.MinValue);
       Console.WriteLine( "MinDouble {0}", System.Double.MinValue);
       // Console.WriteLine( "MinBoolean {0}", System.Boolean.MinValue);
       Console.WriteLine( "MinDecimal {0}", System.Decimal.MinValue);
    
       Console.WriteLine("\nSystem Maximums\n");
       Console.WriteLine( "MaxSByte {0}", System.SByte.MaxValue);
       Console.WriteLine( "MaxByte {0}", System.Byte.MaxValue);
       Console.WriteLine( "MaxInt16 {0}", System.Int16.MaxValue);
       Console.WriteLine( "MaxUInt16 {0}", System.UInt16.MaxValue);
       Console.WriteLine( "MaxInt32 {0}", System.Int32.MaxValue);
       Console.WriteLine( "MaxUInt32 {0}", System.UInt32.MaxValue);
       Console.WriteLine( "MaxInt64 {0}", System.Int64.MaxValue);
       Console.WriteLine( "MaxUInt64 {0}", System.UInt64.MaxValue);
       Console.WriteLine( "MaxChar {0}", System.Char.MaxValue);
       Console.WriteLine( "MaxSingle {0}", System.Single.MaxValue);
       Console.WriteLine( "MaxDouble {0}", System.Double.MaxValue);
       Console.WriteLine( "MaxDecimal {0}", System.Decimal.MaxValue);
  }
}

20 Decimal.MinValue

using System;
class Test {

  public static void Main() {
       // First, print out the minimum values
       Console.WriteLine("System Minimums\n");
       Console.WriteLine( "MinSByte {0}", System.SByte.MinValue);
       Console.WriteLine( "MinByte {0}", System.Byte.MinValue);
       Console.WriteLine( "MinInt16 {0}", System.Int16.MinValue);
       Console.WriteLine( "MinUInt16 {0}", System.UInt16.MinValue);
       Console.WriteLine( "MinInt32 {0}", System.Int32.MinValue);
       Console.WriteLine( "MinUInt32 {0}", System.UInt32.MinValue);
       Console.WriteLine( "MinInt64 {0}", System.Int64.MinValue);
       Console.WriteLine( "MinUInt64 {0}", System.UInt64.MinValue);
       Console.WriteLine( "MinChar {0}", System.Char.MinValue);
       Console.WriteLine( "MinSingle {0}", System.Single.MinValue);
       Console.WriteLine( "MinDouble {0}", System.Double.MinValue);
       // Console.WriteLine( "MinBoolean {0}", System.Boolean.MinValue);
       Console.WriteLine( "MinDecimal {0}", System.Decimal.MinValue);
    
       Console.WriteLine("\nSystem Maximums\n");
       Console.WriteLine( "MaxSByte {0}", System.SByte.MaxValue);
       Console.WriteLine( "MaxByte {0}", System.Byte.MaxValue);
       Console.WriteLine( "MaxInt16 {0}", System.Int16.MaxValue);
       Console.WriteLine( "MaxUInt16 {0}", System.UInt16.MaxValue);
       Console.WriteLine( "MaxInt32 {0}", System.Int32.MaxValue);
       Console.WriteLine( "MaxUInt32 {0}", System.UInt32.MaxValue);
       Console.WriteLine( "MaxInt64 {0}", System.Int64.MaxValue);
       Console.WriteLine( "MaxUInt64 {0}", System.UInt64.MaxValue);
       Console.WriteLine( "MaxChar {0}", System.Char.MaxValue);
       Console.WriteLine( "MaxSingle {0}", System.Single.MaxValue);
       Console.WriteLine( "MaxDouble {0}", System.Double.MaxValue);
       Console.WriteLine( "MaxDecimal {0}", System.Decimal.MaxValue);
  }
}

21 Double.Parse

 
using System;

public class NumericParsing
{
    public static void Main()
    {
        int value = Int32.Parse("99953");
        double dval = Double.Parse("1.3433E+35");
        Console.WriteLine("{0}", value);
        Console.WriteLine("{0}", dval);
    }
}

22 Double.ToString(String format, CultureInfo info)

  
using System;
using System.Globalization;
using System.Windows.Forms;

public class MainClass
{
    static void Main() {
        CultureInfo germany  = new CultureInfo( "de-DE" );

        double money = 123.45;

        string localMoney = money.ToString( "C", germany );
        Console.WriteLine( localMoney );

    }
}

23 Double.ToString(CultureInfo ci)

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading;
using System.Globalization;

public class MainClass
{
    public static void Main()
    {
       string[] cultures = new string[] { "en-US", "en-GB", "es-MX", "de-DE", "ja-JP" };

        using (TextWriter sw = Console.Out)
        {
            foreach (string c in cultures)
            {
                CultureInfo ci = new CultureInfo(c);

                double number = -100299.55;
                sw.WriteLine("    Number Format: {0}", number.ToString(ci));
            }
        }
    }
}
24 new EventHandler()
  

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class ResizeForm : System.Windows.Forms.Form
{
  private System.ComponentModel.Container components;

  public ResizeForm()
  {
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(292, 273);
    this.Resize += new System.EventHandler(this.ResizeForm_Resize);


  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new ResizeForm());
  }

  private void ResizeForm_Resize(object sender, System.EventArgs e)
  {
    Invalidate();
    Console.WriteLine("Resize");
  }

}

25 FormatException.Message

 
namespace nsExceptions
{
    using System;
    public class FormExce
    {
        static public void Main ()
        {
            const double pi = 3.14159;
            try
            {
                Console.WriteLine ("pi = {0,0:f5", pi);
            }
            catch (FormatException e)
            {
                Console.WriteLine (e.Message);
            }
        }
    }
}

26 new Guid

  
using System;
public class MainClass {
    public static void Main() {

        Guid g1 = new Guid("{0d57629c-7d6e-4847-97cb-9e2fc25083fe}");
        Guid g2 = new Guid("0d57629c7d6e484797cb9e2fc25083fe");
        Console.WriteLine(g1 == g2);  // True
    }
}

27 Guid.NewGuid()

  
    using System;


    public class MainClass
    {


        static void Main(string[] args)
        {
            Guid id = Guid.NewGuid();

            System.Console.WriteLine( id );
        }
    }
28 IAsyncResult.IsCompleted
 

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using System.Runtime.Remoting.Messaging;
using System.Threading;

class Program {
    static void Main(string[] args) {
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = "uid=sa;pwd=;Initial Catalog=Cars;Asynchronous Processing=true;Data Source=(local)";
        cn.Open();

        string strSQL = "WaitFor Delay '00:00:02';Select * From Inventory";
        SqlCommand myCommand = new SqlCommand(strSQL, cn);

        IAsyncResult itfAsynch;
        itfAsynch = myCommand.BeginExecuteReader(CommandBehavior.CloseConnection);

        while (!itfAsynch.IsCompleted) {
            Console.WriteLine("Working on main thread...");
            Thread.Sleep(1000);
        }
        SqlDataReader myDataReader = myCommand.EndExecuteReader(itfAsynch);
        while (myDataReader.Read()) {
            Console.WriteLine("-> Make: {0}, PetName: {1}, Color: {2}.",
              myDataReader["Make"].ToString().Trim(),
              myDataReader["PetName"].ToString().Trim(),
              myDataReader["Color"].ToString().Trim());
        }
        myDataReader.Close();
    }
}
29 implement IComparable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

class Person : IComparable {
    public string Name;
    public int Age;

    public Person(string name, int age) {
        Name = name;
        Age = age;
    }

    public int CompareTo(object obj) {
        if (obj is Person) {
            Person otherPerson = obj as Person;
            return this.Age - otherPerson.Age;
        } else {
            throw new ArgumentException(
               "Object to compare to is not a Person object.");
        }
    }
}

class Program {
    static void Main(string[] args) {
        ArrayList list = new ArrayList();
        list.Add(new Person("A", 30));
        list.Add(new Person("B", 25));
        list.Add(new Person("B", 27));
        list.Add(new Person("E", 22));

        for (int i = 0; i < list.Count; i++) {
            Console.WriteLine("{0} ({1})",
               (list[i] as Person).Name, (list[i] as Person).Age);
        }
        list.Sort();
        for (int i = 0; i < list.Count; i++) {
            Console.WriteLine("{0} ({1})",
               (list[i] as Person).Name, (list[i] as Person).Age);
        }
    }
}

30 implements IDisposable

  

using System;
public class MyClass : IDisposable
{
    private string name;
    public MyClass(string name) { this.name = name; }
    override public string ToString() { return name; }
   
    ~MyClass() 
    { 
        Dispose();
        Console.WriteLine("~MyClass(): " +name); 
    }
   
    public void Dispose()
    {
        Console.WriteLine("Dispose(): " +name);
        GC.SuppressFinalize(this);
    }
}


public class DisposableApp
{
    public static void Main(string[] args)
    {
        Console.WriteLine("start of Main, heap used: {0}", GC.GetTotalMemory(true));
        DoSomething();
        Console.WriteLine("end of Main, heap used: {0}", GC.GetTotalMemory(true));
    }
   
    public static void DoSomething()
    {
        MyClass[] ta = new MyClass[3];
   
        for (int i = 0; i < 3; i++)
        {
            ta[i] = new MyClass(String.Format("object #" +i));
            Console.WriteLine("Allocated {0} objects, heap used: {1}", i+1, GC.GetTotalMemory(true));
        }
   
        for (int i = 0; i < 3; i++)
        {
            ta[i].Dispose();
            ta[i] = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Console.WriteLine("Disposed {0} objects, heap used: {1}",i+1, GC.GetTotalMemory(true));
        }
    }
}

31 implements IFormattable

 


using System;
using System.Globalization;

public sealed class ComplexNumber : IFormattable
{
    public ComplexNumber( double real, double imaginary ) {
        this.real = real;
        this.imaginary = imaginary;
    }

    public override string ToString() {
        return ToString( "G", null );
    }

    public string ToString( string format, IFormatProvider formatProvider ) {
        string result = "(" + real.ToString(format, formatProvider) + " " + real.ToString(format, formatProvider) + ")";
        return result;
    }
   
    private readonly double real;
    private readonly double imaginary;
}

public sealed class MainClass
{
    static void Main() {
        ComplexNumber num1 = new ComplexNumber( 1.12345678, 2.12345678 );
        
        Console.WriteLine( "US format: {0}", num1.ToString( "F5", new CultureInfo("en-US") ) );
        Console.WriteLine( "DE format: {0}", num1.ToString( "F5", new CultureInfo("de-DE") ) );
        Console.WriteLine( "Object.ToString(): {0}",num1.ToString() );
    }
}
32 InvalidCastException.Message
 

using System;
using System.Collections;

class Album : IComparable, ICloneable {
    private string _Title;
    private string _Artist;

    public Album(string artist, string title) {
        _Artist = artist;
        _Title = title;
    }

    public string Title {
        get {
            return _Title;
        }
        set {
            _Title = value;
        }
    }

    public string Artist {
        get {
            return _Artist;
        }
        set {
            _Artist = value;
        }
    }
    public override string ToString() {
        return _Artist + ",\t" + _Title;
    }
    public int CompareTo(object o) {
        Album other = o as Album;
        if (other == null)
            throw new ArgumentException();
        if (_Artist != other._Artist)
            return _Artist.CompareTo(other._Artist);
        else
            return _Title.CompareTo(other._Title);
    }
    public object Clone() {
        return new Album(_Artist, _Title);
    }
}

public class foo {
    public foo() {
        myString = "Test";
    }
    private string myString;
}

class MainClass {
    static void Main(string[] args) {
        ArrayList arr = new ArrayList();

        arr.Add(new Album("G", "A"));
        arr.Add(new Album("B", "G"));
        arr.Add(new Album("S", "A"));

        arr.Sort();
        arr.Insert(0, new foo());

        try {
            foreach (Album a in arr) {
                Console.WriteLine(a);
            }
        } catch (System.InvalidCastException e) {
        }

    }
}

33 Object.GetType()

using System;

class MainClass
{
  static void Main(string[] args)
  {
    Object cls1 = new Object();
    System.String cls2 = "Test String" ;

    Type type1 = cls1.GetType();
    Type type2 = cls2.GetType();

    // Object class output
    Console.WriteLine(type1.BaseType);
    Console.WriteLine(type1.Name);
    Console.WriteLine(type1.FullName);
    Console.WriteLine(type1.Namespace);

    // string output
    Console.WriteLine(type2.BaseType);
    Console.WriteLine(type2.Name);
    Console.WriteLine(type2.FullName);
    Console.WriteLine(type2.Namespace);
  } 
}

34 Random.Next()

  
using System;

class CondOpApp {
    [STAThread]
    static void Main(string[] args) {
        Random rand = new Random();
        int a = 0, b = 0;

        for (int i = 0; i < 5; i++) {
            a = rand.Next() % 100;
            b = rand.Next() % 100;

            Console.WriteLine("a={0}, b={1}, so the winner is: {2}", a, b, a > b ? 'a' : 'b');
        }
    }
}

35 Random.NextDouble()

  
using System;
using System.Windows.Forms;
using System.Drawing;

public class Test {
  static void Main() {
      Random roller = new Random();
      double toHit = roller.NextDouble();
      Console.WriteLine(toHit);
  }
}

36 Random.Next(range)

  

using System;

public class RandomIntegers
{
   public static void Main( string[] args )
   {
      Random randomNumbers = new Random(); 
      int face; 

      for ( int counter = 1; counter <= 20; counter++ )
      {
         face = randomNumbers.Next( 1, 7 );
         Console.Write( "{0}  ", face );
         if ( counter % 5 == 0 )
            Console.WriteLine();
      } 
   }
} 
37 Single.MaxValue
 


using System;
class Test {

  public static void Main() {
       // First, print out the minimum values
       Console.WriteLine("System Minimums\n");
       Console.WriteLine( "MinSByte {0}", System.SByte.MinValue);
       Console.WriteLine( "MinByte {0}", System.Byte.MinValue);
       Console.WriteLine( "MinInt16 {0}", System.Int16.MinValue);
       Console.WriteLine( "MinUInt16 {0}", System.UInt16.MinValue);
       Console.WriteLine( "MinInt32 {0}", System.Int32.MinValue);
       Console.WriteLine( "MinUInt32 {0}", System.UInt32.MinValue);
       Console.WriteLine( "MinInt64 {0}", System.Int64.MinValue);
       Console.WriteLine( "MinUInt64 {0}", System.UInt64.MinValue);
       Console.WriteLine( "MinChar {0}", System.Char.MinValue);
       Console.WriteLine( "MinSingle {0}", System.Single.MinValue);
       Console.WriteLine( "MinDouble {0}", System.Double.MinValue);
       // Console.WriteLine( "MinBoolean {0}", System.Boolean.MinValue);
       Console.WriteLine( "MinDecimal {0}", System.Decimal.MinValue);
    
       Console.WriteLine("\nSystem Maximums\n");
       Console.WriteLine( "MaxSByte {0}", System.SByte.MaxValue);
       Console.WriteLine( "MaxByte {0}", System.Byte.MaxValue);
       Console.WriteLine( "MaxInt16 {0}", System.Int16.MaxValue);
       Console.WriteLine( "MaxUInt16 {0}", System.UInt16.MaxValue);
       Console.WriteLine( "MaxInt32 {0}", System.Int32.MaxValue);
       Console.WriteLine( "MaxUInt32 {0}", System.UInt32.MaxValue);
       Console.WriteLine( "MaxInt64 {0}", System.Int64.MaxValue);
       Console.WriteLine( "MaxUInt64 {0}", System.UInt64.MaxValue);
       Console.WriteLine( "MaxChar {0}", System.Char.MaxValue);
       Console.WriteLine( "MaxSingle {0}", System.Single.MaxValue);
       Console.WriteLine( "MaxDouble {0}", System.Double.MaxValue);
       Console.WriteLine( "MaxDecimal {0}", System.Decimal.MaxValue);
  }
}

38 Single.Parse

 
using System;
using System.Data;


class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(int.Parse(IsNum));    
        Console.WriteLine(float.Parse(IsNum));    // 111
      Console.WriteLine(float.Parse(IsFloat));  // 23.11
      //Console.WriteLine(float.Parse(IsExp));  // throws
      
      try
      {
        Console.WriteLine(int.Parse(IsNotNum));
      }
      catch (FormatException e)
      {
        Console.WriteLine("Not a numeric value: {0}", e.ToString());  // throws
      }

        }
}

39 Single.MinValue

 


using System;
class Test {

  public static void Main() {
       // First, print out the minimum values
       Console.WriteLine("System Minimums\n");
       Console.WriteLine( "MinSByte {0}", System.SByte.MinValue);
       Console.WriteLine( "MinByte {0}", System.Byte.MinValue);
       Console.WriteLine( "MinInt16 {0}", System.Int16.MinValue);
       Console.WriteLine( "MinUInt16 {0}", System.UInt16.MinValue);
       Console.WriteLine( "MinInt32 {0}", System.Int32.MinValue);
       Console.WriteLine( "MinUInt32 {0}", System.UInt32.MinValue);
       Console.WriteLine( "MinInt64 {0}", System.Int64.MinValue);
       Console.WriteLine( "MinUInt64 {0}", System.UInt64.MinValue);
       Console.WriteLine( "MinChar {0}", System.Char.MinValue);
       Console.WriteLine( "MinSingle {0}", System.Single.MinValue);
       Console.WriteLine( "MinDouble {0}", System.Double.MinValue);
       // Console.WriteLine( "MinBoolean {0}", System.Boolean.MinValue);
       Console.WriteLine( "MinDecimal {0}", System.Decimal.MinValue);
    
       Console.WriteLine("\nSystem Maximums\n");
       Console.WriteLine( "MaxSByte {0}", System.SByte.MaxValue);
       Console.WriteLine( "MaxByte {0}", System.Byte.MaxValue);
       Console.WriteLine( "MaxInt16 {0}", System.Int16.MaxValue);
       Console.WriteLine( "MaxUInt16 {0}", System.UInt16.MaxValue);
       Console.WriteLine( "MaxInt32 {0}", System.Int32.MaxValue);
       Console.WriteLine( "MaxUInt32 {0}", System.UInt32.MaxValue);
       Console.WriteLine( "MaxInt64 {0}", System.Int64.MaxValue);
       Console.WriteLine( "MaxUInt64 {0}", System.UInt64.MaxValue);
       Console.WriteLine( "MaxChar {0}", System.Char.MaxValue);
       Console.WriteLine( "MaxSingle {0}", System.Single.MaxValue);
       Console.WriteLine( "MaxDouble {0}", System.Double.MaxValue);
       Console.WriteLine( "MaxDecimal {0}", System.Decimal.MaxValue);
  }
}
40 UInt64.MaxValue
 
using System;

class MainClass
{
    public static void Main(string[] args)
    {
    Console.WriteLine("-> ulong.MaxValue: {0}",ulong.MaxValue);
    Console.WriteLine("-> ulong.MinValue: {0}\n",ulong.MinValue);
    }

}