C Sharp

From Pigbert Wiki


Table of contents

Data Types

Object.GetType().Name

Value Types

  • Primitive Types:
    • byte, sbyte (8,0)
    • short, ushort (16,0)
    • int, uint (32,0) (32,0U)
      • int n = Convert.ToInt32(s); ToDouble(), ToFloat(), ToBoolean(), ToInt64
      • int n = Int32.Parse(s);
      • 3.ToString();
    • long, ulong (64, 0L)
    • float (32, 0.0F)
    • double (64, 0.0, 0.0D)
    • decimal (128, 5M, 5.5M) accurate float, though 50 times slower
    • bool (8,false)
    • char (16,'\0')
      • Char.IsDigit('2')==true;
    • object
    • string
      • string.Length, Compare(), ToUpper(), Split(), Replace()
      • string.Trim(), Pad(), PadRight(), PadLeft(), Substring(), Concat()
      • String.format("{0} times {1} is {2}", 2, 3, 2*3);
        • {0:C} currency $
        • {0:D5} decimal padded with zero Integers only 123 -> 00123
        • {0:E} exponential
        • {0:F2} fixed float 12.1234 -> 12.12
        • {0:N2} number add , separation' 1234.1234 -> 1,234.12
        • {0:X} hexadecimal
        • {0:000.00} 12.3 -> 012.30
        • {0:###.##} 12.123 -> 12.12
        • {0:#00.#%} .0234 -> 02.3%
      • string = Console.ReadLine();
  • enum:
    • is used to group named constants. Details see System.Enum@MSDN (http://msdn2.microsoft.com/en-us/library/system.enum(VS.80).aspx).
    • enum Priority{Low, Medium, High};
    • to prevent invalid integer parameter when an Enum is required:
if(!Enum.IsDefined(typeof(EnumType),enumVariable))
throw (new InvalidEnumArgumentException("name",(int)enumVariable,typeof(EnumType)));


  • string:
immutable (same as String in Java), meaning that the values cannot be changed once created. So, better to use System.Text.StringBuilder (http://msdn2.microsoft.com/en-us/library/system.text.stringbuilder(VS.80).aspx) for concatenation.
values of strings are comparable using == or !=.
string literals @ can be used to avoid escape sequences. E.g. string path2 = @"\\FileShare\Directory\file.txt";
  • Boxing and Unboxing:
    • Boxing means stuffing a piece of value-type data (int,bool,char,any struct) into a reference-type object on the heap.
    • (C# does Boxing (http://msdn2.microsoft.com/en-us/library/25z57t8s(VS.80).aspx) and Unboxing (http://msdn2.microsoft.com/en-us/library/25z57t8s(VS.80).aspx) in a memory-efficient or stack-preferable way.). Value Types @ MSDN (http://msdn2.microsoft.com/en-us/library/s1ax56ch(VS.80).aspx)
          int i = 999; 
          object o = i;   // boxing, o is in the heap
          int j = (int)o; // unboxing, j is in the stack
      

Reference Types

Variables of reference types, referred to as objects, store references to the actual data. Reference Types (C# Reference) @ MSDN (http://msdn2.microsoft.com/en-us/library/490f96s2(VS.80).aspx).

Delegate

Delegate Class (http://msdn2.microsoft.com/en-us/library/system.delegate(VS.80).aspx), delegate (http://msdn2.microsoft.com/en-us/library/900fyy8e(VS.80).aspx,), Anonymous Methods (http://msdn2.microsoft.com/en-us/library/900fyy8e(VS.80).aspx).

Interface

Interfaces (http://msdn2.microsoft.com/en-us/library/ms173156(VS.80).aspx), interface (http://msdn2.microsoft.com/en-us/library/87d83y5b(VS.80).aspx)

  • Declaration: public interface ISampleInterface{}.
  • Inherit: public class Minivan : Car, IComparable {}
  • Property: string Name { get; set; }
  • Indexer: string this[int index]{ get; set; }
  • Explicit interface member implementation using the fully qualified name of the interface member. E.g. public string IEmployee.this{ ... } public string ICitizen.this{ ... }
Class

class (http://msdn2.microsoft.com/en-us/library/0b0thckt(VS.80).aspx), Objects (http://msdn2.microsoft.com/en-us/library/x53a06bb(VS.80).aspx), Classes (http://msdn2.microsoft.com/en-us/library/x9afc042(VS.80).aspx).

  • None: class ClassA { }
  • Single: class DerivedClass: BaseClass { }
  • None, implements two interfaces: class ImplClass: IFace1, IFace2 { }
  • Single, implements one interface: class ImplDerivedClass: BaseClass, IFace1 { }
  • is: equivalent to instanceof, work with primitive types. if(account1 is SavingsAccount) ...
  • as: converts the type on the left to the type on the right, but safely returns a null if the conversion fails. Does not work with primitive types.
Structs
  • A struct is a simplified object in the stack. When a struct is passed to a method, a copy of the struct is passed, but when a class instance is passed, a reference is passed.
  • Consider defining a structure instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
  • Do not define a structure unless the type has all of the following characteristics:
    • It logically represents a single value, similar to primitive types (integer, double, and so on).
    • It has an instance size smaller than 16 bytes.
    • It is immutable.
    • It will not have to be boxed frequently.
  • Declaration: public struct PostalAddress { // Fields, properties, methods and events go here... }
  • Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
  • A struct is automatically garbage collected. So it may not declare a default constructor — a constructor with no parameters — or a destructor.
  • Default value of a struct is the value produced by setting all value-type fields to their default values and all reference-type fields to null.
  • References: Structs (http://msdn2.microsoft.com/en-us/library/x9afc042(VS.80).aspx), Structs (C# Programming Guide) (http://msdn2.microsoft.com/en-us/library/saxz13w4(VS.80).aspx)


Pointer Types

Pointer types (http://msdn2.microsoft.com/en-us/library/900fyy8e(VS.80).aspx)


 hline-music11.gif


Design

Type Design Guidelines (http://msdn2.microsoft.com/en-us/library/ms229036(VS.80).aspx),

Generics
  • Find the right null value of a generic type T: return default(T);
  • Generic Method::
public static void Swap<T>(ref T a, ref T b){ ... }
public static void Sort<T>(ref T a, ref T b) where T : IComparable<T> { ... }
Swap<int>(ref a, ref b); Swap<string>(ref a, ref b);
  • Generic Interface: interface ICertifiable<T>{ ... }
  • Generic Class: class PriorityQueue<T,U> where T : IPrioritizable, where U : new()
    • class MyClass<T>: where T: MyBase ---- T must be or subclass MyBase
    • class MyClass<T>: where T: MyInterface ---- T must implement MyInterface
    • class MyClass<T>: where T: class ----T can only be a reference type
    • class MyClass<T>: where T: struct ----T can only be a value-type
    • class MyClass<T>: where T: new() ----T must have a parameterless constructor. The new() constraint is required for any generic class or method that wants to create objects of type T.
    • class MyClass<T,U> where T : ISettable<U>, new() ---- factory for creating objects that have a constructor with one parameter
      // factory for creating objects that have a constructor with one parameter
      class GenericFactory <T,U> where T : ISettable<U>, new(){
          public T Create(U u){
              T t = new T();
              t.SetParameter(u); // T must implement ISettable, so it has SetParameter()
              return t;
          }
      }
      
      interface ISettable<U>{ void SetParameter(U u); }
      
      GenericFactory<Student,string> factory - new GenericFactory<Student, string>();
      students[0] = factory.Create("Meowky");
      

Inheritance

Inheritance @ MSDN (http://msdn2.microsoft.com/en-us/library/ms173149(VS.80).aspx).

  • public class B : A
  • abstract: public abstract class A{ public abstract void DoWork(); }
  • sealed: a sealed class cannot be used as a base class. E.g. public sealed class D {}
Polymorphism

Polymorphism @ MSDN (http://msdn2.microsoft.com/en-us/library/ms173152(VS.80).aspx). When a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base class. To change the data and behavior of a base class, you have two choices: you can replace the base member with a new derived member, or you can override a virtual base member.

  • new: the base class members can still be called if an instance of the derived class is cast to an instance of the base class. E.g. public new string ToString(){}.
  • virtual: goes with override. used in the base class to make sure an instance of a derived class will completely take over a class member from a base class. E.g. public virtual void DoWork(){}.
  • override: goes with virtual. used in derived classes to override virtual methods and properties. E.g. public override void DoWork(){}.
  • sealed: a derived class can stop virtual inheritance by declaring an override as sealed. E.g. public sealed override void DoWork() { }.


 hline-music11.gif


Class Members

Members (C# Programming Guide) @ MSDN (http://msdn2.microsoft.com/en-us/library/ms173113(VS.80).aspx)

Fields
  • Accessibility (http://msdn2.microsoft.com/en-us/library/ba0a1yw2(VS.80).aspx)
    • public: no restriction.
    • protected: accessible in the same class hierarchy.doc (http://msdn2.microsoft.com/en-us/library/bcd5672a(VS.80).aspx)
    • internal: accessible in the same assembly (or solution).doc (http://msdn2.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx)
    • protected internal: combines access for protected and internal.
    • private: accessible only within the declaration class.
  • Constants (http://msdn2.microsoft.com/en-us/library/ms173119(VS.80).aspx)
    • readonly: can only be assigned once at run time.
    • static readonly: field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time.
    • const: Constants can only be assigned once at compile time. (= final in Java). They are accessed as if they were static fields, although they cannot use the static keyword.
Properties
Properties (http://msdn2.microsoft.com/en-us/library/x9fsa0sw(VS.80).aspx) are methods on a class that are accessed as if they were fields on that class.
A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. For more information, see Accessor Accessibility.
The value keyword is used to define the value being assigned by the set indexer.
Properties that do not implement a set method are read only.
class TimePeriod{
    private double seconds;
    public double Hours{
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}
class Program{
    static void Main(){
        TimePeriod t = new TimePeriod();
        t.Hours = 24;  // Assigning the Hours property causes the 'set' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);  // Evaluating the Hours property causes the 'get' accessor to be called.
    }
}
Constructors and Destructors
References: Constructors (http://msdn2.microsoft.com/en-us/library/x9afc042(VS.80).aspx), Destructors (http://msdn2.microsoft.com/en-us/library/x9afc042(VS.80).aspx).
  • call base constructor: public SubClass(int i1, int i2) : base(i1){ ... }
  • destructor: ~BaseClass()
Methods
as methods in Java.
  • Multiple return values:
    • ref: variable has to be initialized before use
    • out: variable does not have to be initialized before use
      public void setVariables(ref decimal v1, ref decimal v2, out decimal v3){
          v1 = "meow";
          v2 = "woof";
          v3 = "gobble";
      }
      decimal a1 = 0, a2 = 0, a3;
      setVariables(ref a1, refa2, out a3);
      
* Call super class: base.Method()
Events
  • Events are a way of providing notifications about occurrences, such as button clicks or the successful completion of a method, to other objects.
  • Events are defined and triggered using delegates.
  • References: Events (http://msdn2.microsoft.com/en-us/library/awbftdfh(VS.80).aspx), Events and Delegates (http://msdn2.microsoft.com/en-us/library/awbftdfh(VS.80).aspx).
  • page event model: the sequence of what happens when a page is loading
  • master pages: template for a whole bunch of pages
  • controls: things that you can build that you can put on a page
Operators
Operators can be redefined to perform operations on custom data types.
Operators Overview (http://msdn2.microsoft.com/en-us/library/ms173145(VS.80).aspx), C# Operators (http://msdn2.microsoft.com/en-us/library/6a71f45d(VS.80).aspx), Overloadable Operators (http://msdn2.microsoft.com/en-us/library/ms173145(VS.80).aspx)
  • &, |: if the first expression is false/true, the second expression is still evaluated.
  • ^: logical XOR. Console.WriteLine("0x{0:x}", 0xf8 ^ 0x3f);
  • ??: returns the left-hand operand if it is not null, or else it returns the right operand.
Indexers
  • Indexers enable objects to be indexed in a similar way to arrays.
  • A get accessor returns a value. A set accessor assigns a value.
  • The this keyword is used to define the indexers.
  • The value keyword is used to define the value being assigned by the set indexer.
  • Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.
  • Indexers can be overloaded.
  • Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.
  • Indexers @ MSDN (http://msdn2.microsoft.com/en-us/library/6x16t2tx(VS.80).aspx)
class SampleCollection<T>{
    private T[] arr = new T[100];
    public T this[int i] {
        get { return arr[i]; }
        set { arr[i] = value; }
    }
}
class Program{
    static void Main(string[] args){
        SampleCollection<string> stringCollection = new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}
Nested/Inner Types
  • Nested Types are types declared within a class or struct.
  • Nested Types are often used to describe objects used only by the types containing them.
  • Public nested class is accessible outside using the full name. E.g. Container.Nested nest = new Container.Nested();
  • Reference: Nested Types @ MSDN (http://msdn2.microsoft.com/en-us/library/ms173120(VS.80).aspx).
public class Container{
    public class Nested{
        private Container m_parent;
        public Nested(){}
        public Nested(Container parent){
            m_parent = parent;
        }
    }
}


 hline-music11.gif


I/O

  • System.Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);

good tutorial on FileStream (http://www.aspfree.com/c/a/C-Sharp/C-Sharp-FileStream-Explained/1/)

  • FileStream seekable
  • StreamReader
  • StreamWriter

String

string formatting (http://blog.stevex.net/string-formatting-in-csharp/) The primary formatting function is String.Format(); the text inside the curly braces is {index[,alignment][:formatString]}.

  • If alignment is positive, the text is right-aligned in a field the given number of spaces; if it’s negative, it’s left-aligned.


 hline-music11.gif


Debugging & Exception Handling

Debug.Assert()
Use System.ApplicationException as the base class to user-defined exceptions
Built-in Exceptions
  • ArgumentException
    • ArgumentNullException
    • ArgumentOutOfRangeException
    • InvalidEnumArgumentException
  • Standard Exceptions:
    • NullReferenceException
    • ArrayTypeMismatchException
    • IndexOutOfRangeException
  • NotImplementedException
    • NotImplementedException
    • NotSupportedException
    • MemberAccessException
    • MethodAccessException
  • Invalid Operation:
    • InvalidOperationException
    • ObjectDisposedException
  • Arithemtic Exception
    • ArithemticException
    • NotFiniteNumberException
    • DevideByZeroException
    • OverflowException
  • Parsing Exceptions
    • IOException
      • System.IO.IOException
      • System.IO.DirectoryNotFoundException
    • Configuration Exception
      • System.Configuration.ConfigurationException
      • System.Configuration.Install.InstallException
    • FormatException
      • System.FormatException
      • System.Reflection.CustomAttributeFormatException
  • Special Exceptions:
    • System.Web.WebException: thrown when a pluggable protocol causes an error
  • ExternalException
    • System.Runtime.InteropServices.COMException: thrown when an unknown HRESULT is returned from a COM object.
    • System.ServiceProcess.TimeoutException
    • System.Xml.XmlException: thrown due to a general error in the XML
Inner Exceptions
  • All exceptions have an InnerException property.


[SerializableAttribute]
    public class PlayerRunsOutOfChipException : ApplicationException, ISerializable
    {

        public User Player { get; private set; }

        public PlayerRunsOutOfChipException (User player)
            : base() {
            this.Player = player;
        }

        public override string Message {
            get {
                return base.Message;
            }
        }
    }



 hline-music11.gif


Collections

IList

Types
  • List
  • ArrayList
  • BitArray
  • Stack
  • Queue
Functions

C#'s list mechanism provides us with a number of useful methods.

  • ForEach:
dog.ForEach(delegate(Dogs p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });
  • FindAll:
List<Dogs> young = dog.FindAll(delegate(Dogs p) { return p.age < 25; });
  • Sort:
dog.Sort(delegate(Dogs p1, Dogs p2) { return p1.name.CompareTo(p2.name); });
HowTo
  • How to print all memebers in a list:
list.ForEach(delegate(Obj p) { Console.WriteLine(String.Format("{0}", p)); });

ICollection

StringCollection


IDictionary

Hashtable
SortedList
 hline-music11.gif

Attribute/Annotations

    [DatabaseTable()]
    public class User{
        ...
    }

    public class DatabaseTableAttribute : System.Attribute {
        ...
    }

    object[] attributes = typeof(User).GetCustomAttributes(typeof(DatabaseTableAttribute), true);
    DatabaseTableAttribute attribute = (DatabaseTableAttribute)attributes[0];

or 

    PropertyInfo property = typeof(User).GetProperties()[0];
    then call .GetCustomAttributes() on the property you want.


Assign Attribute

  • Attribute can be assigned to classes, fields, properties, and methods.
  • There are two way of instanciate a field:
    • Define a constructor:
    • Assign value to properties with a public set method. For example,
      public class MyDatabaseAttribute : Attribute{
      
          public string ExtraField {get; set;}
      
          public MyDatabaseAttribute(string name, int i){ 
              // constructor code ... 
          }
      }
      
      [MyDatabase("Meowky",1, ExtraField="cat")]
      public class User {
          // ...
      }
      
 hline-music11.gif

Other

Anonymous type


        <asp:ListView runat="server" ID="datatable" >
            <LayoutTemplate>
                <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
            </LayoutTemplate>
            <ItemTemplate>
                <div style="padding: 5px; float: left; border-bottom: solid 2px #124578;">
                    <%# Eval("UserID") %>
                </div>
                <div style="padding: 15px; float: left; border-bottom: solid 2px #789451;">
                    <%# Eval("Rating") %>
                </div>
                <br style="clear: left;" />
            </ItemTemplate>
        </asp:ListView>


            this.datatable.DataSource = // require an IEnumerable
                from row in table.Cast<object[]>()
                select new { // anonymous type 1
                    UserID = row[0], // the type has two fieldList
                    Rating = row[1]  
                };
            this.datatable.DataBind();

Keywords

Keywords@MSDN (http://msdn2.microsoft.com/en-us/library/x53a06bb(VS.80).aspx)

goto
//spaghetti code
if(a > b){
    goto exitLabel;
}
exitLabel:
    // control continues here



foreach
foreach(Cat child in meowky){
    // meow
}

Properties

  1. It does generics right.
  2. It handles exceptions right.
  3. It has type inference.
  4. It has currying.
  5. It has delegates. So it "treats functions as first-class citizen";
  6. It has kind of a "lazy-like" evaluation on LINQ queries. It won't actually evaluate a query until it needs the result.
  7. It doesn't force you to use pointers explicitly, but still let you if you really want to.
  8. It is imperative happy_schadenfreude.gif .

Inline

  • <%= and %> means Response.Write()
  • <%#Eval("Path") %>&MaxSize=<%=PhotoMaxSize %>
  • ImageUrl='<%# string.Format("../ImageHandler.ashx?File={0} ...

Documentation

  • Syntax:
    • Starts with \\\
    • <summary> ... </summary>
    • <param> ... </param>
    • <returns> ... </returns>
  • Generate XML Documentation:
Project -> Properties -> Build -> Output -> XML documentation file
Build -> Rebuild Solution


String

  • Split a String
char[] delim = {' '};
string[] strArr = strOriginal.Split(delim);
  • Extract SubStrings from a String
strModified = strOriginal.Substring(25);
  • Reverse a String
string strModified = Microsoft.VisualBasic.Strings.StrReverse(strOriginal);
  • Convert a String to Byte[] (Byte Array)
byte[] b = Encoding.Unicode.GetBytes(strOriginal);
strModified = Encoding.Unicode.GetString(b);
  • Convert a String to Char[](Char Array)
har[] chArr = strOriginal.ToCharArray();
strModified = new String(chArr);
  • Test/define null/empty string
string str = String.Empty;
bool check = String.IsNullOrEmpty(str);
  • Convert the Case of a String
textInfo.ToLower(strOriginal
textInfo.ToUpper(strOriginal)
textInfo.ToTitleCase(strOriginal)
  • Count the occurrences of words in a String
System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(srchString);
int count = rex.Matches(strOriginal).Count;
MessageBox.Show(srchString + " occurs " + count + " times");


  • Replace characters in a String
strModified = strOriginal.Replace("come handy", "be useful");
  • Count words
System.Text.RegularExpressions.MatchCollection wordColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @"[\S]+");
MessageBox.Show(wordColl.Count.ToString());
  • Count characters, white space is treated as a character
System.Text.RegularExpressions.MatchCollection charColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @".");
MessageBox.Show(charColl.Count.ToString());
  • Insert/Removes characters beginning at certain indices
str = str.Remove(25);
str = str.Remove(25,5);
str = str.Insert(26, "very ");
  • Create Date and Time from String
DateTime dt = DateTime.Parse("8/20/2008");
  • Convert String to Base64
byte[] byt = System.Text.Encoding.UTF8.GetBytes(strOriginal);
strModified = Convert.ToBase64String(byt);
  • Convert Base64 string to Original String
byte[] b = Convert.FromBase64String(strModified);
strOriginal = System.Text.Encoding.UTF8.GetString(b);
  • Copy a String
strModified = String.Copy(strOriginal);
  • Trimming a String
strOriginal = " Some new string we test ##";
strModified = strOriginal.Trim().Trim(char.Parse("#"));
  • Padding a String
strModified = strOriginal.PadLeft(34,'*');
  • Create a Delimited String
string[] strArr = new string[3] { "str1", "str2", "str3"};
string strModified = string.Join(";", strArr);
  • (Try) convert String To Integer
int temp = Int32.Parse("12345");
int i = 0;
bool b = Int32.TryParse("234abc", out i);
  • Search a String: use IndexOf (http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx) LastIndexOf (http://msdn.microsoft.com/en-us/library/system.string.lastindexof.aspx) StartsWith (http://msdn.microsoft.com/en-us/library/system.string.startswith.aspx) and EndsWith (http://msdn.microsoft.com/en-us/library/system.string.endswith.aspx)
Personal tools