Overview
The following details some aspects of the C# programming language which may be unusual if you are not used to C++ style languages
-
The following is the most basic C# file,
using System; using System.Net; // ... Other 'using' lines here ... namespace YourAppName { public class MyClassName { // ... Methods and properties here ... } } - Everything you write in C# is inside a class (or struct which is basically a class with no methods), every class is inside a namespace
-
The following keywords are used often,
-
thisis used to refer to the object instance inside a method. The object namespace is automatically imported into the method scope and so is used for clarity -
baseis used to refer to a method or property on an inherited class. Inherited classes are specified as followspublic class MyClassName : InheritedClass1, InheritedClass2 -
newinstantiates a new class
-
-
There are no functions or global variables in C#. Instead write a class using the
statickeyword which allows access to methods and properties of a class without instantiating it . e.g.
can be accessed elsewhere asnamespace YourAppName { public static class MyClassName { public static string MyStringProperty; public static string MyStringMethod() { return "Hello"; } } }YourAppName.MyClassName.MyStringPropertyandYourAppName.MyClassName.MyStringMethod(). -
Typical C# code makes frequent use of getters and setters. The syntax for this is as follows,
the convention for private variables is to prefix with an underscoreprivate string _myString; public string MyString { get { return this._value; } set { this._myString = value; } }
Generics, Boxing/Unboxing and Interfaces
C# is strongly typed. There are a few techniques which allow us to use and write code which can accept a wide range of objects
-
Generics
-
Allows the type to be specified when instantiating the object e.g.
creates a newList<MyClassName> myListOfClasses = new List<MyClassName>();Listobject which contains 'MyClassName' objects
-
Allows the type to be specified when instantiating the object e.g.
-
Boxing/Unboxing
-
All C# objects inherit from
object -
The technique where code accepts
objectas a type and then requires casting back into its true type later is known as Boxing/Unboxing -
e.g. a typical event handler for a button click
The sender is passed as anprivate void cancelBtn_Click(Object sender, EventArgs e) { Button b = sender as Button; // ... more code here }objectbut has to be cast back to aButtonbefore we can access its properties and methods - Use the Visual Studio debugger to help determine an objects 'true' type
-
All C# objects inherit from
-
Interfaces
- An interface in C# specifies a set of methods or properties that a class must implement to comply with that interface. Code can then be written that accepts the interface as a type and subsequently assumes that only these methods or properties exist.
-
e.g.
IEnumerableis an interface. It requiresGetEnumerator()to be defined in the class. If a class implements this interface then it can be used in any code that specifiesIEnumerableas a type. If code acceptsIEnumerableas a type then it can only assume that it has theGetEnumerator()method -
In Windows Phone development we most commonly have to implement the
IValueConverter, theINotifyPropertyChangedand theINotifyPropertyChanginginterfaces
Miscellaneous tips
-
Object Initializers can initialise properties on instantiation without lots of tedious code in the constructor e.g.
Profile p = new Profile(){ Name = "Delia", Occupation = "Chef", FavouriteTeam = new Team() { Name = "Norwich City", LeaguePosition = 15 }, Age = null, }; -
To make a variable nullable (that isn't already e.g.
int,bool) place a question mark after it i.e.int? myNullableInteger; -
To convert a string to a number use
Convert.ToDouble()if you know it will work. If you are unsure use,double num; bool wasSuccessful = double.TryParse(someString, out num); -
Specifying
outon a parameter means pass by reference, so the above will read the parsed number intonum
Linq
-
Linq is syntax that allows us to filter and manipulate collections of data such as
EntitySetobjects and anything that implements theIEnumerableinterface e.g.List<T>generics,var profilesNamedDeliaQuery = from Profile p in myProfiles where p.Name == "Delia" select p -
The result is filtered
IEnumerablequery which has not yet been resolved. To turn into aList<T>use,List<Profile> profilesNamedDelia = profilesNamedDeliaQuery.ToList(); -
Since an unresolved query are returned this means complex queries can be built up without using lots of memory, e.g.
the query here is only converted to aList<string> profileNamesWithNoOrders = ((from Profile p in myProfiles select p.Name).Except(from Order o in myOrders select o.ClientName) ).ToList();List<string>once both of the internal Linq queries have completed - Windows Phone uses Linq-To-SQL which is a subset of full Linq
- A good way to test and learn Linq queries is using the Linqpad tool
