From C++ to C#
(and C++ standard library to
.NET)
Cpt S 321 Washington State University
String
• string vs String
• String is a class declared in the System namespace in .NET. • string (lowercase s) type that maps to System.String.
• Strings in C# are immutable
• Once the object is instantiated, it cannot be changed in any way
• If the string is initialized as “ABCDE” then it will stay “ABCDE” in memory and cannot be modified.
• Methods: Substring (!), Replace (!), ToLower (!), IndexOf, StartsWith, and many others …
String (cont.)
string s = “Hello”;
string s1 = “_World!”;
s += s1;
Console.WriteLine(s); // Output ?
Ex.1
string a = “hello”;
string b = “h”;
b += “ello”; Console.WriteLine(a == b);
// Output?
Console.WriteLine((object)a
== (object)b); // Output?
Ex.3
string s = “Hello “; Ex.2 string s1 = s;
s += “World”;
Console.WriteLine(s); // Output ? System.Console.WriteLine(s1); // Output ?
String (cont.) – Example 1
Reference
1. s 2. s1
3. s
Output:
4. Hello_World!
Object
“Hello”
“_World!” “Hello _World!”
Ready for GC
1. string s = “Hello”;
2. string s1 = “_World!”;
3. s += s1;
4. Console.WriteLine(s); // Output ?
String (cont.) – Example 2
Reference
1. s 2. s1
3. s Output:
4. Hello_World!
5. Hello
Object
“Hello ”
1. string s = “Hello “;
2. string s1 = s;
3. s += “World”;
4. Console.WriteLine(s); // Output?
5. System.Console.WriteLine(s1); // Output?
“Hello World!”
String (cont.) – Example 3
Reference Object
1. a “Hello” 2.b “H”
3. b “Hello”
Ready for GC
1. string a = “Hello”;
2. string b = “H”;
3. b += “ello”;
4. Console.WriteLine(a == b);
// Output?
5. Console.WriteLine((object)a == (object)b); // Output?
Output:
4. True
5. False
Q: What would be the output if we were to replace lines 2 and 3 by string b = a; ? A: True for both lines 4 and 5.
StringBuilder
• StringBuilder class for mutable strings
• Better performance when your program has many string manipulations.
• Do not automatically replace all String by StringBuilder: String operations are highly optimized
• String versus StringBuilder, what to consider:
• What is the number of changes you plan to make to a string? • Will you need search methods?
• StringBuilder – important properties: Length, Capacity, MaxCapacity
• Creating a StringBuilder:
1. StringBuilder sb = new StringBuilder(); // default capacity, i.e., 16 characters
2. StringBuilder sb = new StringBuilder(“ABC”, 50); // explicitly setting the capacity
Arrays
• Arrays are OBJECTS in C#
• They have properties and methods unlike arrays in C++
• Length property tells you the size of the array • Is read-only and cannot be set
• Array indices are checked and if out of bounds, exceptions are thrown
• Examples:
1. int[] anArray = new int[]{1,2,3,4,5};
2. Console.WriteLine(anArray [5]); // throws an exception
3. int[,] anotherArray = new int[3, 6]; // a two dimensional array
C#:List (C++:vector)
• Link to List class on MSDN
• Generic class (like a template class)
• System.Collections.Generic Namespace
• Holds a collection of objects of the same type
• Indexed access
• Can remove at any valid index (RemoveAt)
• C++ vector has size() function, C# list has Count property
• Examples:
1. List
3. Console.WriteLine(myList[0]);
C#:HashSet
• Link to HashSet class on MSDN
• Hash set implementation
• Collection of unique items (no duplicates)
• Item insertion and lookup is close to O(1) (provided the hash table doesn’t need to resize internally)
• Generic class → Can use it to store a set of ANY type of object
• Add function
• Adds the item to the set if it isn’t already there • Otherwise does nothing
• Count property: the number of elements that are contained in the set
• HashSet vs Dictionary
C#:Dictionary
• Link to Dictionary class on MSDN
• Hash table implementation • Collection of key/value pairs • One key maps to one value
• Generic class → Can specify types for both the keys and values
• Has Count property that indicates the number of key value pairs in the
collection
• Has Add method to add a new key/value pair
• operator[] allows you to access items by key
C#:Dictionary – Example
Dictionary
students.Add(“Student B”, 87654321); Console.WriteLine(students[“Student A”]); Console.WriteLine(students[“Student B”]);
// Output?
12345678
87654321
Q: Anything wrong with the design here?
Stacks and Queues
• They’re in the standard C++ library and also in the .NET framework
• Within the System.Collections.Generic namespace: • Stack class
• Queue class
Math
• There’s a Math class (System.Math) that provides all the basic mathematical operations and values
• Static fields • Math.E
• Math.PI
• Static methods
• Math.Sin, Math.Cos
• Math.Abs
• Math.Floor, Math.Ceiling • many more methods
No more limits.h
• In C++ you had various min/max values for several types defined in limits.h
• In C# such limits are available as static fields from the types themselves
• int.MinValue, int.MaxValue
• Similar things exist for char, byte, short, ushort, uint, float and double
• What can we say about the cohesion of the types then?
• What can we say about the coupling of the framework?
Use MSDN
• More information found on MSDN
• Use the links within these notes as starting points and get a feel for how to search for information about types in the .NET framework
• Web searches like “string class MSDN” should get you easy access to information about types in C#/.NET
TODO before we move to the coding demo
• Talk about casting
• Don’t forget to fill the survey on BB before you leave!
Coding demo – Hello world
Let’s create the skeletal code for our main program (Program.cs)
• We want our program to behave as shown below:
• Print a menu for the user and ask him to choose
• Parse the user input and allow him to choose what to do next
Hello World – TODOs for today
1.
Implement Angle as a class and as a structure (use the lecture notes as a starting point)
Show a scenario where you observe that structures are passed by value and classes by reference
Create a BasicMessageClass
– Add a field “message”
– Add a property ”Message”
– Add 2 constructors (default and with 1 parameter – the message)
– Add a ”ShowMessage” method
2.
–
Hello World (cont.)
3.
In the main program
– Create an instance of BasicMessageClass with ”Hello World!”
– Show the message on the console (option 2) – Show the message in a text file (option 3)
– Show the message in a …
Implement a linked list to store positive integers – Create a class LinkedListNode
– In LinkedListNode we need a constructor
– Create a class LinkedList
– Implement method Add
4.
Where to start?
• Open VS
• Create a new solution. Use this solution for all in-class exercises. You
can call it ‘CptS321-in-class-exercises’ for example.
• Create a new project. Mine is called ‘HelloWorld’ because this is our first C# project
• Create a new class in the project, call it Program or Main or whatever else makes sense to you. This will be the main program that will display the menu and ask the user for input. Check the next slide for a template.
Where to start – template for our main program
using System;
class Program {
static void Main() {
Console.WriteLine(“Your code goes here…”); }
}