Netdesk 2124
12/12/2005 – 12/16/2005
Day 1 2005.12.12
Rick White MCSD, MCDBA, MCT
Rick.White@netdesk.com
- basics
- Ramp Program --- for 6 g’s you can take as many netdesk
classes you want, for 1 year
- Password: P@ssw0rd
- Training files: c:\program files\msdntrain\2124
- MCP stuff is changing --- www.microsoft.com/traincert
- .Net Framework basics
- CLR handles traditional win32 probs, you don’t even have
to worry about them now
- Memory leaks
- Does this via a managed heap (garbage
collection)
- Even if you aren’t referencing an object, CLR still is
- buffer overflows (aka overruns)
- type checker provides type safety for the
managed heap
- rights abuse
- security engine handles this
- collects info about program, assigns rights
- don’t worry about this for this week
- DLL Hell
- Previously, new versions of dlls could overwrite
pre-existing versions, and if v1 functionality was changed, it could
break the dll for legacy code.
- GAC
- DLL hell is fixed in .net by the GAC... this allows a
program to point to it’s own version of dlls
- Public/Private key token: in the GAC, dlls are
protected from overwriting by encryption with a public/private key
scheme
- Note: read more about GAC and Pub/Private key tokens
- CLR sits on top of win32
- Essentially provides basic OS functions
- Check out: Intercalc, and BrainF--- these
are supposed to be funny
- An Assembly is a file that has MSIL in it, and has
references that tell a class loader where to look for a .dll
- JIT compilation: process that automatically
changes IL into Win32 instructions [ask about this]
- NGEN.exe allows you to manually compile to Win32
instructions
- It is possible to have multiple versions of framework,
vs, etc. all working on 1 box
- Good Books
- “ADO .NET” by David Sheppa (MS Press Book)
- Headfirst design patterns by Dino Esposio
- Design patterns in C# by Steven Metsker
- Expert C# Business Objects (Books for
Professionals by Professionals) by Rockford Lhotka
- (http://www.amazon.com/gp/product/1590593448/qid=1134754604/sr=2-1/ref=pd_bbs_b_2_1/002-0862613-1131213?s=books&v=glance&n=283155)
- Question: what is the relationship between a Namespace and
an Assembly
- Assemblies are physical files
- Namespaces are locigal groupings of classes
- Visual Studio walkthru
- A project will output to a single Assembly
- Static means that the method/property is the same across
however many instances of the class are created sort of like a global
within the context of the 1-n instances of a specific class [check with
Rick]
- Ctrl+F5 runs a console app with a press any key to
contine
- View >> other windows >> object browser
(ctrl+alt+j)
- Basic C#
- A class is a set of data
- Lowercase keywords like string, int, just are shortcuts
to get to instances of String, Int32, etc.
- Value vs Reference type
- A value type has a ValueType it has inherited from it’s base
class listed in it’s Bases and Interfaces
- A reference type has an Object it has inhereted from it’s
base class listed in it’s Bases and Interfaces
- Naming
- User Defined Types
- Enumeration (enum)
- For strings, for objects use collections
- Value type
- Structure (struct)
- Value type
- For groups of strings, sort of like a stripped down
class
- Converting
- Easy convert? x = (int)150; this converts 150 into an int
- Looping through a collection…
Foreach (int number in
numbers){
Console.WriteLine(numer);
}
Day 2 2005.12.13
- Exceptions
- There are two ways to refer to an obj on the managed
heap:
- refer to the obj with a variable of that obj’s type
- refer to the obj with a variable of a parent type of
that obj
- ergo: you can always refer to an exception (or any
other obj) with a variable of type object
- get info from Rick about how to have try/catch return a
var vs an obj
- Application exception this is where you define and can
throw your own custom errors
- static methods/props can only be referred to by the
classname, not by instances of a class
- If you want to call a static method/prop, you have to
refer directly to the overall class, you can’t access these via a
specific instance of the class. (however, you can refer to
Class.prop/method within an instance)
- Check out MSDN patterns and practices website
- Once you throw an exception, the CLR jumps straight to the
catch
- An Instance Variable is a property of an instance
of a class
- Static indicates that a variable or method are
associated with the class itself, not with an instance of the class
- You can call a static method from a static method
- You can call a non static method1 from from a static
method0 by creating a new instance of method1
- NonStatic indicates that there may be from zero to
many instances of the method, class, variable, etc.
- Stack Frame --- local variables go here, they go
out of scope when a method, class instance, whatever, ends
- Managed Heap ---persists, there is just one, and
this is associated with the application, as soon as the app ends, the MH
goes away
- When you load a class, all the static methods, variables,
etc., all go onto the stack frame. However, any NONstatic methods,
variables, etc., DO NOT exist until you instantiate them via the new
method.
- A Class level (shared) variable is visible
to all members in a class, may be static or not, depending
- Passing stuff…
- [val by val] When you pass an value type (int, for
example) into a method by val (not out/ref), you are passing by value,
and the value stays on the calling code’s stack frame, and a copy of the
value goes on the called code’s stack frame. Thus, operations in the
called code WON’T effect the value outside of the called code.
static void m(int i)
{
}
- [val by ref] When you pass an value type (int, for
example) into a method by ref, you are passing by reference. Thus,
operations in that method WILL effect the value type outside of the
method
- Actually, this stores the int in something called a box
in the managed heap, and there is a pointer to this box on the stack
frame, and when the method ends, the box is destroyed and the value is
put back on the stack frame (this is called boxing)
static void m(ref int i)
{
}
- [ref by val] When you pass a reference type (an
object) without specifying ref, you are passing the reference to the obj
by value, but because it’s a reference type, you’re just passing the
reference, not the value. Changes to the data in the obj will be
reflected in the calling code.
- This situation gives you two references, one on the
calling stack frame, and one on the called stack frame, BOTH pointing to
the same obj on the managed heap
- [ref by ref] When you pass a reference type (an
object) and specifying ref, you are passing the obj by ref, but because
it’s a reference type, you’re just passing a reference to the reference,
Changes to the data in the obj will be reflected in the calling code.
The only difference between this and ref by val is that this allows
you to change which obj you are pointing to
- This situation gives you 3 references, one on the calling
stack frame, one on the called stack frame, BOTH referring to a box (on
managed heap), which contains a ref to one obj on the managed heap
- [ref/val by out] this passes an uninitalized
variable of the passed type by ref. The called method has to create a new
instance of the obj (ref types), or initialize the type (val type), and
do whatever, including return the new obj to main. This lets you create
a factory. The different between this and passing a ref or val by ref is
that you pass in a variable of the type, but it isn’t instantiated yet
- I’m not going into what happens here
- Params keyword --- lets you pass a reference (to
an array) by value into a method
Calling…
Blabla(1,2,3);
In the called method
Static void blabla(params
int[p])
{
Console.WriteLine(args[0]);
Console.WriteLine(args[1]);
Console.WriteLine(args[2]);
}
or…
Foreach (int i in p) {}
- With overloading, if you want the overloaded methods to
share functionality, you have to have them call each other
- Arrays
- Arrays have to have elements of the same time
- Structs can have elements of different types
- Arrays are reference types which contain
references to either other reference types or to value types
- Rank is another way of referring to the number of
dimensions in an array
- ArrayLists are like collections, more flexible,
resizeable, etc.
long[ ] bla = new long
{0,1,2,3}
long[4] bla = new long
{0,1,2,3}
…both are OK
§
You can assign length to arrays at run time
§
Copied arrays
·
Shallow copy (new array = old array) puts copies of the data
contained in the old array in the new array, either values or references,
depending on what was in the array
o
Classes
§
Data structure that contains both data and functions
§
All variables in a struct end up in stack, classes end up in heap
§
Encapsulation is keeping certain things in the class hidden from
external code
§
“this” allows you to find the object in which this code is
currently running doesn’t work in static methods
Day 3 2005.12.14
- Basic OO Action
- You can refer to an obj on the managed heap with your
specific class, or with any parent up the hierarchy all the way to object
- A class always has one base class (except for object,
which has no base class), which is just the next parent up the hierarchy
- A method with no implementation is called an operation
this lets you define a method in a base class, and then let children
independently define exactly what it does
- Every base class exists in every derived class
- Abstract base class these exist purely to provide
structure to programmers
- Interfaces
- 3 ways you can refer to an object:
- same type
- parent type
- INTERFACE
- An interface lets you make your class adhere to a
defined set of methods and/or properties, and other code can expect to be
able to use those methods/properties
- The class that implements the interface has to actually
write the code that the interface defines
- Vtable - table of contents for all the members
(methods and props) in the class
- Here’s how to use an interface:
- Create an interface
- Create a class that implements the interface
- This class will have to have members (methods/props)
for all the members in the interface
- Create a ref variable of the interface’s type, which
refers to an obj of the class’ type
IWhateverInterface
a = new MyClass();
- Reference variable - variable on the stack frame
that points to an obj on the managed heap
- Not totally required, but it’s a good idea to set ref
variables to null when you are done with them.
- In C#, you can define how comparison operators work with
your own data types. i.e., do a comparison of two bank accounts are bigger,
this requires operator overloading
- Note: when comparing two reference variables, you are
comparing the REFERENCES, except for with strings, which just compares
the size of the string. Thus, == or != will tell you whether two ref
variables are pointing to the same obj on the managed heap, and will
return false if they point to different objs, EVEN if they contain the
same values.
- Use the term reference instead of pointer,as pointer
implies certain things to C++ devs
- Sealed - you can’t inherit a sealed base class, for
example: String
- Any change to a String creates a WHOLE NEW COPY of the
String on the managed heap! This is inefficient.
- When comparing lots of strings to one another, replacing,
inserting, appending, etc., use System.Text.StringBuilder, this is
a lot faster.
- Object.ReferenceEquals() can be used to determine
if two ref variables point to the same obj
- typeof() operator - gives you an instance of the
type class info for the obj ref passed to typeof(). This lets you inspect
the obj, do reflection, etc.
- Streams - these can be files, xml, port, etc.
- Data Conversion
- Implicit conversion (x=y) is cool if you are converting
to a parent type, no so the other direction
- Use the is operator to check if a parent type is actually
one sub type or another; or to see if an obj is the same type as another
obj
- Alternatively, use the as operator to attempt to convert
one type to the other, if this fails, the target ref variable is null
- You can implicitly convert from a type that implements an
interface to the interface
- Explicit casting:
WhateverType a
= (WhateverType)b;
if this works, a
and b both point to the same obj on the managed heap; that obj on the managed
heap may be of WhateverType or a child of WhateverType
- Getting name of an obj from the obj
System.Type t = obj.GetType();
Console.WriteLine(t.Name);
Or
Console.WriteLine(obj.GetType().Name);
- Constructors
- A constuctor returns a ref to the new obj, but you don’t
specify a return type
- When you call a child constructor, the parent’s default
constructor gets called by the compiler automatically
- If you want to call the parent’s non-default constructor,
specify
public Child(type[s]
ChildParam[s]) :Base(type[s] ParentParam[s])
{
…
}
…in the child
constructor, and the parent’s non default constructore will get called
- Look for an article called writing unmaintainable code
- Adding a private constructor to a class prevents it from
ever being instantiated
Day 4 2005.12.15
- Destructor - this is a finalize method. It works
like a contstructor, but doesn’t get called by the coder. This runs when
garbage collection frees the memory, it can be used to free up a
connection to com component, etc.
- When destructing (finalizing), don’t assume what order
objs on the managed heap are destructed so don’t have obj a that refers
to obj b call a method on b in the destructor, because it may not be
there! (Destructors kind of suck, and add a lot of overhead)
- Check out module 9, pg 51,52 to see a pattern called
Resource Wrapper that uses IDisposable, the Dispose method, and the
GC.SuppressFinalize(this) method this lets you:
- Call a method to do all of your disconnecting
- Moves the obj out of the Finalization queue, and NOT into
the FReachable queue (good thing)
- Lets normal garbage collection clean up the obj (instead
of going through the more time consuming and non-deterministic
finalization
- Also, it doesn’t freak out if you call Dispose twice, or
forget to call it at all, as finalization will still happen, at some
point
- Declarations (the line that declare the class or member)
- Virtual/Override (members) -
- base class defines a virtual method Abc()
- child defines an override method Abc() with a different
implementation (does something different)
- THEN, you can have a child cast as a base, and still get
child funtionality from the base
- Useful when you have a bunch of different child types
from a single base, and want to have the children do Abc(), whatever
that means to the child
- Note: virtual/override will always give you the Abc()
that is furthest down the hierarchy
- You can do this multiple times down the hierarchy, just
specify a virtual Abc() in the base, and then override the child Abc()
methods all the way down the hierarchy
- You can have all the classes up the hierarchy execute
their AS WELL, by having the children execute their own Abc(), and also
specify base.Abc() in each child
- New (members) in a method definition lets you hide
a child’s Abc(), even though the base is virtual, in this case, you
should have another name, probably -- TURN CRAP DETECTOR ON
- Abstract (members or classes) - you can’t
instantiate this, it’s intended as a base for children to derive from
- Sealed (classes) - this class cannot be derived
from
- Protected (members) - visible to children only
(privates are visible to the class only, not even to children, although
children will have their own privates)
- Internal (classes or members) - you can only call
this from within the same assembly. This often gets used when you have
the classes (A,B,C,D) within an assembly calling a single class (X), but
don’t want classes outside the assembly to be able to directly call X
instead call to A,B,C, or D.
- Interfaces
interface IToken
{
int LineNumber();
string name();
}
- Have your member of a class that implements an interface
return this cast as the interface member, this way the calling code can
deal with the interface, and doesn’t have to deal directly with your code
- When your class (or member) implements an interface,
other code can instantiate a variable of that interface type from your
class
IXyz x = new
Abc();
…this
instantiates an obj x of type Abc, in which only the IXyz members are available
- Complex Objects - composed of multiple simpler
objects car has engine, chassis, wheels, etc.
- Module - grouping of source code that isn’t
changing, this is used to make builds go more quickly
- Hashtable - key/value pair keys are (ususally)
numbers, but can be objs, values are references to objs. Best practice
from the framework guidelines is to use an int for key
Day 5 2005.12.16
- Operator Overload
- Note that you can change what operators +, -, *, /, etc.
do with specific data types by writing an operator overload method
- You can also do this with relational operators,
conversion operators
- I think you really shouldn’t do any of this, it’s really
unclear what’s going on
- Delegates
- Delegate -
- Is a variable type, essentially a very flexible
reference type
- A callback is when you pass a delegate to another
method, typically in another process or on another thread
- A delegate defined as type X and as accepting args Y can
call any method that returns X and accepts args Y
- Usually used in lists, collections, or arrays
- Operations:
- Define a delegate d
- Type X, accepts args Y
- Instantiate a variable A of type some class C with
method m
- m is type X, accepts args Y
- new d(A.m);
- D now contains a reference to A.m
- You can repeat this with more classes that have methods
of type X, args Y, regardless of what class they come from, or what
they do
- Use += to add more delegates to d
new d1(B.m);
d+=d1;
new d2(F.m);
d+=d2;
- A delegate lets you access a method on an
instance of a class, just like an interface, BUT without the extra work
of having that class implement an Interface

(Diagram to complement
code on page 46)
- A multicast delegate contains an arraylist of delegates
(they all conform to the same delegate definition)
- You can get the invocation list from this, and manually
invoke each delegate’s method
- GetInvocationList() returns an array of delegates
- Events are essentially multicast delegates
- In your class that uses a delegate, you can define an
event that is of the type of the delegate
private event
D E;
…this way, when
the event E gets thrown, the delegate gets invoked, which invokes each
individual method which is referred to by the multicast delegate
- Accessors - properties
- Properties have to have a get and a set
- Generally, you want to use a public prop to access a
private string
- Accessors are useful when you want to do some logic when
code gets or sets a value you can’t do this with a public variable.
- Best practice is to make all types that you want to be
publicly available be private, and have public accessors
- Props are always set by val (val by val, or ref by val)
- Can be static
- Make a class indexable (give it an indexer) by creating
a public property call this like so:
class A
{
public long this[int i]{}
}
…note that the data type doesn’t
have to be long.
- Attributes - put in a bunch of behind the scenes
code for you, simply by adding the attribute
- Conditional debugging, webservice, are good examples
- Custom attributes are supported as well