C# For C++ Programmers
C# For C++ Programmers
switch
string can be used as test variable
no falling throught to the next case clause
goto case ___
Color
Color myColor
myColor == Color.Red;
Color.Red;
Console.WriteLine("{0}",
Console.WriteLine("{0}", myColor);
myColor);
//
// Displays
Displays Red
Red
Color
Color secondColor
secondColor == (Color)Enum.Parse(
(Color)Enum.Parse(
typeof(Color),
typeof(Color), "GREEN",
"GREEN", true
true );
);
// true – ignore case
// true – ignore case
Unboxing
pp == (int)box
(int)box
Ways to Reduce Boxing and Unboxing
Operations of Value Types
Encapsulate value types in a class
Manipulate value types through interfaces
Krzysztof Mossakowski (http://www.mini.pw.edu.pl/~mossakow)
Strings
Escaping special characters
(\’ \” \\ \0 \a \b \f \n \r \t \v)
\0is not a string terminator
@ prevents any character from being escaped
@”C:\Program Files\”
Unicode
\u#### - can be used in variable names
string is immutable
StringBuilder class - allows to modify a string
without creating a new object
int
int MyInt
MyInt == int.Parse("123,456",
int.Parse("123,456",
System.Globalization.NumberStyles.AllowThousands);
System.Globalization.NumberStyles.AllowThousands);
string
string MyString
MyString == 100.ToString("C");
100.ToString("C"); //
// "$100.00"
"$100.00"
Krzysztof Mossakowski (http://www.mini.pw.edu.pl/~mossakow)
Regular Expressions
Regular expressions – powerful text processing
Pattern-matching notation allows to:
findspecific character patterns
extract, edit, replace, or delete text substrings
add the extracted strings to a collection to generate a
report
Designed to be compatible with Perl 5
System.Text.RegularExpressions.RegEx
class
class Example3
Example3 {{
static
static void
void Main(string[
Main(string[ ]] args)
args) {{
foreach
foreach (string
(string arg
arg in
in args)
args) {{
System.Console.WriteLine(arg);
System.Console.WriteLine(arg);
}}
}}
}}
int
int xx == myArray3d[1,2,0]
myArray3d[1,2,0] ++ myArray2d[0,1];
myArray2d[0,1];
Jagged
int
int [][]
[][] myJaggedArray
myJaggedArray == new
new int[3][];
int[3][];
for (int i=0; i<3; i++)
for (int i=0; i<3; i++)
myJaggedArray[i]
myJaggedArray[i] == new
new int[2*i
int[2*i ++ 2];
2];
int
int xx == myJaggedArray[1][3];
myJaggedArray[1][3];
Krzysztof Mossakowski (http://www.mini.pw.edu.pl/~mossakow)
Sorting an Array
Sort Method Using Element’s
IComparable.CompareTo
Array.Sort(
Array.Sort( anArray
anArray );
);
MyStruct
MyStruct Struct;
Struct; //
// Creates
Creates aa MyStruct
MyStruct instance
instance
//
// but does not call
but does not call any
any constructor.
constructor.
//
// Fields
Fields in
in MyStruct
MyStruct will
will be
be
//
// uninitialized.
uninitialized.
Struct
Struct == new
new MyStruct();
MyStruct(); //// Calls
Calls constructor,
constructor,
//
// so
so initializing
initializing fields.
fields.
//
// But
But doesn’t
doesn’t allocate
allocate any
any memory
memory
//
// because Struct already exists
because Struct already exists
//
// on
on stack.
stack.
Krzysztof Mossakowski (http://www.mini.pw.edu.pl/~mossakow)
Operator =
Simple data types: copies the value
Structs: does a shallow copy of the struct
Classes: copies the reference
to shallow copy the instance:
MemberwiseCopy() – protected method of Object class
ICloneable interface with Clone() method
Default constructors
the compiler will generate this default constructor
only when there are no constructors
class
class MyClass
MyClass {{
public
public override
override void
void VirtualMethod()
VirtualMethod() {{ ...
... }}
public
public new
new void
void NormalMethod()
NormalMethod() {{ ...
... }}
// hides MyBaseClass.NormalMethod
// hides MyBaseClass.NormalMethod
}}
Abstract method
cannot contain a method body
is virtual
class
class String
String {{
public
public char
char this[int
this[int index]
index] {{
get
get {{
if
if (index
(index << 00 ||
|| index
index >=
>= Length)
Length)
throw
throw new
new IndexOutOfRangeException(
IndexOutOfRangeException( );
);
...
...
}}
}}
...
...
}}
string
string ss == "Hello
"Hello world!";
world!";
char
char ch
ch == s[3];
s[3];
Time
Time t;
t;
string
string ss == t;
t;
float
float ff == (float)t;
(float)t;
Implementing interfaces
a class can implement zero or more interfaces
a class must implement all inherited interface
methods
the implementing method can be virtual or non-virtual
Box
Box myBox
myBox == new
new Box();
Box();
IDimensions
IDimensions myDimensions == (IDimensions)myBox;
myDimensions (IDimensions)myBox;
float
float aa == myBox.Length();
myBox.Length(); //
// error
error
float
float b = (myBox as IDimensions).Width(); // OK
b = (myBox as IDimensions).Width(); // OK
float
float cc == myBox.Width();
myBox.Width(); //
// OK
OK
float
float dd == myDimensions.Length();
myDimensions.Length(); //
// OK
OK
float
float ee == myDimensions.Width();
myDimensions.Width(); //
// OK
OK
Krzysztof Mossakowski (http://www.mini.pw.edu.pl/~mossakow)
Delegates
Idea: the method pointer is wrapped in a
specialized class, along with a reference to the
object against which the method is to be called
(for an instance method, or the null reference
for a static method)
A delegate is a class that is derived from the
class System.Delegate
Delegate contains a reference to a method
All methods invoked by the same delegate must
have the same parameters and return value
Krzysztof Mossakowski (http://www.mini.pw.edu.pl/~mossakow)
Using Delegates
delegate
delegate void
void MyOp(int
MyOp(int X);
X);
class MyClass
class MyClass {{
void
void MyMethod(int
MyMethod(int X)
X) {{ ...
... }}
}}
MyClass
MyClass Mine
Mine == new
new MyClass();
MyClass();
MyOp
MyOp DoIt = new MyOp(Mine.MyMethod);
DoIt = new MyOp(Mine.MyMethod);
//
// Invoking
Invoking the
the method
method via
via the
the delegate
delegate
DoIt();
DoIt();
public
public class
class MyForm
MyForm :: Form
Form {{
private
private Button
Button button;
button; //
// derived
derived from
from Control
Control
public MyForm() : base()
public MyForm() : base() { {
button.Click
button.Click +=
+= new
new EventHandler(Button_Clicked);
EventHandler(Button_Clicked);
}}
private
private void
void Button_Clicked(
Button_Clicked(
object
object sender,
sender, EventArgs
EventArgs e)
e) {{
MessageBox.Show( "Button was clicked"
MessageBox.Show( "Button was clicked" ););
}}
}}
Krzysztof Mossakowski (http://www.mini.pw.edu.pl/~mossakow)
Delegates, Events, Interfaces
Use a delegate if:
you basically want a C-style function pointer
you want single callback invocation
the callback should be registered in the call or at
construction time, not through an add method call
Use events if:
client signs up for the callback function through an add
method call
more than one object will care
you want end users to be able to easily add a listener to the
notification in the visual designer
Use an interface if:
the callback function entails complex behavior,
such as multiple methods
Krzysztof Mossakowski (http://www.mini.pw.edu.pl/~mossakow)
Attributes
Derived from System.Attribute
Declarative tags that convey information to the
runtime
Stored with the metadata of the element
Predefined attributes in .NET:
general attributes
COM interoperability attributes
transaction handling attributes
visual designer component building attributes
public
public class
class Win32
Win32 {{
[DllImport("user32.dll",
[DllImport("user32.dll", CharSet=CharSet.Auto)]
CharSet=CharSet.Auto)]
public
public static
static extern
extern int
int MessageBox(int
MessageBox(int hWnd,
hWnd,
String
String text, String caption,
text, String caption, uint
uint type);
type);
}}
public
public class
class HelloWorld
HelloWorld {{
public
public static void
static void Main()
Main() {{
Win32.MessageBox(0,
Win32.MessageBox(0, "Hello
"Hello World",
World",
"Platform
"Platform Invoke
Invoke Sample",
Sample", 0);
0);
}}
}}
[Author("H.
[Author("H. Ackerman",
Ackerman", version=1.1)]
version=1.1)]
class
class SomeClass {{ ...
SomeClass ...
}}
System.Nullable<T>
System.Nullable<T> variable
variable
//
// or
or
T?
T? variable
variable
System.Nullable<int>
System.Nullable<int> myNullableInt;
myNullableInt;
int?
int? myOtherNullableInt;
myOtherNullableInt;
if
if (myNullableInt.HasValue)
(myNullableInt.HasValue)
//
// or
or
if
if (myNullableInt
(myNullableInt !=
!= null)
null)
static
static void
void Main(string[]
Main(string[] args)
args) {{
bool Console = true;
bool Console = true;
int
int xx == 5;
5;
Console.WriteLine(x);
Console.WriteLine(x); //
// compilation
compilation error
error
System.Console.WriteLine(x);
System.Console.WriteLine(x); //
// compilation
compilation error
error
global::System.Console.WriteLine(x);
global::System.Console.WriteLine(x); //
// OK
OK
global::System.Console.WriteLine(Console);
global::System.Console.WriteLine(Console); //// OK
OK
}}
}}
}}