Csharp/C Sharp/Language Basics/Variable Definition

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

An attempt to reference an uninitialized variable

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example2_4.cs shows an attempt to reference an
  uninitialized variable
*/
public class Example2_4
{
  public static void Main()
  {
    int myValue;
    System.Console.WriteLine(myValue);  // causes an error
  }
}


A promotion surprise

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// A promotion surprise!  
  
using System;  
  
public class PromDemo {     
  public static void Main() {     
    byte b;  
    
    b = 10;  
    b = (byte) (b * b); // cast needed!!  
  
    Console.WriteLine("b: "+ b);  
  }     
}


Create a 4-bit type called Nybble

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Create a 4-bit type called Nybble. 
 
using System;  
  
// A 4-bit type. 
class Nybble {  
  int val; // underlying storage 
 
  public Nybble() { val = 0; }  
 
  public Nybble(int i) { 
    val = i; 
    val = val & 0xF; // retain lower 4 bits 
  } 
  
  // Overload binary + for Nybble + Nybble.  
  public static Nybble operator +(Nybble op1, Nybble op2)  
  {  
    Nybble result = new Nybble();  
  
    result.val = op1.val + op2.val;  
 
    result.val = result.val & 0xF; // retain lower 4 bits  
  
    return result;  
  }  
  
  // Overload binary + for Nybble + int.  
  public static Nybble operator +(Nybble op1, int op2)  
  {  
    Nybble result = new Nybble();  
  
    result.val = op1.val + op2;  
 
    result.val = result.val & 0xF; // retain lower 4 bits  
  
    return result;  
  }  
  
  // Overload binary + for int + Nybble.  
  public static Nybble operator +(int op1, Nybble op2)  
  {  
    Nybble result = new Nybble();  
  
    result.val = op1 + op2.val;  
 
    result.val = result.val & 0xF; // retain lower 4 bits  
  
    return result;  
  }  
  
  // Overload ++. 
  public static Nybble operator ++(Nybble op) 
  { 
    op.val++; 
 
    op.val = op.val & 0xF; // retain lower 4 bits 
 
    return op; 
  } 
 
  // Overload >. 
  public static bool operator >(Nybble op1, Nybble op2) 
  { 
    if(op1.val > op2.val) return true; 
    else return false; 
  } 
 
  // Overload <. 
  public static bool operator <(Nybble op1, Nybble op2) 
  { 
    if(op1.val < op2.val) return true; 
    else return false; 
  } 
 
  // Convert a Nybble into an int. 
  public static implicit operator int (Nybble op) 
  { 
    return op.val; 
  } 
 
  // Convert an int into a Nybble. 
  public static implicit operator Nybble (int op) 
  { 
    return new Nybble(op); 
  } 
}  
  
public class NybbleDemo {  
  public static void Main() {  
    Nybble a = new Nybble(1);  
    Nybble b = new Nybble(10);  
    Nybble c = new Nybble();  
    int t; 
  
    Console.WriteLine("a: " + (int) a); 
    Console.WriteLine("b: " + (int) b); 
 
    // use a Nybble in an if statement 
    if(a < b) Console.WriteLine("a is less than b\n"); 
 
    // Add two Nybbles together 
    c = a + b; 
    Console.WriteLine("c after c = a + b: " + (int) c); 
 
    // Add an int to a Nybble 
    a += 5; 
    Console.WriteLine("a after a += 5: " + (int) a); 
 
    Console.WriteLine(); 
 
    // use a Nybble in an int expression 
    t = a * 2 + 3; 
    Console.WriteLine("Result of a * 2 + 3: " + t); 
     
    Console.WriteLine(); 
 
    // illustrate int assignment and overflow 
    a = 19; 
    Console.WriteLine("Result of a = 19: " + (int) a); 
     
    Console.WriteLine(); 
 
    // use a Nybble to control a loop     
    Console.WriteLine("Control a for loop with a Nybble."); 
    for(a = 0; a < 10; a++) 
      Console.Write((int) a + " "); 
 
    Console.WriteLine(); 
  }  
}


Create an implication operator in C#

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Create an implication operator in C#. 
using System; 
 
public class Implication {  
  public static void Main() {    
    bool p=false, q=false; 
    int i, j; 
 
    for(i = 0; i < 2; i++) { 
      for(j = 0; j < 2; j++) { 
        if(i==0) p = true; 
        if(i==1) p = false; 
        if(j==0) q = true; 
        if(j==1) q = false; 
         
        Console.WriteLine("p is " + p + ", q is " + q); 
        if(!p | q) Console.WriteLine(p + " implies " + q + 
                    " is " + true);   
        Console.WriteLine(); 
      } 
    } 
  } 
}


declaring a reference type variable and creating an object the variable will reference

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// RefType.cs -- Demonstrate declaring a reference type variable
//               and creating an object the variable will reference.
//
//               Compile this program with the following command line:
//                   C:>csc RefType.cs
using System;
using System.IO;
namespace nsRefType
{
    public class RefType123
    {
        static public void Main ()
        {
// Declare the reference type variable
            FileStream strm;
// Create the object the variable will reference
            strm = new FileStream ("./File.txt",
                                   FileMode.OpenOrCreate,
                                   FileAccess.Write);
        }
    }
}


Declaring a variable.

 

class MainClass {
    public static void Main() {
        short x;
        int y;
        double z = 0;
        x = 6;
        y = 10;
        z = x + y;
        System.Console.WriteLine("X = {0} Y = {1} Z = {2}", x, y, z);
    }
}


Definite Assignment and Arrays

using System;
struct Complex
{
    public Complex(float real, float imaginary) 
    {
        this.real = real;
        this.imaginary = imaginary;
    }
    public override string ToString()
    {
        return(String.Format("({0}, {0})", real, imaginary));
    }
    
    public float    real;
    public float    imaginary;
}
public class DefiniteAssignmentandArrays
{
    public static void Main()
    {
        Complex[]    arr = new Complex[10];
        Console.WriteLine("Element 5: {0}", arr[5]);        // legal
    }
}


Demonstrate block scope

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate block scope. 
 
using System; 
 
public class ScopeDemo { 
  public static void Main() { 
    int x; // known to all code within Main() 
 
    x = 10; 
    if(x == 10) { // start new scope
      int y = 20; // known only to this block 
 
      // x and y both known here. 
      Console.WriteLine("x and y: " + x + " " + y); 
      x = y * 2; 
    } 
    // y = 100; // Error! y not known here  
 
    // x is still known here. 
    Console.WriteLine("x is " + x); 
  } 
}


Demonstrate casting

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate casting. 
 
using System; 
 
public class CastDemo {    
  public static void Main() {    
    double x, y; 
    byte b; 
    int i; 
    char ch; 
    uint u; 
    short s; 
    long l; 
 
    x = 10.0; 
    y = 3.0; 
 
    // cast an int into a double 
    i = (int) (x / y); // cast double to int, fractional component lost 
    Console.WriteLine("Integer outcome of x / y: " + i); 
    Console.WriteLine(); 
     
    // cast an int into a byte, no data lost 
    i = 255; 
    b = (byte) i;  
    Console.WriteLine("b after assigning 255: " + b + 
                      " -- no data lost."); 
 
    // cast an int into a byte, data lost 
    i = 257; 
    b = (byte) i;  
    Console.WriteLine("b after assigning 257: " + b + 
                      " -- data lost."); 
    Console.WriteLine(); 
 
    // cast a uint into a short, no data lost 
    u = 32000; 
    s = (short) u; 
    Console.WriteLine("s after assigning 32000: " + s + 
                      " -- no data lost.");  
 
    // cast a uint into a short, data lost 
    u = 64000; 
    s = (short) u; 
    Console.WriteLine("s after assigning 64000: " + s + 
                      " -- data lost.");  
    Console.WriteLine(); 
 
    // cast a long into a uint, no data lost 
    l = 64000; 
    u = (uint) l; 
    Console.WriteLine("u after assigning 64000: " + u + 
                      " -- no data lost.");  
 
    // cast a long into a uint, data lost 
    l = -12; 
    u = (uint) l; 
    Console.WriteLine("u after assigning -12: " + u + 
                      " -- data lost.");  
    Console.WriteLine(); 
 
    // cast an int into a char 
    b = 88; // ASCII code for X 
    ch = (char) b; 
    Console.WriteLine("ch after assigning 88: " + ch);  
  }    
}


Demonstrate dynamic initialization

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate dynamic initialization.  
  
using System;  
  
public class DynInit {  
  public static void Main() {  
    double s1 = 4.0, s2 = 5.0; // length of sides 
  
    // dynamically initialize hypot  
    double hypot = Math.Sqrt( (s1 * s1) + (s2 * s2) ); 
  
    Console.Write("Hypotenuse of triangle with sides " + 
                  s1 + " by " + s2 + " is "); 
 
    Console.WriteLine("{0:#.###}.", hypot); 
 
  }  
}


Demonstrate lifetime of a variable

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate lifetime of a variable. 
 
using System; 
 
public class VarInitDemo { 
  public static void Main() { 
    int x;  
 
    for(x = 0; x < 3; x++) { 
      int y = -1; // y is initialized each time block is entered 
      Console.WriteLine("y is: " + y); // this always prints -1 
      y = 100;  
      Console.WriteLine("y is now: " + y); 
    } 
  } 
}


Demonstrate the use of readonly variables

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// ReadOnly.cs -- demonstrate the use of readonly variables
//
//                Compile this program with the following command line
//                    C:>csc ReadOnly.cs
//
namespace nsReadOnly
{
    using System;
    
    public class ReadOnly
    {
        static double DegreeFactor = 1;
        static double MilFactor = 0.05625;
        static public void Main ()
        {
            double degrees = 42;
            
            // 1 degree = 17.77778 mils
            double mils = degrees * 17.77778;
            
            // 1 degree = 0.017453 radians
            double radians = degrees * 0.017453;
            clsArea InDegrees = new clsArea (DegreeFactor);
            InDegrees.Angle = degrees;
            InDegrees.Radius = 50;
            Console.WriteLine ("Area of circle is {0,0:F1}", InDegrees.Area);
            // Radians are the default, so you can use the parameterless 
            // constructor
            clsArea InRadians = new clsArea ();
            InRadians.Angle = radians;
            InRadians.Radius = 50;
            Console.WriteLine ("Area of circle is {0,0:F1}", InRadians.Area);
            clsArea InMils = new clsArea (MilFactor);
            InMils.Angle = mils;
            InMils.Radius = 50;
            Console.WriteLine ("Area of circle is {0,0:F1}", InMils.Area);
        }
    }
    class clsArea
    {
        public clsArea ()
        {
        }
        public clsArea (double factor)
        {
            m_Factor = factor / 57.29578;
        }
        private const double pi = 3.14159;
        private const double radian = 57.29578;
        private readonly double m_Factor = 1;
        public double Angle
        {
            get {return (m_Angle);}
            set {m_Angle = value;}
        }
        public double Radius
        {
            get {return (m_Radius);}
            set {m_Radius = value;}
        }
        private double m_Angle;
        private double m_Radius;
        public double Area
        {
            get
            {
               return (m_Radius * m_Radius * pi * m_Angle * m_Factor /  (2 * pi));
            }
        }
    }
}


Heap and Stack Memory

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 */
using System;
namespace Client.Chapter_7___References__Pointers_and_Memory_Management
{
  public class HeapandStackMemory
  {
    static void Main(string[] args)
    {
      MyClass ThisClass = new MyClass();
    }
  }
  public class MyClass
  {
    public int MyInt;
    private long MyLong;
    public void DoSomething()
    {
      Console.WriteLine(MyInt);
      Console.WriteLine(MyLong);
    }
  }
}


Illustrates variable scope

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example2_6.cs illustrates scope
*/
public class Example2_6
{
  public static void Main()
  {
    {
      int myValue = 1;
    }
    myValue = 2;  // causes error
  }
}


Initializing a variable.

 
using System;
class MainClass{
    public static void Main() {
        // Initialize a variable at declaration
        short x = 5;
        // Initialize a variable as a copy of another
        int y = x;
        double z = y + 10.25;
        int a = (int)z;
        Console.WriteLine("X = {0} Y = {1} Z = {2}", x, y, z);
        Console.WriteLine("A = {0}", a);
    }
}


Init variable

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example2_5.cs is the same as Example2_4.csc, except
  myValue is assigned a value before it is referenced
*/
public class Example2_5
{
  public static void Main()
  {
    int myValue = 2;
    System.Console.WriteLine(myValue);  // no error
  }
}


Int, float, double, decimal

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 public class IntFloatDoubleDecValues
 {
     static void Main()
     {
         int firstInt, secondInt;
         float firstFloat, secondFloat;
         double firstDouble, secondDouble;
         decimal firstDecimal, secondDecimal;
         firstInt = 17;
         secondInt = 4;
         firstFloat = 17;
         secondFloat = 4;
         firstDouble = 17;
         secondDouble = 4;
         firstDecimal = 17;
         secondDecimal = 4;
         Console.WriteLine("Integer:\t{0}\nfloat:\t\t{1}",
             firstInt/secondInt, firstFloat/secondFloat);
         Console.WriteLine("double:\t\t{0}\ndecimal:\t{1}",
             firstDouble/secondDouble, firstDecimal/secondDecimal);
         Console.WriteLine(
           "\nRemainder(modulus) from integer division:\t{0}",
             firstInt%secondInt);
     }
 }


This program attempts to declared a variable in an inner scope

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
/*  
   This program attempts to declared a variable 
   in an inner scope with the same name as one 
   defined in an outer scope. 
 
   *** This program will not compile. *** 
*/  
 
using System; 
 
public class NestVar {  
  public static void Main() {  
    int count;  
 
    for(count = 0; count < 10; count = count+1) { 
      Console.WriteLine("This is count: " + count);  
     
      int count; // illegal!!! 
      for(count = 0; count < 2; count++) 
        Console.WriteLine("This program is in error!"); 
    } 
  }  
}


Two reference type variables may refer (or point) to the same object

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
/*
    Refs1.cs - Shows that two reference type variables may refer (or point)
               to the same object. Changing the object using one variable
               changes the object for the other variable.
            Compile this program with the following command line:
                csc refs1.cs
 */
namespace nsReference
{
    using System;
    public class Refs1
    {
        static public void Main ()
        {
            clsClass first = new clsClass (42);
            clsClass second = first;
            second.m_Var /= 2;
            Console.WriteLine ("first.m_Var = " + first.m_Var);
        }
    }
    class clsClass
    {
        public clsClass (int var)
        {
            m_Var = var;
        }
        public int m_Var;
    }
}


Uninitialized Values

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
// with compile error
public class UninitializedValues
 {
    static void Main( )
    {
       int myInt;
       System.Console.WriteLine
       ("Uninitialized, myInt: {0}",myInt);
       myInt = 5;
       System.Console.WriteLine("Assigned, myInt: {0}", myInt);
    }
 }


Use new with a value type

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use new with a value type. 
 
using System; 
 
public class newValue {  
  public static void Main() {  
    int i = new int(); // initialize i to zero 
 
    Console.WriteLine("The value of i is: " + i); 
  }  
}


Using casts in an expression

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Using casts in an expression.  
  
using System;  
  
public class CastExpr {     
  public static void Main() {     
    double n;  
  
     for(n = 1.0; n <= 10; n++) {  
       Console.WriteLine("The square root of {0} is {1}",  
                         n, Math.Sqrt(n));  
  
       Console.WriteLine("Whole number part: {0}" ,   
                         (int) Math.Sqrt(n));  
   
       Console.WriteLine("Fractional part: {0}",   
                         Math.Sqrt(n) - (int) Math.Sqrt(n) );  
       Console.WriteLine(); 
    }  
  
  }     
}


Variable default name

using System;
class DefValObject
{
  // Here are a number of fields...
  public sbyte  theSignedByte;
  public byte    theByte;
  public short  theShort;
  public ushort  theUShort;
  public int    theInt;
  public uint    theUInt;
  public long    theLong;
  public ulong  theULong;
  public char    theChar;
  public float  theFloat;
  public double  theDouble;
  public bool    theBool;
  public decimal  theDecimal;
  public string  theStr;
  public object  theObj;
    public static int Main(string[] args)
    {
    DefValObject v = new DefValObject();
    // Print out default values.
    Console.WriteLine("bool: {0}", v.theBool);
    Console.WriteLine("byte: {0}", v.theByte);
    Console.WriteLine("char: {0}", v.theChar);
    Console.WriteLine("decimal: {0}", v.theDecimal);
    Console.WriteLine("double: {0}", v.theDouble);
    Console.WriteLine("float: {0}", v.theFloat);
    Console.WriteLine("int: {0}", v.theInt);
    Console.WriteLine("long: {0}", v.theLong);
    Console.WriteLine("object: {0}", v.theObj);
    Console.WriteLine("short: {0}", v.theShort);
    Console.WriteLine("signed byte: {0}", v.theSignedByte);
    Console.WriteLine("string: {0}", v.theStr);
    Console.WriteLine("unsigned int: {0}", v.theUInt);
    Console.WriteLine("unsigned long: {0}", v.theULong);
    Console.WriteLine("unsigned short: {0}", v.theUShort);
        return 0;
    }
}


Variable Scoping and Definite Assignment:Definite Assignment

using System;
struct Complex
{
    public Complex(float real, float imaginary) 
    {
        this.real = real;
        this.imaginary = imaginary;
    }
    public override string ToString()
    {
        return(String.Format("({0}, {1})", real, imaginary));
    }
    
    public float    real;
    public float    imaginary;
}
public class DefiniteAssignment3
{
    public static void Main()
    {
        Complex    myNumber1;
        Complex    myNumber2;
        Complex    myNumber3;
        
        myNumber1 = new Complex();
        Console.WriteLine("Number 1: {0}", myNumber1);
        
        myNumber2 = new Complex(5.0F, 4.0F);
        Console.WriteLine("Number 2: {0}", myNumber2);
        
        myNumber3.real = 1.5F;
        myNumber3.imaginary = 15F;
        Console.WriteLine("Number 3: {0}", myNumber3);
    }
}