DEVCT 3 C For The Visual Basic Programmer

DEVCT 3: C# For The Visual ® Basic Programmer Drew Fletcher Product Unit Manager VC++, C# Microsoft Corporation Daniel Appleman President Desaware Corporation DEVCT 3

What Is C#? l A simpler C and C++ Ø Ø Ø l l No header or IDL files No macros No multiple inheritance First “component oriented” language in the C/C++ family Component concepts are first class: Ø Ø Ø Properties, methods, events Design-time and run-time attributes Integrated documentation using XML

Why Use C#? l l If you already use C/C++!!! A few things Visual Basic can’t do (today): Ø Ø Ø Operator overloading Direct access to memory But that’s about it!

Why Use Visual Basic Instead Of C#? l l l Performance is same as VB. Net You already know VB!! Advanced Visual Basic Ø C-oriented syntax developers should learn to Ø Case sensitive read C# source code Ø Not CLS compliant VB has: Ø Ø Ø Option Strict Background compilation Declarative event handling Standard Modules Late binding

Visual Basic Or C#? l For more information: “Visual Basic. Net or C#, Which to Choose? ” Author: Dan Appleman http: //www. desaware. com/VBor. CSharp. htm

Hello, C# using System; // A "Hello World!" program in C# class Hello { static void Main() { Console. Write. Line("Hello World!"); } }

C# Syntax And Style l Semi colons Ø l Curly braces { } Ø Ø Ø l Line breaks not significant Surround code blocks Not required for single line blocks Style is religious Ctrl K + Ctrl F (code formatter) Ctrl + ] for {} matching Ctrl M+ Ctrl O (Ctrl P) to collapse code Code comments Ø // or /*…*/

C# Syntax And Style l Case is significant Ø l Often see variables and types with same names, only case different In general, style guide: Ø Ø Use Mixed. Case for Public. Names Use camel. Case for: Ø Ø Ø l internal. Names (exception) parameter names CLS Compliance Return values Ø No Sub versus Function

Free form syntax C# block comments VB block comments Return values Collapsing code {} options (beautifier)

Statements And Control Flow l If Ø Ø l Requires bool expression = vs == No Else. If, sortof… No Then Switch Ø Ø Explicit break required Switch on strings allowed… Ø Ø … but remember case sensitivity Note: Visual Basic has support for objects, ranges

Control Flow: Iteration l do while for l for each l l Ø Ø Iterate over arrays or collections System. Collections… Ø Array. List, Hash. Table, Dictionary…

Predefined Types l C# predefined types Ø Ø Ø l Reference object, string Signed sbyte, short, int, long Unsigned byte, ushort, uint, ulong Floating-point float, double, decimal Character char (unicode) Logical bool Predefined types are simply aliases for system-provided types Ø For example, int == System. Int 32

Classes 101 l l In C# all code is based on classes. CS files can contain multiple classes Ø l …more common in C++ style languages Instantiate using new keyword Ø Ø Ø Slightly different from Visual Basic 6. 0… In. Net new creates the instance immediately Tip: use property/method to delay load

Classes: using statement l using statement Ø Ø Makes it easier to use namespaces Provide shortcut to fully qualified names VB equivalent: System. Win. Forms. Message. Box. Show("Hello"); using System. Win. Forms; Imports // Allows this: Message. Box. Show ("Hello"); // Instead of requiring this: System. Win. Forms. Message. Box. Show("Hello");

Classes: using statement l TIP: Use statement using statement completion & dynamic help Ø Makes it easier to use to namespaces identify class vs. Ø Provide shortcut to namespace fully qualified names Ø Can’t be used with classes …or use VB using System. Console; System. Console. Writeline("Hello"); // Not allowed!!!: Writeline ("Hello"); l Note: Visual Basic has project property for storing all “imports”

Classes: Namespace Statement l l Organize classes into a single hierarchical structure Namespaces can contain namespaces Ø l E. g. , dots (. ) allowed Typical design patterns: Ø namespace == dll name

Classes: Constructors l Called when object created Ø C# uses same name as class Ø Ø Ø Visual Basic calls it Sub New Use to pass variables to the class, and for general initialization Instantiate classes using the new keyword Point p = new Point (10, 20); l Note: if you don’t provide a constructor for your class, the compiler will

Classes: Constructors l Can provide multiple constructors Ø Ø Different parameters control which one gets called Intelli. Sense™ shows list String s = new String ( l No optional params in C# Ø Ø Implement overloads instead Versioning issue

Using Namespace Constructors

Classes: Inheritance l Inheritance Ø Ø l “: ” == derives from All objects : System. Object Polymorphism Ø Ø Ø VB => inherits Virtual Abstract Sealed

Classes: Inheritance C# Visual Basic Virtual Overridable Abstract (classes) Must. Inherit (methods) Must. Override Sealed (classes) Not. Inheritable (methods) Not. Overridable

Methods l Member functions Ø Ø Return values In parameters Ø Ø Ref parameters Ø Ø Passed by value, unless… VB: must be explicit, use byref or byval Allows you to modify value in place Out parameters Ø Ø Initialization not required Method assigns a value

public void Pass. Ref. Vars (ref int x, out int y) { x = 12; y = 10; } public void Test. Pass. Ref. Vars () { //passed byref, must be initialized int a = 0; //out param, no need for initialization int b; Pass. Ref. Vars (ref a, out b); }

Structs l l Value versus Reference Types Like classes, except Ø Ø Ø l Ideal for lightweight objects Ø Ø l Complex, point, rectangle, color int, float, double, etc. , are all structs Benefits Ø Ø l Stored in-line, not heap allocated Assignment copies data, not reference No inheritance No heap allocation, less GC pressure More efficient use of memory Boxing

struct Point { public int x; public int y; public Point (int x, int y) { this. x = x; this. y = y; } }

Properties l l l ‘get’, ‘set’ ‘value’ parameter Casing pattern private string my. Property; public virtual string My. Property { get { return my. Property; } set { my. Property = value; } }

Enums l Default: 1 st value = 0 public enum Country { France Germany Japan USA }

Enums l l Can specify values Can use expressions (based on values in the enumeration) public enum Pet { Cat = 1 Dog = 2 Monkey = Cat + Dog Horse = Dog * 2 + Monkey }
![Arrays VB: days(50) l Create array objects. Dim using new as Integer int[] days Arrays VB: days(50) l Create array objects. Dim using new as Integer int[] days](http://slidetodoc.com/presentation_image_h2/68474786b2484151dae7478b5b14c874/image-29.jpg)
Arrays VB: days(50) l Create array objects. Dim using new as Integer int[] days = new int[50]; string[] address = new string[20]; l Array values automatically initialized Ø int => 0’s Ø string => null’s l Can also initialize manually int[] days = {0, 1, 2, 5, 8, 12}; Int[] days = new int[6] {0, 1, 2, 5, 8, 12};

Arrays TIP: MD arrays easier to use Jagged arrays can be l Multidimensional faster arrays int[, ] matrix = new int[2, 3]; int[, ] matrix = {{1, 1}, {1, 2}, {2, 3}}; Int[, , ] cube = new int[2, 2, 2]; l Jagged array - an array of arrays int[][] matrix = new int[3][]; int[][] matrix = {new int[5], new int[3]};

Arrays l TIP: Ø Use System. Array class for sort, search, reverse, etc. ) int[] i = {4, 5, 2, 6}; System. Array. Sort(i); l TIP: Ø To get sort/search functionality on your own classes - Implement Equals() or IComparable()

Strings Immutable l Ø Strings cannot be modified inline String s = “Hello, world”; s "Hello world"

Strings Immutable l Ø Strings cannot be modified inline String s = “Hello, world”; s = “Goodbye”; s "Hello world" “Goodbye"

Strings Immutable l Ø Strings cannot be modified inline String s = “Hello, world”; s = “Goodbye”; s += “, cruel world”; s "Hello world" “Goodbye, cruel world"

Strings l l Lots of functionality in System. String!! Important: Methods that modify strings return a new string Compare() Compare. Ordinal() End. With() Copy. To()VB compatible Split() Insert() methods Substrng () in available Join() VB runtime. To. Lower() Starts. With() Pad. Left() To. Upper() Index. Of() Pad. Right() Trim() Last. Index. Of() Remove() Trim. End() Concat() Replace() Trim. Start() (Instr, Left, Mid, etc. )

Strings l String. Builder class Ø Ø Can modify strings inline Use in performance critical situations using System. Text; String. Builder sb = “Hello”; sb "Hello"

Strings l String. Builder class Ø Ø Can modify strings inline Use in performance critical situations using System. Text; String. Builder sb = “Hello”; sb. Append (“, world”); sb "Hello" "Hello, world"

Strings String. Builder class l Ø Ø Can modify strings inline Use in performance critical situations using System. Text; String. Builder sb = “Hello”; sb. Append (“, world”); String s = sb. To. String(); sb "Hello, world" s "Hello, world"

Strings – Indexing l Indexers Ø Ø System. String implements an indexer Iterate over characters in any string String s = “Hello, world”; for (int i = 0; i < s. Length; i++) Console. Write. Line (“Char: {0}”, s[i]});

Strings – Indexing l indexed Strings are read-only String s = “Hello, world”; Char c = s[4]; S[4] = ‘x’; //error: doesn’t compile l Indexed String. Builders are read-write l Note: char literals are single quotes String. Builder sb = new String. Builder (“Hello, world”); Char c = s[4]; sb[0] = ‘J’

Is. Palindrome

Strings l String. Format using System. Win. Forms; int i = 4; int j = 5; string s; s = String. Format("i = {0} and j = {1}", i, j ); Message. Box. Show (s); l System. Text. Regular. Expressions Ø Regex

String Literals using System. Text; String. Builder sb = new String. Builder(); sb. Append("Column A t Column Bn"); int i = 0; while (i++ < 10) { sb. Append (i. To. String() + "t" + (i*i). To. String() + "n"); } System. Win. Forms. Message. Box. Show(sb. To. String());