int i = 3;
string s = i.ToString();
// This is an explanatory version of System.Int32
namespace System {
struct Int32 {
...
public string ToString() {
return ...;
}
}
}
// This is valid code, but we recommend you use the int alias
System.Int32 i = 5;

Value Types and Reference Types Side By Side

// Reference-type declaration
class PointR {
public int x, y;
}
// Value-type declaration
struct PointV {
public int x, y;
}
class Test {
static void Main() {
PointR a; // Local reference-type variable, uses 4 bytes of
// memory on the stack to hold address
PointV b; // Local value-type variable, uses 8 bytes of
// memory on the stack for x and y
a = new PointR(); // Assigns the reference to address of new
// instance of PointR allocated on the
// heap. The object on the heap uses 8
// bytes of memory for x and y, and an
// additional 8 bytes for core object
// requirements, such as storing the
// object's type synchronization state
b = new PointV(); // Calls the value-type's default
// constructor. The default constructor
// for both PointR and PointV will set
// each field to its default value, which
// will be 0 for both x and y.
a.x = 7;
b.x = 7;
}
}
// At the end of the method the local variables a and b go out of
// scope, but the new instance of a PointR remains in memory until
// the garbage collector determines it is no longer referenced
...
PointR c = a;
PointV d = b;
c.x = 9;
d.x = 9;
Console.WriteLine(a.x); // Prints 9
Console.WriteLine(b.x); // Prints 7
}
}

Statements

Expression Statements

int x = 5 + 6; // assign result
x++; // side effect
int y = Math.Min(x, 20); // side effect and assign result
Math.Min (x, y); // discards result, but ok, there is a side effect
x == y; // error, has no side effect, and does not assign result

// InControl.cs - compile with /r:Greeting.dll,English.dll
using System;
using System.Reflection;
class TestReflection {
// Note: This method requires the ReflectionPermission perm.
static void ModifyPrivateData(object o, string msg) {
// Get a FieldInfo type for the private data member
Type t = o.GetType();
FieldInfo fi = t.GetField("msg", BindingFlags.NonPublic|
BindingFlags.Instance);
// Use the FieldInfo to adjust the data member value
fi.SetValue(o, msg);
}
static void Main() {
// Create instances of both types
BritishGreeting bg = new BritishGreeting();
AmericanGreeting ag = new AmericanGreeting();
// Adjust the private data via reflection
ModifyPrivateData(ag, "Things are not the way they seem");
ModifyPrivateData(bg, "The runtime is in total control!");
// Display the modified greeting strings
ag.SayHello(); // "Things are not the way they seem"
bg.SayHello(); // "The runtime is in total control!"
}
}
Things are not the way they seem
The runtime is in total control!