Sunteți pe pagina 1din 7

Problem. You need to review syntax and method names in the C# programming language.

View arrays, strings, methods, sorting, and classes. Useful for homework or reference. Solution. This table contains many common tasks in C#, with columns containing the title, description, and example code. Arrays Create new array Initialize array Assign array Check array size Create new array to store values. Create new int or string array with certain values. Set element in array to value. Use array's length property, then access elements. Sort an array alphabetically (A Z). [C# Sort String Arrays dotnetperls.com] Use a two-dimensional array to store a grid of values. [C# 2D Array Use dotnetperls.com]
int[] cat = new int[5]; // cat = 0, 0, 0, 0, 0 string[] s = new string[10]; // s = null, null, ... int[] cat = {1, 4, 6}; string[] a = {"dog", "cat", "plant"}; cat[0] = 3; cat[1] = 4; cat[4] = 7; if (cat.Length == 3) { // 3 elements } string[] a = new string[] { "z", "a", "b" }; Array.Sort(a); // "a", "b", "z" int[,] i = new int[2, 2]; i[0, 0] = 0; i[0, 1] = 1; i[1, 0] = 2; i[1, 1] = 3; // 0, 1 // 2, 3 List<int> e = new List<int>(); e.Add(1); e.Add(2); int[] a = e.ToArray(); // a = 1, 2 List<int> e = new List<int>(); e.Add(1); e.Add(2); foreach (int i in e) { // 1, 2 } int[] a = {5, 6, 1}; Array.Reverse(a); // 1, 6, 5 class C { void Method() { int a = 4; Method2(ref a); // a = 5 }

Sort array

Use 2D array

Use extension method Convert List to ToArray() to convert List to array equivalent array.

Loop through List

Iterate through each item in an array or list.

Reverse array

Reorder elements in array backwards.

Methods Ref parameter Allow another method to directly change value.

void Method2(ref int p) { p = 5; } } class C { void Method() { int a; Method2(out a); // a = 5 } void Method2(out int p) { p = 5; } }

Allow another method to Out parameter directly change value. With compile-time checking.

Strings Divide string into separate parts. string c = "one,two"; string[] s = c.Split(','); Split string [C# Split String Examples // s[0] = "one" dotnetperls.com] // s[1] = "two" Declare a string with newlines string s = @"line 1 line 2 String new lines in it. line 3"; Use "" for a quote. Add strings together (also called string s1 = "cat"; string s2 = "dog"; Combine concatenation). string c = s1 + " and " + s2; strings Use overloaded + operator. // c = "cat and dog"
string s1 = "cat"; string s2 = "dog"; string s3 = "cat"; if (s1 == s2) { // not true } if (s1 == s3) { // success } string s1 = ""; string s2 = null; string s3 = "cat"; if (string.IsNullOrEmpty(s1)) { // true } if (string.IsNullOrEmpty(s2)) { // true } if (string.IsNullOrEmpty(s3)) { // not true } string c = "cat"; if (c.Length == 3) {

Compare strings

See if two strings have equal characters and lengths.

Empty string check

See if string is empty or null (has no value).

Get string length

Find number of characters in string.

Append strings quickly Uppercase entire string Uppercase first letter

Convert string convert it to int value. to int [C# int.Parse for Integer Conversion - dotnetperls.com] Substring of string Remove whitespace Get part of string based on indexes. Trim whitespace at beginning and ending of string. [C# Trim String Tips dotnetperls.com] Modify the letters in string inplace.

// true } StringBuilder b = new Use StringBuilder and convert StringBuilder(); b.Append("Text"); back to string. b.Append(" more"); [C# StringBuilder Secrets string r = b.ToString(); dotnetperls.com] // r = "Text more" string s = "cat"; Uppercase each letter in string. s = s.ToUpper(); // s = "CAT" string s = "cat"; Uppercase the first letter in char[] a = s.ToCharArray(); string. a[0] = char.ToUpper(a[0]); [C# Uppercase First Letter string u = new string(a); dotnetperls.com] // u = "Cat" string s = "105"; Take string containing digits and int i = int.Parse(s); // i = 105 string double // d = string string // b = s2 = "105.5"; d = double.Parse(s2); 105.5 s = "developer"; b = s.Substring(0, 7); "develop"

string s = " cat "; string t = s.Trim(); // t = "cat" string char[] // a[0] = // string // s = "cat"; a = s.ToCharArray(); a = 'c', 'a', 't' 'h'; a = 'h', 'a', 't' s2 = new string(a); s2 = "hat"

Change string characters

Find position of letter in string string s = "word"; using IndexOf. int i = s.IndexOf("r"); Letter position [C# IndexOf String Examples - // i = 2 dotnetperls.com] Classes Declare constructor Cast safely
class C { public C(int a) { Create new constructor for class. // initialize } } Use as operator or is operator. void Method(object a) { Convert from one type to if (a is MyClass) another. { // correct type } } void Method2(object a) {

Null reference

New object

Singleton

Properties Accessors Getters, setters

} Causes exception in programs. string s = null; if (s.Length == 0) Null variable used. { [C# Exception Types // exception raised dotnetperls.com] } class C { // impl. } class Program Create a new object of a kind. { void Main() { C name = new C(); } } class S { private static readonly _inst = new S(); Make a single object. public static S Instance { One instance per AppDomain. get { return _inst; } [C# Singleton Class } dotnetperls.com] S() { // init } } class C { public int P { get; set; } Create properties to access fields } void Method(C name) of classes publicly. { [Visual Studio Encapsulate name.P = 4; Field - dotnetperls.com] int i = name.P; // i = 4 } string[] lines = File.ReadAllLines("file.txt" ); // lines[0] = "..." // lines[1] = "..." string f = File.ReadAllText("file.txt") ; // f = "..." using (StreamReader s = new StreamReader("file.txt"))

MyClass m = a as MyClass; if (m != null) { // correct type }

File IO Read file lines Read in each line of file into array. Read in entire file containing text. [C# File Handling dotnetperls.com] Read file line-by-line with StreamReader.

Read text file Read lines separately

Fastest and lowest memory. [C# Using StreamReader dotnetperls.com]

Append to file Add text to end of file on disk. Write text to file on disk, replacing any existing files. See if folder exists on file Directory exists system. Add using System.IO; Write file File exists Hashtables See if file exists on disk at path.

string t; while ((t = s.ReadLine()) != null) { // t = "..." } } File.AppendAllText("file.txt", "..." + Environment.NewLine); File.WriteAllText("file.txt", "..."); if (Directory.Exists("C:\\f")) { // ... } if (File.Exists("file.txt")) { // ... } Dictionary<string, int> d = new Dictionary<string, int>(); d.Add("cat", 2); d.Add("dog", 4); if (d.ContainsKey("cat")) { // true } if (d.ContainsKey("hat")) { // not true } Dictionary<string, int> d = new Dictionary<string, int>(); d.Add("cat", 2); if (d.ContainsKey("cat")) { int v = d["cat"]; // v = 2 } foreach (KeyValuePair<string, int> p in d) { // p.Key, p.Value }

Use the generic Dictionary Use hashtable object with string keys. Use Dictionary [C# Dictionary Examples, Keys and Values - dotnetperls.com]

Lookup Dictionary value

Get value from hashtable/Dictionary based on key. [C# Dictionary Lookup Overview - dotnetperls.com]

Use KeyValuePair on Dictionary to list each key/value combo. Scan Dictionary Use this style to convert to values string. [C# KeyValuePair Collection Hints - dotnetperls.com] Language Namespaces Current time Put at top of file. Required for some examples. Get current time using

using System; using System.IO; using System.Linq; using System.Text; DateTime d = DateTime.Now;

DateTime. string s = d.ToString(); [C# DateTime Tips and Tricks - // s = "8/20/2008 4:18:52 PM" dotnetperls.com] Write diagnostics message to console. Debug message [C# Debug Write and Assert dotnetperls.com]
using System.Diagnostics; class C { void Method() { Debug.WriteLine("..."); } } enum E { None, Cat, Dog }; void Method() { E name = E.Cat; if (name == E.Dog) { // not true } } for (int i = 0; i < 100; i++) { // 0, 1, 2, 3, ... 99 } try { int i = 1 / 0; } catch (Exception) { // log error } switch(v) { case "cat": case "tiger": { // feline break; } case "dog": default: { // other break; } }

Use constants Enum values

Use enum type to assign names to numbers. [C# Enum Tips and Examples dotnetperls.com]

Loop through numbers

Use the for loop to loop through range of values.

Catch exceptions

Detect errors and try to recover from them.

Switch statement

Compare value against constant values. Faster than if. [C# Switch Statement dotnetperls.com]

Interfaces public interface IName Interfaces Define required methods for Code contracts classes so they can be swapped. { void Method();
} class C : IName {

public void Method() { // ... } } class D : IName { public void Method() { // ... } } void Method() { C name = new C(); Method2((IName)name);

Use classes by their common Use interfaces interfaces. Improves code reuse.

} void Method2(IName i) { // ... }

D name2 = new D(); Method2((IName)name2);

S-ar putea să vă placă și