General C# Learning Notes and Reminders

Below are some points I noted down when learning C#. As my memory is like a sieve, I though I should post them online!

C# Error Handling

Some notes on errors and exceptions. This is all bread and butter C#, but I thought id just blog some old notes from my first days of learning the language.

  • Separates the error handling logic from the main programming logic
  • Removes the need for error codes / flags to be passed around / global error flag
  • Try catch statements can be nested – the error will be caught by the closest nested catch statements.
  • Note that all of the standard exceptions are part of the System namespace.
  • Can use multiple catch handlers

Example
try
{
// Run some code here
}
catch (DivideByZeroException ex)
{
// Handle DivideByZeroException
}
catch (FormatException ex)
{
// Handle format exception
}
catch (Exception ex)
{
// general catch handler - fall through for any exceptions not previously caught
// Note that don't even need to specify (Expectation ex) in catch declaration if
// your not going to do anything with the actual exception object
}
finally
{
// Finally code - executes regardless of whether an exception was thrown or not
}

Throwing Exceptions
Examples (all have various overloads)…
throw new Exception(“An error message”);
throw new ArguementOutOfRangeException(“out of range”);
throw new FormatException(“Invalid Format”);

Checked / unchecked keywords
These are only relevant for integer arithmetic – to check for overflow etc

  • checked keyword – used around integers where exceptions will cause break
  • unchecked keyword – opposite as above

You can either wrap a code block with the checked / unchecked keyword using braces, or wrap an expression in brackets (ie using it as an operator – unchecked(expression) ).

Using keyword

The using keyword has various different meanings in C#. The first one is for namespace inclusion. It can also be used to scope variables e.g.
using console = System.Console; console.writeLine("Hello World");
It can also be used to specify the scope of a variable within a method e.g.:
using (WinForm our_Form = new WinForm())
{
    Application.Run(our_Form);
}

As keyword – effectively the same as casting:

Attempts to cast – returns null if fails – casting with brackets would throw an exception instead

Enums

enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
Integer values are associated with enums. Numbering starts at 0, however can changed this eg
enum day {Monday=1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
Can cast: (int)day.Tuesday; // returns 2.
Can also do enum day {Monday, WorstDay=Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
Note that you can choose an enumeration type as well
enum day : byte {Monday, WorstDay=Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
To call an enumeration
day firstDay = day.Monday;

GUIDS

Guids are Globally Unique Identifiers generated by Windows (numbers are 128 bits). These unique codes are used to uniquely identify stuff (eg records, files etc).
To create a guid simply do
Guid test = new Guid();
If you know a guid as a string, and you need a guid type in code, use the following constructor overload Guid test = new Guid(string guidId);
This can be really useful in sharepoint e.g. SPList list = SPWeb.Lists[test];

Compile directives

Conditional compilation – ive never used these (as yet) but thought id note down a couple of links for future reference.
http://www.csharphelp.com/archives/archive36.html
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfpreprocessordirectives.asp
I think these are used with switches on the compiler.

Reference / Value types

Value type
The variable holds the actual value. Primative data types such as int, char structs and enums are value types.
Reference type
Class types are reference types. A reference type varaible holds a reference to an object and not the actual object. Copying a reference variable does not make an actual copy of the data, it simply creates another reference to the data
Ref Keyword
Used to pass a reference to a variable into a method instead of the actual variable. If the actual variable was passed, a copy of that variable would be made which is local to that method (providing that the variable is a value type).
Note that if a reference type is passed to the method (eg an object), there is no point in using the ref keyword). The use of this is to ensure that any changes made to the variable referenced persist after the method has executed.
out keyword
This is essentially the same as the ref keyword, however it requires that the variable referenced must be set / updated the value that is referenced
Stack
Value types are stored on the stack. These are primitive data types such as int, char etc. These only exist for as long as the remain in scope. Note that I believe that actual references to objects are held on the stack.
Heap
Variables that are referenced (eg via ref, out or new keywords) are stored on the heap (objects etc). These continue to exist after the method referencing them is finished executed. They are only deleted when they are not referenced from anywhere (by C# disposal).
Boxing
If you reference an primitive type, the value of that primitive type is copied from the stack to the heap. Note that this mean that when you update the item on the stack, the item in the heap isnt updated and viceversa.
Unboxing
If you have a reference to an object that can be cast to a primitive type, casting will copy the value of the object to the primitive data type variable. Note that this mean that when you update the item on the stack, the item in the heap isnt updated and viceversa.

Structs

  • A struct type is a value type and not a reference type (such as a class).
  • A struct can have its own fields, methods and constructors
  • You cannot declare a default constructor (one with no params) – the compiler always writes one.
  • Note that if you dont intialise a variable in a class constructor, you will not be able to access it (a class would set uninitialised variables to 0, null or false).
  • Note that you cant initialise a struct member variable when you declare it.

struct Date
{
    private int _day, _month, _year;
    public Date(int  day, int month, int year) 
    {    
        _day = day;
        _month = month;
        _year = year; 
    }

Xml reading and writing and XPath

Rather than talking about xml and xpath, here is some example code…
using System.Xml;
// Load xml doc
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(pathToXmlFile);
// Get the table where name node innertext is equal to tableName
string xPath = string.Format("//settings/tables/table/name[. ='{0}']", tableName);
XmlNode tableXml = xmlDoc.SelectSingleNode(xPath).ParentNode;
if (tableXml != null)
{
    XmlNodeList fields = tableXml.SelectNodes("fields/field/name");
    foreach (XmlNode tableName in field)
    {
        Console.WriteLine(tableName.InnerText);
    }    
}
// To get a single value do
string connStr = xmlDoc.SelectSingleNode("/settings/databaseConnectionString").InnerText;
Console.WriteLine(connStr);
// Note, to do a where clause on an attribute, (Where attribute id=1 and type=b or c do 
xmlDoc.selectNodes("//settings/tables[@id='1' and (@type='B' or @type='C')]")

This is a pretty good article on xpath where clauses: http://www.eggheadcafe.com/articles/20030627d.asp

Indexers

Indexers are used to allow the properties of a class to be accessed using array like syntax (eg in Sharepoint SPListItem[“internalName”] to get the value of an internal name).
public class testClass
{
    string[] test = new string[]{"test1", "test2", "test3"};
    public int this[int index]
    {
        get
        {
            return test[index];
        }
        set 
        {
            test[index] = value;
        }
    }
}

Note that indexers can be specified in an interface e.g.
interface IExample
{
   int this[int index]{ get; set;}
}

Delegates and Events

A delegate can be thought of as a smart method, similar to thinking of properties as smart fields.
Delegates generally seem to be declared outside of a class, e.g.
delegate void DoSomething(int someParam);
Subsequent classes then implement Tick. A method must jsut have the same signature as tick, e.g.
void AnImplementationOfDoingSomething(int someParam)
{
   ...do something
}
You can pass the delegate method through as a method param to a method - eg
void Example(DoSomething param, int anotherParam)
{
    DoSomething(anotherParam);  // Call DoSomethingMethod
}

Events
To attach a delegate to an event anObject.anEvent += new MethodToExecute(param);
To detach a delegate to an event anObject.anEvent -= new MethodToExecute(param);
To raise an event
public event ActionHandler EventName;
private void Raise()
{
    if (EventName != null)
    {
        EventName();
    }
}

Other Notes

  • chars are denoted by single quotes – eg ‘:’ string are denoted by double quotes – eg “:” would be a string

You May Also Like

About the Author: rnowik

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.