550 likes | 717 Views
C#. Intro to C# Programming. From: http ://www.lcs.syr.edu/faculty/fawcett/handouts/coretechnologies/CSharp.htm. Statements And Expressions. Statements must do work int a=1; //valid assignment int a==1; //invalid expression Expressions must return a bool
E N D
C# Intro to C# Programming From: http://www.lcs.syr.edu/faculty/fawcett/handouts/coretechnologies/CSharp.htm
Statements And Expressions • Statements must do work int a=1; //valid assignment int a==1; //invalid expression • Expressions must return a bool bool b=(a>0);//valid expression/assignment a==a; //invalid:expression, no assignment • Some statements require expressions: • Loops: while, do-while, for, foreach • Branching: if, switch, goto • Boolean Assign
Predefined Types • C# predefined types • Reference object, string • Signed sbyte, short, int, long • Unsigned byte, ushort, uint, ulong • Character char • Floating-point float, double, decimal • Logical bool • Predefined types are simply aliases for system-provided types • For example, int == System.Int32
Operators • Binary Assignment: = a = 2 • Binary Mathmatical: • Plus: + 1+2 = 3 • Minus: - 2-2 = 0 • Multiply: * 3*2 = 6 • Divide: / 4/2 = 2 • Modulo: % 5%2=1 • Urnary: • Increment: ++ i++ same as i = i+1 • Increment: --i-- same as i = i-1 • Ternary: ?: (a>1)?(a=1):(a++);
Other Operators • Binary Comparison: • GT: > 5>2 true • GTE: >= 5>=2 true • LT: < 5<2 false • LTE: <= 5<=2 false • Equals: == 5==2 false • Other Logical Comparison: • And: && T&&F=F, T&&T=T • Or: ||T||F=T, F||F=F • Not: ! !true = false, !false = true
Operator Precedence • Primary: (x), x.y, x->y, f(x), a[x], x++, x--, … • Unaru: +, -, !, ~, ++x, --x, (T)x, *x, &x • Multiplicative: *,/ • Additive: +,- • Bit Shift: >>, << • Relational: <, >, <=, >=, is, as • Equality: ==, != • Bitwise AND: & • Bitwise OR: | • Conditional AND: && • Conditional OR ||
Demo HW#2 – PART A • Discuss the Visual Studios Development Environment • Variable Types and Declaration • Operators
Strings • To display any text, the value of the text is stored as a type called strings. • Strings are essentially named because you literally create them by stringing one or more characters together: string A = “Hello”; • To print a string to a console, just:Console.WriteLine(A); • Single Character: ‘A’ • Single Character String: “A”
String Methods – Part 1 • The string class support MANY methods for string manipulation and query, including: • Contains: Does string contains specified character/string • IndexOf/LastIndexOf :what is the index/last index of the specified character/string • Insert: at specified index, insert character/string • Length: Return the number of characters • Remove: Remove all instances of the supplied character/string • Replace: Replace every instance of the supplied character/string with other supplied character/string
String Methods – Part 2 • Split: Split the string into an array, based on a supplied token character/string • StartsWith: does a string start with the specified character/string • SubString: return a substring from starting index and total length • ToUpper/ToLower: Changes all characters to upper/lower case • Trim: Remove whitespace from beginning and end of string • Since string are arrays of characters, you can index with [ ]. For instance: char c = “Hello”[0];
for vsforeach foreach(object o in someList){ //do something useful o.UsefulReadOnlyOperation(); } for(inti=0;i<domeList.Length;i++){ object o = someList[i]; o.UsefulReadWriteOperation(); }
while vsdo-while inti = 0; while(i<someList.Length){ object o = someList[i++]; o.UsefulReadWriteOperation(); } do{ object o = someList[i++]; o.UsefulReadWriteOperation(); } while(i<someList.Length);
if vsswitch if(selectedDay == DAYS.SAT){ //do something fun for Saturday }else if(selectedDay == DAYS.SUN){ //do something restful for Sunday }else{ //go to work? } switch(selectedDay){ case DAYS.SAT: //do something fun for Saturday break; case DAYS.SUN: //do something restful for Sunday break; default: //go to work? break; }
goto Statement For now, No!
Demo HW#2 – PART B • Cover Console Output • Strings • For vs. For-each Loops
Program Structure • Namespaces • Contain types and other namespaces • Type declarations • Classes, structs, interfaces, enums, and delegates • Members • Constants, fields, methods, properties, indexers, events, operators, constructors, destructors • Organization • No header files, code written “in-line” • No declaration order dependence
Namespace using System; namespace UserNamespace { public Enum MY_ENUMERATION { ITEM_1, ITEM2, ETC… } public class UserClass : Inheritance { //define your class } public structUserStruct { //define your structure } }
Type System • Value types • Primitives inti; • Enumsenum State { Off, On } • Structsstruct Point { int x, y; } • Reference types • Classes class Foo: Bar, IFoo {...} • Interfaces interface IFoo: IBar {...} • Arrays string[] a = new string[10]; • Delegates delegate void Empty();
Type System • Value types • Directly contain data • Cannot be null • Reference types • Contain references to objects • May be null inti = 123; string s = "Hello world"; i 123 s "Hello world"
Enumerations • Strongly typed • No implicit conversions to/from integer • Operators: +, -, ++, --, &, |, ^, ~ • Can specify type: Byte, short, int, long enumColor : byte { Red = 1, Green = 2, Blue = 4, Black = 0, White = Red | Green | Blue, }
Enumerations • Strictly increasing discrete values, wrapped in constant named groupings. Like, Days of Week: EnumDaysOfWeek { SUN, //Sunday has value of 0 by default MON, //Monday has value of 1 TUES, //Tuesday has value of 2 WED, //Wednesday has value 3 THU = 4, //Thursday now assigned value 4 FRI, //Friday has value of 5 SAT = 0, //Error, since SUN already equals 0 }
Classes And Structs class CPoint { int x, y; ... } structSPoint { int x, y; ... } CPointcp = new CPoint(10, 20); SPointsp = new SPoint(10, 20); 10 sp 20 cp CPoint 10 20
Structs • Like classes, except • Stored in-line, not heap allocated • Assignment copies data, not reference • No inheritance • Ideal for light weight objects • Complex, point, rectangle, color • int, float, double, etc., are all structs
Classes • Single inheritance • Multiple interface implementation • Class members • Constants, fields, methods, properties, indexers, events, operators, constructors, destructors • Static and instance members • Nested types • Member access • public, protected, internal, private
Classes public class UserClass : InheritedClass, Interfaces { string classMemberVariable; public string ClassMemberProperty { get{return classMemberVariable;} get{classMemberVariable = value;} } public UserClass(){//constructor} public void Method(string someString) { //does something usful generally } }
Class Modifiers • public: item in class visible to everybody inside and outside the class • private: visible only to the class in which it was defined • protected: visible to the base class, where it was defined, and any child class inheriting the base class. • internal: base class items visible to any class inside the base class’s current assembly. • protected internal: base class items visible to any class in the current assembly of the child class.
Methods/Functions public string UserMethod( string arg ) { //declare variables local to this method string myReturn; //do other useful things myReturn = CallAUsefulMethod(arg); //return something useful return myReturn; } public string CallAUsefulMethod( string arg ) { return “Very Useful … Really!” + arg; }
Arrays • Allows you to create a set of objects. • You can iterate through objects of an array using any loop. For Example: int [] numbers = {1,2,3,4}; foreach( intnum in numbers ){ //does something } for( inti = 0; i< numbers.Length, i++){ intnum = numbers[i]; }
Generics • Generics are template classes that allow user to specify a generic type. • Creates a unique class definition for any type. • Provide set of properties like count, first, insert… • You only have to write the class once.
Generic Example T safeConvertValue<T>(string input) { T myReturn; if( T.TryParse(input, out myReturn) { return myReturn } else { return T.MinValue; } }
Generic Example void main() { Console.Write(“Enter an Integer:”); string input = Console.ReadLine(); int v = safeConvertValue<int>(input); if(v == int.MinValue) Console.Readline(“Invalid Value”); else Console.Readline(“Valid Value); }
Generic Lists/Array • List<T> inherits from IEnumerable<T> • IEnumerable<T> is the same as T[] • List<T> adds a bunch of functionality like length, first, insert, order, etc… • You can iterate through and access Lists exactly like arrays.
Methods of Static Classes • Static class do not require instantiation: public static Class NewMath { public static double PI{ get{return 3.14159;}} } public static void main() { Console.Write(“Input a Circle Radius: “); string radius = Console.ReadLine(); double r = double.parse(radius); double a = NewMath.PI * r * r; Console.WriteLine(“Area of a circle is: ” + a); }
Refactoring: • Print numbers 0 to 9: Console.WriteLine(“0”); Console.WriteLine(“1”); Console.WriteLine(“2”); Console.WriteLine(“3”); Console.WriteLine(“4”); Console.WriteLine(“5”); Console.WriteLine(“6”); Console.WriteLine(“7”); Console.WriteLine(“8”); Console.WriteLine(“9”); • Also, Print numbers 0 to 9: for(int j=0;j<9;j++) Console.WriteLine(j); Program Code Should Be Considered for Refactoring Only When: the Equivalent Logic Can be Written, AND The overall numbers of lines are less, AND The code is more maintainable
Demo HW#2 – PART C • Classes and Structures • Constructors • Methods/Functions • Static Methods • Arrays and Generic Lists • Introduce Refactoring
Console Input • Just like Console.WriteLinecan write text to the console, so, too, can Console.ReadLineget text from user input. • Input is a string, anywhere from zero to n characters. • May contain any character, printable or non-printable. • You must parse all input for safety.
Parsing Console Input • Let’s say you want a number, you ask for input, parse the input, and, on error, go back and ask for input, again: boolvalidInput = false; while( !validInput ) { Console.Write(“Input Integer: “); string input = Console.ReadLine(); intdesiredValue; if(int.TryParse( input, out desiredValue)) validInput = true; else Console.WriteLine(“That is not an integer”); }
Parse vs. Try-Parse? • All native types have a try-parse as well as a parse method. • Parse: • Will convert text to native type • Will throw an exception if text invalid • Try-Parse: • Will convert text to native type • Will return false if text invalid, true otherwise • However, Requires out parameter
Demo HW#2 – PART D • Cover Console Input • Input Validation using Try/Parse
Random Number Class • Random number class will generate a random number. • Seeded by time, so as random as possible. • Only pseudo random, as same seed generates same sequence of numbers Random r1 = new Random(); Random r2 = new Random(123); intvalue1 = r1.Next(max); intvalue2 = r2.Next(min, max);
Demo HW#2 – PART E • Random Number Class
Interfaces • Multiple inheritance • Can contain methods, properties, indexers, and events • Private interface implementations interface IDataBound { void Bind(IDataBinder binder); } class EditBox: Control, IDataBound { void IDataBound.Bind(IDataBinder binder) {...} }
Delegates • Object oriented function pointers • Multiple receivers • Each delegate has an invocation list • Thread-safe + and - operations • Foundation for events delegate void MouseEvent(int x, int y); delegate double Func(double x); Funcfunc = new Func(Math.Sin); double x = func(1.0);
Properties • Properties are “smart fields” • Natural syntax, accessors, inlining public class Button: Control { private string caption; public string Caption { get { return caption; } set { caption = value; Repaint(); } } } Button b = new Button(); b.Caption = "OK"; String s = b.Caption;
Events Sourcing • Define the event signature public delegate void EventHandler(object sender, EventArgs e); • Define the event and firing logic public class Button{ public event EventHandler Click; protected void OnClick(EventArgs e) { if (Click != null) Click(this, e); } }
Events Handling • Define and register event handler public class MyForm: Form { Button okButton; public MyForm() { okButton = new Button(...); okButton.Caption = "OK"; okButton.Click += new EventHandler(OkButtonClick); } void OkButtonClick(object sender, EventArgs e) { ShowMessage("You pressed the OK button"); } }
Default Constructors • A default constructor is created by default. • This allows the simple instantiation of objects, but then require all data values to be set: SomeClass class1 = new SomeClass(); class1.SomeProperty1 = propertyValue1; class1.SomeProperty2 = propertyValue2; class1.SomeProperty3 = propertyValue3; class1.SomeProperty4 = propertyValue4;
Default Constructors • A default constructor is created by default. • This allows the simple instantiation of objects, but then require all data values to be set: SomeClass class1 = new SomeClass(); class1.SomeProperty1 = propertyValue1; class1.SomeProperty2 = propertyValue2; class1.SomeProperty3 = propertyValue3; class1.SomeProperty4 = propertyValue4;
Custom Constructors • A default constructor is not created by default when custom constructors are created, although you may create a custom default constructor. • This allows the simple instantiation of objects and property values on one line: SomeClass class1 = new SomeClass(propertyValue1, propertyValue2, propertyValue3, propertyValue4);
Building Constructors • Constructors are added, similar to functions, for classes in which for which they are intended to be used. public class SomeClass { string prop1=“”, prop2=“”, prop3=“”, prop4=“”; public SomeClass(){} //default public SomeClass( string prop1, string prop2, string prop3, string prop4 ) { //custom this.prop1 = prop1; this.prop2 = prop2; this.prop3 = prop3; this.prop4 = prop4; } }