Formatting Numeric and Date Values Method Description
Quick Reference Format Item Syntax: {index[,alignment] [:format string]} Substring mystring.Substring(ndx, len) string alpha = “abcdef”; index – Specifies element in list of values to which format is applied. // returns “cdef” 1. Data Types alignment – Indicates minimum width (in characters) to display value. string s= alpha.Substring(2); format string – Contains the code that specifies the format of the displayed value. // returns “de” Primitive Size Example Example: String.Format(“Price is: {0:C2}”, 49.95); // output: Price is: $ 49.95 s = alpha.Substring(3,2); string 2 bytes/char s = “reference”; bool b = true; a. Numeric Formatting ToCharArray Places selected characters in a string char 2 bytes ch = ‘a’; Format Pattern Value Description in a char array: byte 1 byte b = 0x78; Specifier short 2 bytes Ival = 54; C or c {0:C2}, 1388.55 $ 1388.55 Currency. String vowel = “aeiou”; int 4 bytes Ival = 540; D or d {0:D5}, 45 00045 Must be integer value. // create array of 5 vowels long 8 bytes ival = 5400; E or e {0,9:E2}, 1388.55 1.39+E003 Must be floating point. char[] c = vowel.ToCharArray(); float 4 bytes val = 54.0F; F or f {0,9:F2}, 1388.55 1388.55 Fixed Point representation. // create array of ‘i’ and ‘o’. double 8 bytes val = 54.0D; N or n {0,9:N1}, 1388.55 1,388.6 Insert commas char[] c = vowel.ToCharArray(2,2); decimal 16 bytes val = 54.0M; P or p {0,9:P3}, .7865 78.650% Converts to percent. R or r {0,9:R}, 3.14159 3.14159 Retains all decimal places. 2. Arrays X or x {0,9:X4}, 31 001f Converts to Hex 4. System.Text.StringBuilder Declaration Example: CultureInfo ci = new CultureInfo("de-DE"); // German culture Constructor int[] numArray = {1903, 1907, 1910}; string curdt = String.Format(ci,"{0:M}",DateTime.Now); // 29 Juni StringBuilder sb = new StringBuilder(); int[] numArray = new int[3]; StringBuilder sb = new StringBuilder(mystring); // 3 rows and 2 columns b. DateTime Formatting: (January 19, 2005 16:05:20) en-US StringBuilder sb = new StringBuilder(mystring,capacity); int[ , ] nums = {{1907, 1990}, {1904, 1986}, {1910, 1980}}; Format Value Displayed Format Value Displayed d 1/19/2005 Y or y January, 2005 mystring – Initial value of StringBuilder object Array Operations capacity – Initial size (characters) of buffer. Array.Sort(numArray); // sort ascending D Wednesday, January t 4:05 PM // Sort begins at element 4 and sorts 10 elements 19, 2005 Using StringBuilderMembers Array.Sort(numArray, 4,10); decimal bmi = 22.2M; // Use one array as a key and sort two arrays f Wednesday, January T 4:05:20 PM int wt=168; string[] values = {“Cary”, “Gary”, “Barbara”}; 19, 2005 4:05:20 PM StringBuilder sb = new StringBuilder(“My weight is ”); string[] keys = {“Grant”, “Cooper”, “Stanwyck”}; sb = sb.Append(wt); // can append number Array.Sort(keys, values); F Wednesday, January s 2005-01-19T16:05:20 sb= sb.Append(“ and my bmi is ”).Append(bmi); // Clear elements in array (array, 1st element, # elements) 19, 2005 4:05 PM // my weight is 168 and my bmi is 22.2 Array.Clear(numArray, 0, numArray.Length); sb= sb.Replace(“22.2”,”22.4”); // Copy elements from one array to another g 1/19/2005 4:05 PM u 2005-01-19 16:05:20Z string s = sb.ToString(); Array.Copy(src, target, numelements); // Clear and set to new value G 1/19/2005 4:05:20 PM U Wednesday, January 19, 2005 21:05:20PM sb.Length=0; 3. String Operations sb.Append(“Xanadu”); M or m January 19 Method Description 5. DateTime and TimeSpan Compare String.Compare(stra, strb, case, ci) bool case – true for case insensitive 7. Using the System.Text.RegularExpressions.Regex class DateTime Constructor ci – new CultureInfo(“en-US”) DateTime(yr, mo, day) returns: <0 if a<b, 0 if a=b, 1 if a>b string zipexp = @"\d{5}((-|\s)?\d{4})?$"; string addr="W.44th St, New York, NY 10017-0233"; DateTime(yr, mo, day, hr, min, sec) IndexOf str.IndexOf(val, start, num) Match m = Regex.Match(addr,zipexp); // Static method Regex zipRegex= new Regex(zipexp); DateTime bday = new DateTime(1964,12,20,11,2,0); val – string to search for DateTime newyr= DateTime.Parse(“1/1/2005”); start – where to begin in string m= zipRegex.Match(addr); // Use Regex Object Console.WriteLine(m.Value); // 10017-0233 DateTime currdt = DateTime.Now; num – number of chars to search // also AddHours, AddMonths, AddYears returns (–1) if no match. DateTime tomorrow = currdt.AddDays(1); Pattern Description Example TimeSpan diff = currdt.Subtract(bday); LastIndexOf Search from end of string. + Match one or more occurrence ab+c matches abc, abbc // 14795 days from 12/20/64 to 6/24/05 * Match zero or more occurrences ab*c matches ac, abbc Console.WriteLine(“{0}”, diff.Days); Replace newstr= oldstr.Replace(“old”,”new”); ? Matches zero or one occurrence ab?c matches ac, abc \d \D Match decimal digit or non-digit (\D) \d\d matches 01, 55 // TimeSpan(hrs, min, sec) Split Char[] delim= {‘ ‘, ‘,’}; \w \W Match any word character or non-char \w equals [a-zA-Z0-9_] TimeSpan ts = new TimeSpan(6, 30, 10); string w = “Kim, Joanna Leslie”; \s \S Match whitespace or non-whitespace \d*\s\d+ matches 246 98 // also FromMinutes, FromHours, FromDays // create array with three names [ ] Match any character in set [aeiou]n matches in, on TimeSpan ts = TimeSpan.FromSeconds(120); string[] names= w.Split(delim); [^ ] Match any character not in set [^aeiou] matches r or 2 TimeSpan ts = ts2 – ts1; // +,-,>,<,==, != a|b Either a or b jpg|jpeg|gif matches .jpg \n \r \t New line, carriage return, tab Loop Constructs (Continued) 8. Using the C# Compiler at the Command Line 11. Delegates and Events for (initializer; for (int i=0;i<8;i++) C:\>csc /t:library /out:reslib.dll mysource.cs Delegates termination condition; { csc /t:winexe /r:ctls1.dll /r:ctls2.dll winapp.cs [modifiers] delegate result-type delegate name ([parameter list]); iteration;) tot += i; csc /keyfile:strongkey.snk secure.cs { // statements } } // (1) Define a delegate that calls method(s) having a single string parameter Option Description public delegate void StringPrinter(string s); foreach (type identifier in int[] ages = {27, 33, 44}; /addmodule Import metadata from a file that does // (2) Register methods to be called by delegate collection) foreach(int age in ages) not contain a manifest. StringPrinter prt = new StringPrinter(PrintLower); { // statements } { tot += age; } prt += new StringPrinter(PrintUpper); /debug Tells compiler to emit debugging info. prt(“Copyright was obtained in 2005”); / / execute PrintLower and PrintUpper 10. C# Class Definition /doc Specifies an XML documentation file Using Anonymous Methods with a Delegate Class to be created during compilation. Rather than calling a method, a delegate encapsulates code that is executed: [public | protected | internal | private] /keyfile prt = delegate(string s) { Console.WriteLine(s.ToLower()); }; [abstract | sealed | static] Specifies file containing key used to prt += delegate(string s) { Console.WriteLine(s.ToUpper()); }; class class name [:class/interfaces inherited from] create a strong named assembly. prt(“Print this in lower and upper case.”); /lib Specifies directory to search for Constructor external referenced assemblies. Events [access modifier] class name (parameters) [:initializer] // class.event += new delegate(event handler method); /out Name of compiled output file. Button Total = new Button(); initializer – base calls constructor in base class. Total.Click += new EventHandler(GetTotal); this calls constructor within class. /reference (/r) Reference to an external assembly. // Event Handler method must have signature specified by delegate private void GetTotal( object sender, EventArgs e) { public class Shirt: Apparel { /resource Resource file to embed in output. public Shirt(decimal p, string v) : base(p,v) Commonly used Control Events { constructor body } /target (/t) /t:exe /t:library /t:module /t:winexe Event Delegate Method Click, MouseEnter EventHandler( object sender, EventArgs e) [access modifier] DoubleClick, MouseLeave [static | virtual | override | new | sealed | abstract ] 9. C# Language Fundamentals MouseDown, Mouseup, MouseEventHandler(object sender, method name (parameter list) { body } MouseMove MouseEventArgs e) Control Flow Statements e.X, e.Y – x and y coordinates virtual – method can be overridden in subclass. e.Button – MouseButton.Left, Middle, Right override – overrides virtual method in base class. switch (expression) switch (genre) new – hides non-virtual method in base class. { case expression: { KeyUp, KeyDown KeyEventHandler(object sndr, KeyEventArgs e) sealed – prevents derived class from inheriting. // statements case “vhs”: e.Handled – Indicates whether event is handled. abstract – must be implemented by subclass. break / goto / return() price= 10.00M; e.KeyCode – Keys enumeration, e.g., Keys.V case ... break; e.Modifiers – Indicates if Alt, Ctrl, or Shift key. Passing Parameters: default: case “dvd”: KeyPress KeyPressEventHandler(object sender, a. By default, parameters are passed by value. // statements price=16.00M; KeyPressEventArgs e) b. Passing by reference: ref and out modifiers break / goto / return() break; } default: string id= “gm”; // caller initializes ref 12. struct expression may be price=12.00M: int weight; // called method initializes integer, string, or enum. break; GetFactor(ref id, out weight); } [attribute][modifier] struct name [:interfaces] { struct-body} // ... other code here static void GetFactor(ref string id, out int wt) if (condition) { Differences from class: if (genre==”vhs”) { // statements price=10.00M; • is a value type • cannot inherit from a class or be inherited if (id==”gm”) wt = 454; else wt=1; } else { else if (genre==”dvd”) • fields cannot have initializer • explicit constructor must have a parameter return; // statements price=16.00M; } } else price=12.00M; 13. enum (Enumerated Type) Property Loop Constructs enum enum Operations [modifier] <datatype> property name { public string VendorName enum Fabric: int { int cotNum = (int) Fabric.cotton; // 1 { while (condition) while ( ct < 8) cotton = 1, string cotName = Fabric.cotton.ToString(); // cotton { body } { tot += ct; ct++; } get { return vendorName; } silk = 2, string s = Enum.GetName(typeof(Fabric),2); // silk set { vendorName = value; } // note value keyword wool = 4, // Create instance of wool enum if it is valid } do { body } do { tot += ct; ct++;} rayon = 8 if(Enum.IsDefined(typeof(Fabric), “wool”) Fabric woolFab while (condition); while (ct < 8); } = (Fabric)Enum.Parse(typeof(Fabric),”wool”);