A fine site

Basics of C#

Leave a comment





  • Class System.String

Can be used as standard type string
string s = “Alfonso”;
•Strings are immutable (use StringBuilder if you want to modify strings)
•Can be concatenated with +: “Don ” + s
•Can be indexed: s[i]
•String length: s.Length
•Strings are reference types => reference semantics in assignments
•but their values can be compared with ==and !=: if (s == “Alfonso”) …
•Class String defines many useful operations:
CompareTo, IndexOf, StartsWith, Substring, …

  • Structs

struct Point {
public int x, y; // fields
public Point (int x, int y) { this.x = x; this.y = y; }// constructor
public void MoveTo (int a, int b) { x = a; y = b; }// methods
Point p = new Point(3, 4);// constructor initializes object on the stack p.
MoveTo(10, 20);// method call


  • Classes

class Rectangle
Point origin;public int width, height;
public Rectangle()
origin = new Point(0,0);
width = height = 0;
public Rectangle (Point p, int w, int h)
origin = p; width = w; height = h;
public void MoveTo (Point p)
origin = p;

  • Use

Rectangle r = new Rectangle(new Point(10, 20), 5, 5);
int area = r.width * r.height;
r.MoveTo(new Point(3, 3));


Classes                                                      Structs
Reference Types                                          Value Types
(objects stored on the heap)                         (objects stored on the stack)
support inheritance                                       no inheritance
(all classes are derived from object)                (but compatible with object)
can implement interfaces                               can implement interfaces
may have a destructor                                    no destructors allowed



  • Boxing and Unboxing

Value types (int, struct, enum) are also compatible with object!

The assignment
object obj = 3;
wraps up the value 3 into a heap object

The assignment
int x = (int) obj;
unwraps the value again


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