Demonstrate using statement

image_pdfimage_print
   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/


// Demonstrate using statement. 
 
using System; 
using System.IO; 
 
public class UsingDemo { 
  public static void Main() { 
    StreamReader sr = new StreamReader("test.txt"); 
 
    // Use object inside using statement. 
    using(sr) { 
      Console.WriteLine(sr.ReadLine()); 
      sr.Close(); 
    } 
 
    // Create StreamReader inside the using statement. 
    using(StreamReader sr2 = new StreamReader("test.txt")) { 
      Console.WriteLine(sr2.ReadLine()); 
      sr2.Close(); 
    } 
  } 
}

           
          


This version does not include the using System statement

image_pdfimage_print

   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// This version does not include the using System statement. 
 
public class ExampleConsoleWriteLine { 
 
  // A C# program begins with a call to Main(). 
  public static void Main() { 
 
    // Here, Console.WriteLine is fully qualified. 
    System.Console.WriteLine("A simple C# program."); 
  } 
}


           
          


Use unsage code to swap two integers

image_pdfimage_print
   
  


public class TestUnsafeApp
{
    unsafe public static void Swap(int* pi, int* pj)
    {
        int tmp = *pi;
        *pi = *pj;
        *pj = tmp;
    }
   
    public static void Main(string[] args)
    {
        int i = 3;
        int j = 4;
        Console.WriteLine("BEFORE: i = {0}, j = {1}", i, j);
   
        unsafe { Swap(&i, &j); }
   
        Console.WriteLine("AFTER:  i = {0}, j = {1}", i, j);
    }
}

   
     


mark method as unsafe

image_pdfimage_print

class FixedArrayApp
{
unsafe public static void Foo(int* pa)
{
for (int* ip = pa; ip < (pa+5); ip++) { Console.Write("{0,-3}", *ip); } } static void Main(string[] args) { int[] ia = new int[5]{12,34,56,78,90}; unsafe { fixed (int* pa = ia) { Foo(pa); } } } } [/csharp]

unsafe and fixed block

image_pdfimage_print
   
  

public class MyValue
{
    public int id;
    public MyValue(int id) { this.id = id; }
}
   
class UnsafeClassApp
{
    unsafe public static void Swap(int* pi, int* pj)
    {
        int tmp = *pi;
        *pi = *pj;
        *pj = tmp;
    }
   
    static void Main(string[] args)
    {
        MyValue i = new MyValue(123);
        MyValue j = new MyValue(456);
        Console.WriteLine("Before Swap:	i = {0}, j = {1}", i.id, j.id);
   
        unsafe
        {
             (int* pi = &amp;i.id, pj = &amp;j.id)
            {
                Swap(pi, pj);
            }
        }
   
        Console.WriteLine(
            "After Swap:	i = {0}, j = {1}", i.id, j.id);
    }
}