Chapter 3 – General Coding

SAMS CSHARP 4.0 (P.62) 03/01/2011, 10:27PM

Essential and general C# knowledge that doesn’t fit easily into other chapters

Declare Variables

int x = 13; // declare and define
int y; // declare
y=13; // then define

Use Type Inference (Implicit Typing)
Highly useful in LINQ.
VAR — you want to declare a variable and assign it a value, without having to figure out the type, but still take adv of strong typing. You are merely giving the job of figuring out the type to the compiler. Once done, type can’t change!!!

can use for a local variable but not a class variable!!!

var x=13;
var myObj = new MyType();
// var myNullValue = null; //not allowed to set to NULL
**** but you can set it to NULL after defined
var myNullobj = new MyType();

foreach is a good place to use var.

Defer Type Checking to RunTime (Dynamic Types)

You want to delay type resolution until runtime.
Use the dynamic keyword for your variables and method parameters.

Use Dynamic Typing to Simplify COM Interop

var app=new Excel.Application();
// to avoid casting, use dynamic
dynamic sheet – app.ActiveSheet;

Declare Arrays

(1) int[] array1 = new int[4];
array[0]=13; array[1]=14; array1[2]=15; array1[3]=16;
(2) int[] array1 = new int[4] {13,14,15,16};
(3) int[] array1=new int[] {13,14,15,16};
(4) int[] array1 = {13,14,15,16};
// easiest

Applies to anything that implements IEnumerable

Create Multi-Dimentional Arrays

2D or 3D array

first decide which type of multi-dimentional array you need. (1) rectangular or (2) jagged

rectangular: same size rows

int[,] myarray1 = new int[,] {

float val=myarray1[0,1]; // the value is 2

jagged: like arrays of arrays

int[][] myarray1 = new int[3][];
myarray1[0]=new int[] {1,2,3};
myarray1[1]=new int[] {4,5,6,7,8};
myarray1[2]=new int[] {9,10,11,12};

int val = myarray1[0][1]; // the value is 2

Alias a NameSpace

to abbreviate the namespace in the using section; good for intellisense

using WPFControls = System.Windows.Controls;
using Acme = Acme.Widget.Controls;

Use the Conditional Operator (? 🙂

bool condition = true;
int x = condition? 13:14;


int x = y > 3 ? 5:6;

*** You can also use it to execute method, e.g.:

bool condition = true;
condition ? ExecuteSucceed() : ExecuteFail();

It will execute a method depending on the condition.

Use the Null-Coalescing Operator (??)

k can be null; if n != null, then k=n; else k=-1
int? k = n ?? -1;

Add Methods to Existing Types with Extension Methods (P.71)

static class, static method, and this keyword.In this example, a method is deined for the type integer.

Call Methods with Default Parameters

you want to avoid creating many overloads of a method by specifying default values for some parameters

ShaowFolders(string root = @”C:\”, bool showFullPAth = false)

ShowFolders();// method will take it as using the default: “C:\” and false
ShowFolders(@”C:\”);// “C:\” and false
ShowFolders(false);// not working this way!!!! Can’t just supply the second param.

Not recommended as it’s confusing.

parameter that has default value must appear before others, e.g.,
ShowFolders(string root=@”C:\”, bool showFullPath)

Call Method with Named Parameter

In last example, you need to do this to call the method:

ShowFolders(“C:\”, false)

but you can also do this with named parameters – order of the parameters does not masster in this case.

(add a ParameterName :
in front of the value being passed over)

false, root:

Enforce Code Contracts

Use contract to add constraints to your methods.

Static Checker integrated with VS can interactively notify you of contract violations in your code.

Implement Contracts on Interfaces

You want to implement contracts on every class that implements an interface. Because interfaces don’t have method bodies, you need to create a surrogate implementation
of the interface and add the contracts there. You tie them together using attributes.

Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: