Getting Started With Getting Started With C#C#
SigWin 2004SigWin 2004
OutlineOutline
Class basicsClass basics– InheritanceInheritance– MethodsMethods– PropertiesProperties– TypesTypes
Important C# conceptsImportant C# concepts– Garbage collectionGarbage collection– NamespacesNamespaces– Using statementUsing statement
Event HandlingEvent Handling– DelegatesDelegates– Event processingEvent processing
More advanced stuffMore advanced stuff– Error handlingError handling– Best practicesBest practices
Basic C# featuresBasic C# features
Automatic garbage collection Automatic garbage collection (don’t have to delete objects)(don’t have to delete objects)
No pointersNo pointers Only booleans allowed in if Only booleans allowed in if
statementsstatements Everything inherits from Everything inherits from
System.ObjectSystem.Object
Class basicsClass basics
Classes look like this:Classes look like this:class myClass
{private string myVar;
public myClass() {}
protected void myMethod(int parameter) {
//do stuff here}
}
InheritanceInheritance
C# only supports single C# only supports single inheritanceinheritance
Specify inheritance like so:Specify inheritance like so:
class myClass : myBaseClass class myClass : myBaseClass
MethodsMethods
2 types of methods:2 types of methods:– Static methodsStatic methods– Non-static methodsNon-static methods
Yes, there are others, but we Yes, there are others, but we won’t talk about them (virtual, won’t talk about them (virtual, override, etc.)override, etc.)
Method exampleMethod example
class myClass {
private string myVar;
public myClass() {}
public void myMethod(int parameter) {
//do stuff here}
public static void PrintStuff() {}
}
class myCallerClass {
public myCallerClass() {
myClass.PrintStuff();myClass myInstance= new myClass();myInstance.myMethod(5);
}}
What’s wrong with this What’s wrong with this code?code?
class myClass : myBaseClass, myRealBaseClass
{
myClass()
{}
public int DoSomething(string myString)
{
return 100000000000000;
}
}
PropertiesProperties
Properties are NOT fieldsProperties are NOT fields Fields are variables declared in the Fields are variables declared in the
classclass Properties are “wrappers” for fieldsProperties are “wrappers” for fields Get/Set:Get/Set:private string mystring;private string mystring;public string MyString {public string MyString {
get { return mystring; }get { return mystring; }set {mystring = value; }set {mystring = value; }
}}
TypesTypes
Value Types vs. Reference TypesValue Types vs. Reference Types Value Types are:Value Types are:
– int, byte, double, etc.int, byte, double, etc. Reference types are:Reference types are:
– Everything else! (including string)Everything else! (including string) Reference types=pointersReference types=pointers Can pass value types by reference Can pass value types by reference
by using the “ref” keywordby using the “ref” keyword
What happens here?What happens here?
class myUtil
{
public myUtil()
{
int thenumber=0;
System.Collections.ArrayList myList=new System.Collections.ArrayList();
myList.Add(1);
myList.Add(2);
DoStuff(thenumber, myList);
System.Console.WriteLine(thenumber+"and"+myList.Count);
}
private void DoStuff(int mynumber, System.Collections.ArrayList myListThingy)
{
mynumber=5;
myListThingy.Clear();
}
}
Garbage collectionGarbage collection
The .NET framework takes care of The .NET framework takes care of getting rid of your objectsgetting rid of your objects
It runs automaticallyIt runs automatically You can run it manually by calling You can run it manually by calling
GC.Collect()GC.Collect() BUT:BUT:
NEVER DO THIS!!!NEVER DO THIS!!! Why?Why?
NamespacesNamespaces
This is where I somehow manage This is where I somehow manage to describe a namespaceto describe a namespace
““Using”Using”
Using tells the compiler what Using tells the compiler what prefixes to try on stuff it can’t prefixes to try on stuff it can’t figure out:figure out:
using System.Collections;using System.Collections;
ArrayList myList=new ArrayList()ArrayList myList=new ArrayList()
What’s wrong with this What’s wrong with this code?code?
namespace myProgram
{
class theClass
{
static void Main()
{
Console.WriteLine("blah");
}
}
}
Event handlingEvent handling
Events are how programs Events are how programs communicatecommunicate
Delegates are function pointersDelegates are function pointers To capture an event, you say To capture an event, you say
something like this:something like this:myButton.Click+=new myButton.Click+=new
EventHandler(myButton_click_eveEventHandler(myButton_click_eventhandler);nthandler);
What’s wrong with this What’s wrong with this code?code?
using System;class myClass {
private System.Windows.Forms.Button myButton;public myClass() {
myButton.Click+=new EventHandler(myButtonEvent);
}private void myButtonEvent(object sender,
System.EventArgs e){}
}
Error handlingError handling
System.ExceptionSystem.Exception Gets code information like:Gets code information like:
– Stack traceStack trace– Line and file infoLine and file info– Detailed error messageDetailed error message
Use in try…catch blocksUse in try…catch blocks
Error exampleError example
…
ArrayList myList;
try {
myList.Clear();
} catch (System.NullReferenceException e) {
Console.WriteLine(“variable not initialized”);
}
More error stuffMore error stuff
To throw an error say:To throw an error say:
throw <exception object>throw <exception object>
Or:Or:
throw new <exception class>throw new <exception class>
Exceptions are very costly, don’t Exceptions are very costly, don’t throw them unless there is an errorthrow them unless there is an error
What’s wrong with this What’s wrong with this code? (hard version)code? (hard version)
try {
bool success=false;
success=SomeClass.SomeMethod();
} catch (MyCustomExcecption e) {
Console.WriteLine(success);
}
What’s wrong with this What’s wrong with this code? (really hard code? (really hard version)version)
try {
SomeClass.SomeMethod();
} catch (System.Exception e) {
//process error and rethrow
throw e;
}
What’s wrong with this What’s wrong with this code?code?
//Allocate a lot of objects
int myvar;
for (int i=0; i<10000; i++) {
ArrayList myList=new ArrayList();
}
GC.Collect();
Console.WriteLine(myvar);
What’s wrong here?What’s wrong here?
class myClass {
public myClass() {}
private string userSetsThis;
public string UserSetsThis {
get {return userSetsThis; }
}
public myMethod() {
//Do stuff based on value of userSetsThis
}}
What’s the output What’s the output here? (this is really here? (this is really damn hard)damn hard)
struct myStruct{
int value;
public myStruct(int value){
this.value = value;}
public void SetValue(int value) {
this.value=value;}
public int Value { get {return value;} }
}
class myClass {
public myClass() {
myStruct[] myFoos=new myStruct[2];myFoos[0]=new myStruct(5);myFoos[1]=new myStruct(10);foreach (myStruct foo in myFoos) {
foo.SetValue(99);Console.WriteLine(foo.Value);
}Console.WriteLine();foreach (myStruct foo in myFoos) {
Console.WriteLine(foo.Value);}
}