using System;
class Hello
{
static void Main() {
Console.WriteLine("Hello world");
}
}
* Namespaces
Contain types and other namespaces
Type declarations
Classes, structs, interfaces, enums, and delegates
Members
Constants, fields, methods, properties, indexers, events, operators, constructors, destructors
Organization
No header files, code written “in-line”
No declaration order dependence
* Single inheritance
Member access
* Like classes, except
Stored in-line, not heap allocated
Assignment copies data, not reference
No inheritance
Ideal for light weight objects
Complex, point, rectangle, color
int, float, double, etc., are all structs
Benefits
No heap allocation, less GC pressure
More efficient use of memory
Multiple inheritance
Can contain methods, properties, indexers, and events
Private interface implementations
interface IDataBound
{
void Bind(IDataBinder binder);
}
class EditBox: Control, IDataBound
{
void IDataBound.Bind(IDataBinder binder) {...}
}
* Strongly typed
No implicit conversions to/from int
Operators: +, -, ++, –, &, |, ^, ~
Can specify underlying type
Byte, short, int, long
enum Color: byte
{
Red = 1,
Green = 2,
Blue = 4,
Black = 0,
White = Red | Green | Blue,
}
* Object oriented function pointers
Multiple receivers
Foundation for events
delegate void MouseEvent(int x, int y);
delegate double Func(double x);
Func func = new Func(Math.Sin);
double x = func(1.0);
public class Ade:base-class {}
Ade a = new Ade();
public : no restrictions
private : only accessible to class
protected : only accessible to class and subclasses
internal : accessible to any class in assembly
protected internal : == protected or internal
return-type Name(params) {}
Same name as class and no return type. Can have multiple constructors with different param lists.
Copy constructor must be created manually by passing an object in to a constructor method.
A static constructor will run before any instance of the class is created
Can define a Dispose method – implement interface IDisposable.
Should suppress GC using GC.SuppressFinalize(this);
Called automatically in using clauses eg using (x = new XYZ())
{ } Dispose called automatically.
Default is by value for value types
Use (ref int x) to pass by reference
values must be assigned a value before use. If not initially assigned then use out: (out int x)
public int Xyz {
get { return Xyz; }
set { Xyz = value }
}
a.Xyz++
To override a base class method
base class must define method as virtual
public virtual void open()
to override it in child class public override void open()
All methods are final by default.
Helps in versioning, eg add a new method in base class that has already been declared in a subclass.
If method in subclass is the same as a virtual base method must use new to indicate it is not an override
eg public new virtual Xyz()
abstract public void Add();
Must be overriden by sub class.
Base class must also be abstract
abstract public class AdeBase { }
Provides Equals(), GetHashCode(), GetType(), ToString(), Finalize(), MemberwiseClone(), ReferenceEquals()
int I =123; i.ToString();
int I = 123;
Object o = i;
int j = (int)o;
Defined as static methods, eg for a class Fraction to override + public static Fraction operator+(Fraction lhs, Fraction rhs) {}
[Convention is to use lhs and rhs]
Not all languages in .NET will support operator overloading and thus will not use these methods – worth adding separate add() method.
Be careful – make use intuitive.
If overloading ==, must also overload !=, same with >, < etc. Should also override Equals if overloading ==
Fraction f = 1.67; myInt = (int)f;
use public static implicit operator Fraction (int theInt) { }
A simple user defined type, a lightweight alternative to a class. Can contain methods, properties etc. Doesn’t support inheritance. Does support multiple interfaces. A struct is a value type.
Useful in arrays, but not in collections as boxing is required.
Define similar to class:
public struct Ade {
public SomeMethod() {}
}
Ade x = new Ade();
public interface IAde:baseclass {
void Read();
int Status{ get; set; }
}
Document doc = new Document(“ade”);
IAde iaDoc = doc as IAde;
or IAde iaDoc = (IAde)doc;
iaDoc.Read();
doc.Read();
if (doc is IAde) {}
The as operator returns null (rather than an error) if cast fails.
In a class implementing the interface, can put interface name as part of method declaration. Useful if two interfaces have same method name.
If explicit implentation then method is only visible when object is cast to the interface.
void IAde.Read() { } [Note – no access modifier]
int [] myArray;
myArray = new int[5]; [First element is 0]
Array of value types are value types – not boxed objects. Button[] myArray = new Button[3]; - does not create objects only null references – still have create and assign button objects.
Access element using [index], eg myArray[3]
Multi-dimensional arrays, inc initialisation
int [,] x = new int[2,2];
int [,] x = { {1,2}, {3,4} }
int [][] x
void MyMethod(params int[i] intVals)
MyMethod(1,2,3); or MyMethod(myIntArray);
Allows access to a class as if it were an array.
Effectively overloads the [] operator.
Declare an indexer within a class as: returnType this [accessType argument] { get; set;}
public string this[int i]
{
get { };
set { };
}
then can access as obj[10] where obj is an instance of the class.
The accessType can be any type does not have to be an int. Can also overload using different accessTypes (eg an int and a String indexer)
Associates values with a key. Any kind of object can be associated with any type of key.
Hashtable: Item, Add, Contains, Remove
IDictionary: interface to implement
string x = “abc”; or string x = @”abc”; # says treat string literally (ignore escape characters)
string intStr = myInt.ToString();
Available methods: eg Copy, Compare, Format, SubString, ToUpper, Trim, Split (breaks into substrings)
StringBuilder class for dynamically building and processing strings. Methods available: Append, Insert, Remove, Replace.
try { }
catch { } or catch (Exception type) { }
finally { }
System.Exception provides Message(), StackTrace(), InnerException(), TargetSite()
Custom exceptions must derive from System.ApplicationException
InnerException allows Exception to be saved as part of throwing a new
Exception – these can be nested.
Re-throwing exceptions: throw; or throw Exception;
public delegate int MyDelegate(params);
public void Sort(MyDelegate delFunc) {
x = delFunc(params);
}