C#
Program
Structure
Comments Data Types Constants Enumerations |
Operators
Choices Loops Arrays Functions |
Strings
Exception Handling Namespaces Classes / Interfaces Constructors / Destructors |
Using
Objects
Struts Properties Console I/O File I/O |
|
||||||
using
System;
namespace Hello { public class HelloWorld { public static void Main(string[] args) { string name = "C#"; // See if an argument was passed from the command line if (args.Length == 1) name = args[0]; Console.WriteLine("Hello, " + name + "!"); } } } |
||||||
|
||||||
//
Single line /* Multiple line */ /// <summary>XML comments on single line</summary> /** <summary>XML comments on multiple lines</summary> */ |
||||||
|
||||||
Value
Types bool byte, sbyte char short, ushort, int, uint, long, ulong float, double decimal DateTime (not a built-in C# type) Reference Types object string Initializing bool correct = true; byte b = 0x2A; // hex object person = null; string name = "Dwight"; char grade = 'B'; DateTime today = DateTime.Parse("12/31/2007 12:15:00"); decimal amount = 35.99m; float gpa = 2.9f; double pi = 3.14159265; long lTotal = 123456L; short sTotal = 123; ushort usTotal = 123; uint uiTotal = 123; ulong ulTotal = 123; Type Information int x; Console.WriteLine(x.GetType()); // Prints System.Int32 Console.WriteLine(typeof(int)); // Prints System.Int32 Console.WriteLine(x.GetType().Name); // prints Int32 Type Conversion float d = 3.5f; int i = (int)d; // set to 3 (truncates decimal) |
||||||
|
||||||
|
const int MAX_STUDENTS
= 25;
//
Can set to a const or var; may be initialized in a constructor readonly float MIN_DIAMETER = 4.93f; |
|||||
|
||||||
|
enum Action {Start,
Stop, Rewind, Forward};
enum Status {Flunk = 50, Pass = 70, Excel = 90}; Action a = Action.Stop; if (a != Action.Start) Console.WriteLine(a + " is " + (int) a); // Prints "Stop is 1" Console.WriteLine((int) Status.Pass); // Prints 70 Console.WriteLine(Status.Pass); // Prints Pass |
|||||
|
||||||
|
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 + |
|||||
|
||||||
|
greeting
= age < 20 ?
"What's up?" :
"Hello"; if (age < 20) greeting = "What's up?"; else greeting = "Hello"; // Multiple statements must be enclosed in {} if (x != 100 && y < 5) { x *= 5; y *= 2; } if (x > 5) x *= y; else if (x == 5) x += y; else if (x < 10) x -= y; else x /= y; // Every case must end with break or goto case switch (color) { // Must be integer or string case "pink": case "red": r++; break; case "blue": b++; break; case "green": g++; break; default: other++; break; // break necessary on default } |
|||||
|
||||||
|
Pre-test Loops:
//
no "until" keywordwhile (c < 10) c++; for (c = 2; c <= 10; c += 2) Console.WriteLine(c); Post-test Loop: do c++; while (c < 10); // Array or collection looping string[] names = {"Fred", "Sue", "Barney"}; foreach (string s in names) Console.WriteLine(s); // Breaking out of loops int i = 0; while (true) { if (i == 5) break; i++; } // Continue to next iteration for (i = 0; i < 5; i++) { if (i < 4) continue; Console.WriteLine(i); // Only prints 4 } |
|||||
|
||||||
|
int[] nums = {1, 2,
3}; for (int i = 0; i < nums.Length; i++) Console.WriteLine(nums[i]); // 5 is the size of the array string[] names = new string[5]; names[0] = "David"; names[5] = "Bobby"; // Throws System.IndexOutOfRangeException // C# can't dynamically resize an array. Just copy into new array. string[] names2 = new string[7]; Array.Copy(names, names2, names.Length); // or names.CopyTo(names2, 0); 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; |
|||||
|
||||||
|
// Pass by value (in, default), reference
(in/out), and reference (out)
int a =
1, b = 1, c; // c doesn't need
initializingvoid TestFunc(int x, ref int y, out int z) { x++; y++; z = 5; } TestFunc(a, ref b, out c); Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5 // Accept variable number of arguments int 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 /* C# doesn't support optional arguments/parameters. Just create two different versions of the same function. */ void SayHello(string name, string prefix) { Console.WriteLine("Greetings, " + prefix + " " + name); } void SayHello(string name) { SayHello(name, ""); } |
|||||
|
||||||
|
Escape sequences
//
String concatenation\r // carriage-return \n // line-feed \t // tab \\ // backslash \" // quote string school = "Harding\t"; school = school + "University"; // school is "Harding (tab) University" // Chars char letter = school[0]; // letter is H letter = Convert.ToChar(65); // letter is A letter = (char)65; // same thing char[] word = school.ToCharArray(); // word holds Harding // String literal string msg = @"File is c:\temp\x.dat"; // same as string msg = "File is c:\\temp\\x.dat"; // String comparison string mascot = "Bisons"; if (mascot == "Bisons") // true if (mascot.Equals("Bisons")) // true if (mascot.ToUpper().Equals("BISONS")) // true if (mascot.CompareTo("Bisons") == 0) // true Console.WriteLine(mascot.Substring(2, 3)); // Prints "son" // String matching // No Like equivalent - use regular expressions using System.Text.RegularExpressions; Regex r = new Regex(@"Jo[hH]. \d:*"); if (r.Match("John 3:16").Success) // true // My birthday: Oct 12, 1973 DateTime 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" |
|||||
|
||||||
|
//
Throw an exception Exception up = new Exception("Something is really wrong."); throw up; // ha ha // Catch an exception try { y = 0; x = 10 / y; } catch (Exception ex) { // Argument is optional, no "When" keyword Console.WriteLine(ex.Message); } finally { // Requires reference to the Microsoft.VisualBasic.dll // assembly (pre .NET Framework v2.0) Microsoft.VisualBasic.Interaction.Beep(); } |
|||||
|
||||||
|
namespace
Harding.Compsci.Graphics { ... } // or namespace Harding { namespace Compsci { namespace Graphics { ... } } } using Harding.Compsci.Graphics; |
|||||
|
||||||
|
Accessibility
keywords
public private internal protected protected internal static // Inheritance class FootballGame : Competition { ... } // Interface definition interface IAlarmClock { ... } // Extending an interface interface IAlarmClock : IClock { ... } // Interface implementation class WristWatch : IAlarmClock, ITimer { ... } |
|||||
|
||||||
|
class SuperHero { private int _powerLevel; public SuperHero() { _powerLevel = 0; } public SuperHero(int powerLevel) { this._powerLevel= powerLevel; } ~SuperHero() { // Destructor code to free unmanaged resources. // Implicitly creates a Finalize method } } |
|||||
|
||||||
|
SuperHero hero = new SuperHero();
// No "With" construct
hero.Defend("Laura
Jones");hero.Name = "SpamMan"; hero.PowerLevel = 3; SuperHero.Rest(); // Calling static method SuperHero hero2 = hero; // Both reference the 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(); if (obj is SuperHero) Console.WriteLine("Is a SuperHero object.");
// Mark object for quick disposal
using (StreamReader reader = File.OpenText("test.txt")) { string line; while ((line = reader.ReadLine()) != null) Console.WriteLine(line); } |
|||||
|
||||||
|
struct StudentRecord {
StudentRecord
stu = new StudentRecord("Bob", 3.5f);public string name; public float gpa; public StudentRecord(string name, float gpa) { this.name = name; this.gpa = gpa; } } StudentRecord stu2 = stu; stu2.name = "Sue"; Console.WriteLine(stu.name); // Prints Bob Console.WriteLine(stu2.name); // Prints Sue |
|||||
|
||||||
|
private
int _size;
public int Size { get { return _size; } set { if (value < 0) _size = 0; else _size = value; } } foo.Size++; |
|||||
|
||||||
|
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); // or Console.WriteLine(name + " is " + age + " years old."); int c = Console.Read(); // Read single char Console.WriteLine(c); // Prints 65 if user enters "A" |
|||||
|
||||||
|
using
System.IO; // Write out to text file StreamWriter writer = File.CreateText("c:\\myfile.txt"); writer.WriteLine("Out to file."); writer.Close(); // Read all lines from text file StreamReader reader = File.OpenText("c:\\myfile.txt"); string line = reader.ReadLine(); while (line != null) { Console.WriteLine(line); line = reader.ReadLine(); } reader.Close(); // Write out to binary file string str = "Text data"; int num = 123; BinaryWriter binWriter = new BinaryWriter(File.OpenWrite("c:\\myfile.dat")); binWriter.Write(str); binWriter.Write(num); binWriter.Close(); // Read from binary file BinaryReader binReader = new BinaryReader(File.OpenRead("c:\\myfile.dat")); str = binReader.ReadString(); num = binReader.ReadInt32(); binReader.Close(); |
|||||
Fine
ReplyDelete