c# Comments

c# Comments

  Data Types C# Value Typesboolbyte, sbytecharshort, ushort, int, uint, long, ulongfloat, double, decimalstructures, enumerations Reference Typesobject    (superclass of all other classes)stringarrays, classes, interfaces, delegates Convertions // int to string int x = 123; String y = x.ToString();  // y is "123" // string to inty = "456"; x = int.Parse(y);   // or x = Convert.ToInt32(y); // double to intdouble z = 3.5; x = (int) z;   // x is 3  (truncates decimal)   Constants C# const double PI = 3.14; // Can be set to a const or a variable. May be initialized in a constructor. readonly int MAX_HEIGHT = 9;   Enumerations C# enum Action {Start, Stop, Rewind, Forward}; enum Status {Flunk = 50, Pass = 70, Excel = 90}; No equivalent.Action a = Action.Stop;if (a != Action.Start)  Console.WriteLine(a);             // Prints "Stop" Status s = Status.Pass;Console.WriteLine((int) s);       // Prints "70"   Operators C# Comparison==  <  >  <=  >=  != Arithmetic+  -  *  /%  (mod)/   (integer division if both operands are ints)Math.Pow(x, y) Assignment=  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  -- Bitwise&  |  ^   ~  <<  >> Logical&&  ||  &  |   ^   ! Note: && and || perform short-circuit logical evaluations String Concatenation+   Choices C# greeting = age < 20 ? "What"s up?" : "Hello"; if (x < y)    Console.WriteLine("greater"); if (x != 100) {      x *= 5;   y *= 2; } else   z *= 6;string color = "red";switch (color) {                          // Can be any predefined type  case "red":    r++;    break;       // break is mandatory; no fall-through  case "blue":   b++;   break;   case "green": g++;   break;   default: other++;     break;       // break necessary on default}   Loops C# while (i < 10)   i++;for (i = 2; i <= 10; i += 2)   Console.WriteLine(i); do   i++; while (i < 10); foreach (int i in numArray)    sum += i; // foreach can be used to iterate through any collection using System.Collections;ArrayList list = new ArrayList();list.Add(10);list.Add("Bisons");list.Add(2.3);foreach (Object o in list)  Console.WriteLine(o);   Arrays C# int[] nums = {1, 2, 3};for (int i = 0; i < nums.Length; i++)  Console.WriteLine(nums[i]);string[] names = new string[5];names[0] = "David";float[,] twoD = new float[rows, cols];twoD[2,0] = 4.5f; int[][] jagged = new int[3][] {    new int[5], new int[2], new int[3] }; jagged[0][4] = 5;   Functions C# // Return single valueint Add(int x, int y) {    return x + y; } int sum = Add(2, 3); // Return no valuevoid PrintSum(int x, int y) {    Console.WriteLine(x + y); } PrintSum(2, 3);  // Pass by value (default), in/out-reference (ref), and out-reference (out) void TestFunc(int x, ref int y, out int z, Point p1, ref Point p2) {    x++;  y++;  z = 5;    p1.x++;       // Modifying property of the object         p1 = null;    // Remove local reference to object    p2 = null;   // Free the object } class Point {    public int x, y; } Point p1 = new Point(); Point p2 = new Point(); p1.x = 2; int a = 1, b = 1, c;   // Output param doesn"t need initializing TestFunc(a, ref b, out c, p1, ref p2); Console.WriteLine("{0} {1} {2} {3} {4}",    a, b, c, p1.x, p2 == null);   // 1 2 5 3 True // Accept variable number of argumentsint Sum(params int[] nums) {  int sum = 0;  foreach (int i in nums)    sum += i;  return sum;} int total = Sum(4, 3, 2, 1);   // returns 10   Strings C# // String concatenationstring school = "Harding "; school = school + "University";   // school is "Harding University" // String comparisonstring mascot = "Bisons"; if (mascot == "Bisons")    // trueif (mascot.Equals("Bisons"))   // trueif (mascot.ToUpper().Equals("BISONS"))   // trueif (mascot.CompareTo("Bisons") == 0)    // true Console.WriteLine(mascot.Substring(2, 3));    // Prints "son" // My birthday: Oct 12, 1973DateTime dt = new DateTime(1973, 10, 12);string s = "My birthday: " + dt.ToString("MMM dd, yyyy"); // Mutable string System.Text.StringBuilder buffer = new System.Text.StringBuilder("two "); buffer.Append("three "); buffer.Insert(0, "one "); buffer.Replace("two", "TWO"); Console.WriteLine(buffer);     // Prints "one TWO three"   Exception Handling C# Exception up = new Exception("Something is really wrong."); throw up;  // ha ha try {  y = 0;   x = 10 / y;} catch (Exception ex) {      // Variable "ex" is optional  Console.WriteLine(ex.Message); } finally {  // Code that always gets executed}   Namespaces C# namespace Harding.Compsci.Graphics {  ...} or namespace Harding {  namespace Compsci {    namespace Graphics {      ...    }  }} // Import all class. Can"t import single class.using Harding.Compsci.Graphics;   Classes / Interfaces C# Accessibility keywords publicprivateinternalprotectedprotected internalstatic // Inheritanceclass FootballGame : Competition {  ...} // Interface definitioninterface IAlarmClock {  ...} // Extending an interface interface IAlarmClock : IClock {  ...} // Interface implementationclass WristWatch : IAlarmClock, ITimer {   ...}   Constructors / Destructors C# class SuperHero {  private int mPowerLevel;  public SuperHero() {     mPowerLevel = 0;  }  public SuperHero(int powerLevel) {    this.mPowerLevel= powerLevel;   }  ~SuperHero() {    // Destructor code to free unmanaged resources.    // Implicitly creates a Finalize method.  }}   Objects C# SuperHero hero = new SuperHero(); hero.Name = "SpamMan"; hero.PowerLevel = 3; hero.Defend("Laura Jones");SuperHero.Rest();   // Calling static method SuperHero hero2 = hero;   // Both refer to same object hero2.Name = "WormWoman"; Console.WriteLine(hero.Name);   // Prints WormWoman hero = null ;   // Free the object if (hero == null)  hero = new SuperHero(); Object obj = new SuperHero(); Console.WriteLine("object"s type: " + obj.GetType().ToString()); if (obj is SuperHero)   Console.WriteLine("Is a SuperHero object.");   Properties C# private int mSize; public int Size {   get { return mSize; }   set {     if (value < 0)       mSize = 0;     else       mSize = value;   } } shoe.Size++;   Structs C# struct StudentRecord {  public string name;  public float gpa;  public StudentRecord(string name, float gpa) {    this.name = name;    this.gpa = gpa;  }}StudentRecord stu = new StudentRecord("Bob", 3.5f);StudentRecord stu2 = stu;  stu2.name = "Sue";Console.WriteLine(stu.name);    // Prints "Bob"Console.WriteLine(stu2.name);   // Prints "Sue"   Console I/O C# Console.Write("What"s your name? ");string name = Console.ReadLine();Console.Write("How old are you? ");int age = Convert.ToInt32(Console.ReadLine());Console.WriteLine("{0} is {1} years old.", name, age);// orConsole.WriteLine(name + " is " + age + " years old."); int c = Console.Read();  // Read single charConsole.WriteLine(c);    // Prints 65 if user enters "A" // The studio costs $499.00 for 3 months.Console.WriteLine("The {0} costs {1:C} for {2} months. ", "studio", 499.0, 3); // Today is 06/25/2004Console.WriteLine("Today is " + DateTime.Now.ToShortDateString());   File I/O C# using System.IO; // Character stream writingStreamWriter writer = File.CreateText("c:\myfile.txt"); writer.WriteLine("Out to file."); writer.Close(); // Character stream readingStreamReader reader = File.OpenText("c:\myfile.txt"); string line = reader.ReadLine(); while (line != null) {  Console.WriteLine(line);   line = reader.ReadLine(); } reader.Close(); // Binary stream writingBinaryWriter out = new BinaryWriter(File.OpenWrite("c:\myfile.dat")); out.Write("Text data"); out.Write(123); out.Close(); // Binary stream readingBinaryReader in = new BinaryReader(File.OpenRead("c:\myfile.dat")); string s = in.ReadString(); int num = in.ReadInt32(); in.Close();

 

Döküman Arama

Başlık :

Kapat