Buy Electronics

Monday, May 3, 2010

C# programming language

--- Arrays section (C#) ---
 
Create new array
 
Create new array to store values.
 
int[] cat = new int[5];
// cat = 0, 0, 0, 0, 0
 
string[] s = new string[10];
// s = null, null, ...
 
Initialize array
Create new int or string array with certain values.
 
int[] cat = {1, 4, 6};
string[] a = {"dog", "cat", "plant"};
 
Assign array
Set element in array to value.
 
cat[0] = 3;
cat[1] = 4;
cat[4] = 7;
 
Check array size
Use array's length property, then access elements.
 
if (cat.Length == 3)
{
    // 3 elements
}
 
Sort array
Sort an array alphabetically (A - Z).
 
string[] a = new string[]
{
    "z", "a", "b"
};
Array.Sort(a);
// "a", "b", "z"
 
Use 2D array
Use a two-dimensional array to store a grid of values.
 
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
 
Convert List to array
Use instance method ToArray() to convert List to equivalent array.
 
List e = new List();
e.Add(1);
e.Add(2);
int[] a = e.ToArray();
// a = 1, 2
 
Loop through List
Iterate through each item in an array or list.
 
List e = new List();
e.Add(1);
e.Add(2);
foreach (int i in e)
{
    // 1, 2
}
 
Reverse array
Reorder elements in array backwards.
 
int[] a = {5, 6, 1};
Array.Reverse(a);
// 1, 6, 5
 
--- Methods section (C#) ---
 
Ref parameter
Allow another method to directly change value.
 
class C
{
    void Method()
    {
        int a = 4;
        Method2(ref a);
        // a = 5
    }
    void Method2(ref int p)
    {
        p = 5;
    }
}
 
Out parameter
Allow another method to directly change value.
With compile-time checking.
 
class C
{
    void Method()
    {
        int a;
        Method2(out a);
        // a = 5
    }
    void Method2(out int p)
    {
        p = 5;
    }
}
 
--- Strings section (C#) ---
 
Split string
Divide string into separate parts.
 
string c = "one,two";
string[] s = c.Split(',');
// s[0] = "one"
// s[1] = "two"
 
String new lines
Declare a string with newlines in it. Use "" for a quote.
 
string s = @"line 1
line 2
line 3";
 
Combine strings
Add strings together (also called concatenation).
Use overloaded + operator.
 
string s1 = "cat";
string s2 = "dog";
string c = s1 + " and " + s2;
// c = "cat and dog"
 
Compare strings
See if two strings have equal characters and lengths.
 
string s1 = "cat";
string s2 = "dog";
string s3 = "cat";
if (s1 == s2)
{
    // not true
}
if (s1 == s3)
{
    // success
}
 
Empty string check
See if string is empty or null (has no value).
 
string s1 = "";
string s2 = null;
string s3 = "cat";
if (string.IsNullOrEmpty(s1))
{
    // true
}
if (string.IsNullOrEmpty(s2))
{
    // true
}
if (string.IsNullOrEmpty(s3))
{
    // not true
}
 
Get string length
Find number of characters in string.
 
string c = "cat";
if (c.Length == 3)
{
    // true
}
 
Append strings quickly
Use StringBuilder and convert back to string.
 
StringBuilder b = new StringBuilder();
b.Append("Text");
b.Append(" more");
string r = b.ToString();
// r = "Text more"
 
Uppercase entire string
Uppercase each letter in string.
 
string s = "cat";
s = s.ToUpper();
// s = "CAT"
 
Uppercase first letter
Uppercase the first letter in string.
 
string s = "cat";
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
string u = new string(a);
// u = "Cat"
 
Convert string to int
Take string containing digits and convert it to int value.
 
 
string s = "105";
int i = int.Parse(s);
// i = 105
 
string s2 = "105.5";
double d = double.Parse(s2);
// d = 105.5
 
Substring of string
Get part of string based on indexes.
 
string s = "developer";
string b = s.Substring(0, 7);
// b = "develop"
 
Remove whitespace
Trim whitespace at beginning and ending of string.
 
string s = " cat  ";
string t = s.Trim();
// t = "cat"
 
Change string characters
Modify the letters in string in-place.
 
string s = "cat";
char[] a = s.ToCharArray();
    // a = 'c', 'a', 't'
a[0] = 'h';
    // a = 'h', 'a', 't'
string s2 = new string(a);
    // s2 = "hat"
 
 
--- Classes section (C#) ---
 
Declare constructor
Create new constructor for class.
 
class C
{
    public C(int a)
    {
        // initialize
    }
}
 
Cast safely
Use as operator or is operator.
Convert from one type to another.
 
void Method(object a)
{
    if (a is MyClass)
    {
        // correct type
    }
}
void Method2(object a)
{
    MyClass m = a as MyClass;
    if (m != null)
    {
        // correct type
    }
}
 
Null reference
Causes exception in programs. Null variable used.
 
 
string s = null;
if (s.Length == 0)
{
    // exception raised
}
 
New object
Create a new object of a kind.
 
class C
{
    // impl.
}
class Program
{
    void Main()
    {
        C name = new C();
    }
}
 
Singleton
Make a single object. One instance per AppDomain.
 
class S
{
    private static readonly _inst = new S();
    public static S Instance
    {
        get { return _inst; }
    }
    S()
    {
        // init
    }
}
 
Properties, Accessors, Getters, setters
Create properties to access fields of classes publicly.
 
class C
{
    public int P { get; set; }
}
void Method(C name)
{
    name.P = 4;
    int i = name.P;
    // i = 4
}
 
--- File/IO section (C#) ---
 
 
Read file lines
Read in each line of file into array.
 
string[] lines = File.ReadAllLines("file.txt");
// lines[0] = "..."
// lines[1] = "..."
 
 
Read text file
Read in entire file containing text.
 
string f = File.ReadAllText("file.txt");
// f = "..."
 
 
Read lines separately
Read file line-by-line with StreamReader.
Fastest and lowest memory.
 
using (StreamReader s = new StreamReader("file.txt"))
{
    string t;
    while ((t = s.ReadLine()) != null)
    {
        // t = "..."
    }
}
 
 
Append to file
Add text to end of file on disk.
 
File.AppendAllText("file.txt", "..." + Environment.NewLine);
 
Write file
Write text to file on disk, replacing any existing files.
 
File.WriteAllText("file.txt", "...");
 
Directory exists
See if folder exists on file system. Add using System.IO;
 
if (Directory.Exists("C:\\f"))
{
    // ...
}
 
File exists
See if file exists on disk at path.
 
if (File.Exists("file.txt"))
{
    // ...
}
 
--- Hashtables section (C#) ---
 
Use Dictionary
Use the generic Dictionary object with string keys.
 
 
Dictionary d = new Dictionary();
d.Add("cat", 2);
d.Add("dog", 4);
if (d.ContainsKey("cat"))
{
    // true
}
if (d.ContainsKey("hat"))
{
    // not true
}
 
Lookup Dictionary value
Get value from hashtable/Dictionary based on key.
 
 
Dictionary d = new Dictionary();
d.Add("cat", 2);
if (d.ContainsKey("cat"))
{
    int v = d["cat"];
    // v = 2
}
 
Scan Dictionary values
Use KeyValuePair on Dictionary to list each key/value combo.
Use this style to convert to string.
 
 
 
foreach (KeyValuePair p in d)
{
    // p.Key, p.Value
}
 
Use Hashtable
Implements older version of Dictionary, slower but required sometimes.
 
 
Hashtable h = new Hashtable();
h.Add(400, "Blazer");
 
string s = h[400] as string; // Cast
if (s != null) // True
{
    Console.WriteLine(s);
}
 
--- Language section (C#) ---
 
Namespaces
Put at top of file. 
 
using System;
using System.IO;
using System.Linq;
using System.Text;
 
Current time
Get current time using DateTime.
 
 
DateTime d = DateTime.Now;
string s = d.ToString();
// s = "8/20/2008 4:18:52 PM"
 
Debug message
Write diagnostics message to console.
 
 
using System.Diagnostics;
class C
{
    void Method()
    {
        Debug.WriteLine("...");
    }
}
 
Enums
Use enum type to assign names to numbers.
 
 
enum E
{
    None,
    Cat,
    Dog
};
void Method()
{
    E name = E.Cat;
    if (name == E.Dog)
    {
        // not true
    }
}
 
Loop through numbers
Use the for loop to loop through range of values.
 
 
 
for (int i = 0; i <>
{
    // 0, 1, 2, 3, ... 99
}
 
Catch exceptions
Detect errors and try to recover from them.
 
try
{
    int i = 1 / int.Parse("0");
}
catch (Exception)
{
    // log error
}
 
Switch statement
Compare value against constant values. Faster than if.
 
switch(v)
{
    case "cat":
    case "tiger":
        {
            // feline
            break;
        }
    case "dog":
    default:
        {
            // other
            break;
        }
}
 
 
 
 
 
--- Interfaces section (C#) ---
 
Interfaces, code contracts
Define required methods for classes so they can be swapped.
 
public interface IName
{
    void Method();
}
class C : IName
{
    public void Method()
    {
        // ...
    }
}
class D : IName
{
    public void Method()
    {
        // ...
    }
}
 
Use interfaces
Use classes by their common interfaces. Improves code reuse.
 
void Method()
{
    C name = new C();
    Method2((IName)name);
 
    D name2 = new D();
    Method2((IName)name2);
}
void Method2(IName i)
{
    // ...
}

0 comments:

Post a Comment

Tu comentario será moderado la primera vez que lo hagas al igual que si incluyes enlaces. A partir de ahi no ser necesario si usas los mismos datos y mantienes la cordura. No se publicarán insultos, difamaciones o faltas de respeto hacia los lectores y comentaristas de este blog.

Mobiles