week 1 ====== Unified (Universal) Modeling Language (UML) - minus sign means private + plus sign means public ====================================== = Student = ====================================== = - StudentID; string = Private = - name; string = = - major; string = = - gpa; double = ====================================== = + ApplyForAdmission(); bool = Methods = + EnrollAsStudent(); bool = = + ChangeName(); = ====================================== Information hiding: is an important component of OOP Object is an instance of a class Inheritance: it is defining a subclass of data objects that share some or all of the parent class characteristics. Everything in C# is a class, even primitive variable types (int, float, doble, etc). All program statements in C# language are placed in a class. Every C# program uses at last one class. More OO than Java. C# is 100% OO. C# is used to develop: - mobile application - dynamic web pages - database access components - windows desktop applications - console based applications .Net framework: is a layer between the OS and the application *All code from each language (C#, C++, VB, J#) compiles to common Microsoft intermediate language (IL). ADO.Net Relational Databases Why C#?: - Most of the .Net class libraries are written in C#. - These classes or templates were designed for reuse by any .Net supported languages Through using the visual studio .Net IDE (Integrated Development Environment) and .Net framework, C# provides an easy way to create graphical user interface similar to VB. C# also provides the pure data crunching horsepower to which C and C++ programmers are accustomed. comments: /* */ // using System ^ (directive) namespace program ^ (identifier) When a console application is created visual studio .Net automatically references and imports the system namespace. static void Main() ^ modifier ^return type ^ method *static: implies that a single copy of the method is created and that we can access this method without having an object of the class COnsole.WriteLine("Hello") ^class ^method ^param cout cin Write() Read() WriteLine() ReadLine() - enter multiple characters Relationship between C# elements: class library namespace classes methods statements week 2 ====== Identifiers -> predefined (system, main, console, wrtieline) userdefined (class) C# is case sensitive. Convention for capitalizaing indentifiers - pascal case - first letter int the indentifier and the first letter of each subsequent concatenated word are captelized (MyNameIs, AverageSalary) - camel case - Hungarian Notation - first letter of an identifier is lowercase and the first letter of each subsequent concatentated word is capitalized (myNameIs, averageSalary) - upper case - constant variables only - int INCHES_PER_FOOT = 12; (constant) variables --------- represents an area in the computer memory Ex. int homeWorkScore = 100; Everytime we declare a variable int the C# language we are actually instantiating a class (creating an object) Ex. int homeWorkScore1; -- int examNumber1; - created 3 objects int numberOfPointsScored; -- We are instantiating the int class when these objects are created *In C# every program must include a class. In C# a simple data type such as a whole number (int) is implemented as a class. The primitive types (int, float) are classes in C# object -> instance or occurnace of classes. class -> an encapsulation of data and behaviors into a single package or unit *CTS -> Common Type System (job interview question - what is advantage of using .net framework?) - this enables cross language integration of code - a single project or application can be written using multiple languages such as C#, J#, VB .Net decimal - it is a new type not found in C++ or Java double extraPerson = 3.50; - note nothing float totalAmount = 23.57f; - note the "f" decimal number = 0.07m; - not the "m" boolean variable ---------------- bool moreDate = true; - the bool type will not accept values such as 0, 1, or -1 - you can only use true or false making data constant -------------------- const - forces the functionality of not allowing the value to be changed Ex. const int SPEED = 70; string ------ string fileLocation = "path"; + (concatenation) casts (type conversion) ----------------------- c# provides an explicit type conversion trhrough type casting (type) expression Ex. int value1 = 0, anotherNumber = 0; double value2 = 100, anotherDouble = 100; value1 = (int) value2; value2 = (double) anotherNumber (not necessary, it will do this automatically) Week 3 ====== formatting output ----------------- Console.out.writeline("The cost " + BEST_CARPET + "is {0:C}", totalCost); ^ currency We can format the results through the Console.out.write() method which calls the string format method automatically. Character Description --------- ----------- C or c currancy ($) F or f fixed point (automatically rounds) N or n number Console.out.write("{0:C}", 28.76); => $28.76 Console.out.write("{0:F4}", 50); => $50.0000 Console.out.write("{0:N}", 700976); => 700,976 Console.out.write("Carpet {0:F} is {1:C}.", 9, 14); => Carpet 9 is $14. Methods ------- - operations or behavior for the data member of a class - similar to functions, procedures - it is a group of statements placed together under a single name *- unlike some languages such as C and C++ that allows methods to be defined globally outside the class, we can't do this in C#. - methods have to be included in a class Modifiers --------- - how to access data and members const (to indicate that the value is constant and can not be changed) static (class.method - no object required to access members data, all main() method headings must include the static modifier) public private write(), writeline() and readline() are all static methods of Console class. Console.read() ^class ^method Methods defined as part of our user defined class, in which objects are instantiated, do not use static. Methods that use static modifier are called class methods. access modifiers in C# ---------------------- public - no restrictions on accessing public members of a class, other classes can reuse your class in different applications protected - limited to the containing class or classes derived from the containing class private - members are accessable only within the body of the class in which they are declared. internal - limited to the current project protected internal - limited to current project and classes derived from class Method Names ------------ CalculateSalesTax() -> pascal format *some languages place the void keyword inside the paranthesis in place of the parameter list to include that no parameters are needed. *C# does not allow this and generates a syntax error. Console.writeline("value1 {0} + value2 {1} " + " = value3 ({2})", 25, 75, (25+75)); => value1 25 + value2 75 = value3 (100) week 4 ====== Console.Read() - input a character from keyboard Console.ReadLine() - input string input from keyboard week 5 ====== Console.Read() In unicode decimal representation for a -> 97 (ascii) int aNumber; aNumber.Console.Read(); Console.WriteLine("character: ", aNumber); ------ output ------ character: 97 (gives ascii code) Console.WriteLine("character: ", (char) aNumber); ------ ^^^^^^ casting output ------ character: a (gives character) another option -------------- Console.WriteLine("The value: " + (char) Console.Read()); ------ ^^^^^^ casting output ------ character: a (gives character) - This single line is possible because the Console.Read() method allows the user to enter one character to read() method returns an int. The int value is cast to a character for display purposes and the value is then concatenated to the end of the string with '+' operator. Convert.ToDouble(); Convert.ToDecimal(); Convert.ToInt32(); Writing our own class methods ----------------------------- modifier returntype methodname (parameters) - general form { } returntype - specifies what kind of information is returned when the body of the method is finished executing. user defined method - methods that do not return a value, called void method methods that return a value, called return methods ***methods declared as "static" do not need an object to call (called class method), otherwise an object must be used. DisplayInstructions(); static void DisplayInstructions() {} The object concept ------------------ - By abstracting out the attributes (data) and behavior (method) we can create a class to serve a template from which many objects of that type can be instantiated private member data ------------------- The variables declared in the main method or other methods (our own) were only visible inside the body of the method in which they were declared. If we declare field(variable) inside the class but not inside any specific method they become visible to all members of the class, including all of the method members. Usually private is for the data usually public is for methods (functions) When we write an instance method we do not use static keyword in the heading. TO call an instance method, however, an object must be instantiated and associated with a method. Constructor ----------- When we instantiate a class(object), we actually create an instance of the class, an object that takes up space and exists. It is through a special method called constructors that we use to create instances of a class. Constructors differ from other methods in 2 ways ------------------------------------------------ 1) constructors do not return a value, but the keyword void is not included 2) constructors use the same identifier as the class name. - always use the 'public' access modifier for constructors so that other classes can instantiate objects of their type. week 6 ====== When we instantiate a class (object), we actually create an instance of the class, an object that takes up memory space. It is through a special method, called constructor that we use to create instances of class ** Constructors differ with other methods - have same name with a class - it does not return value A public access modifier is always associated with constructors so that other classes can instantiate objects of their type. As with overloaded methods, signatures must differ for constructors. You could not have one constructor that has the two string parameters or variables of firstName and lastName and then define another constructor that took string parameters of lastName & firstName. accesser (getters) ------------------ public double GetNoOfQuareYards() { return noOfSquareYards } - data members usually declared as private objects that instantiate one class may need to access members in another class by calling methods because methods are usually defined as public. * A Standard Naming convention is to add "Get" on the front of accessor mutator (setters) ----------------- public void SetNoOfSquareYards() { } * A Standard Naming convention is to add "Set" on the front of accessor Property (new feature in C#) ---------------------------- public double Price() { get { return PricePerYard; } set { PricePerSqYard = value; } } - provides a way to set/get private member data ** - get, set & value are not keywords Objects ------- classname objectname = new classname (arguements) - general form for declaring object & instantiating constructor ^ keyword to call constructor***** carpetCalculator pile = new carpetCalculator(37.90, 17.95); call by reference - use ref instead of & in C++ Boolean - true / false == equal to != not equal to 1 == 2 is false Relational Operators -------------------- greater than 8 > 5 true less than 1 < 2 true greater than or equal to 100 >= 100 true less than or equal to 100 <= 100 true ================================================================================================================ int aValue = 100; int bValue = 1000; char cValue = 'A'; string sValue = "cs958"; decimal money = 50.22m; double dValue = 50.22; ================================================================================================================ expression result explanation ========== ====== =========== if (money == 1000.00) syntax error Type mismatch - money is decimal & 1000.00 is double ^decimal ^ double if (money == 50.22m) true ^decimal if (money != dValue) syntax error Type mismatch if (aValue > bValue) false 100 is not greater than 1000 if (sValue < "cs") syntax error Can not be used with string. Could have used == or != though. if (aValue > dValue) true Integer aValue is converted to double & compared if (cValue = 'F') syntax error it is an assignment statement if (cValue < 'f') true unicode A has a value of 65 and unicode A has a value of 102. In C#, the == and != are defined to work with strings to compare the characters. Logical Operators ================= exp1 exp2 exp1 && exp2 exp1 || exp2 T T T T T F F T F T F T F F F F if (aValue > bValue) & (count++ < 100) - does counter to the right even if condition to the left is false week 7 ====== $ or | - useful for the situation that involves compound or complex expression in which you want the entire expression to be performed whether the result of the conditional expression returns true example: value = 3; value2 = 100; (value > value2) & (count++ < 100) - In this case (False) but still the increment continues by replacing the $$ with $ but produces the same false result. However, the side effect of incrementing "count" will continue. - one way statement if (expression) statement - two way statement if (expression) statement else statement - nest if ... else statement - when we place an if within an if, we create a nested if .. else statement, also referred to as a nested if statement. Long Way -------- if (hourlyEmployee && hours > 40) bonus = 500; if (hourlyEmployee && hours <= 40) bonus = 100; if (! hourlyEmployee && yearsEmployed > 10) bonus = 300; if (! hourslyEmployee && yearsEmployed <= 10) bonus = 200; Nested Way ---------- bool hourlyEmployee; double hours, bonus; int yearsEmployed if (hourlyEmployee) if (hours > 50) bonus = 500; else bonus = 100; else if (yearsEmployed > 10) bonus = 300; else bonus = 200; if (average > 89) grade = 'A'; elseif (average > 79) grade = 'B'; elseif (average > 69) grade = 'C' elseif (average > 59) grade = 'D' else grade = 'F' Switch Selection Statement -------------------------- The switch statement allows to perform a large number of alternatives based on a single variable - can only test on an integral (int, short, long), character or string ***It can not be used with a double, decimal or float Conditional Operator -------------------- grade = examScore > 89 ? 'A' : 'C' OR if (examScore > 89) grade = 'A'; else grade = 'C'; general format: expression1 ? expression2 : expression3; week 8 ====== *** readline() - use if inputting more than one character while loop - statement is a pretest loop while (condition statement) { statements; } The conditional expression is tested before any of the statement in the body of the loop are performed. Counter-controlled loop ----------------------- When we know the number of times the statement must be executed Sentinal-controlled loop ------------------------ Used for inputting data when we do not know the exact number of values to be entered. Sentinal value - extreme or dummy value Windows Applications using loops -------------------------------- An event_driven model manages the interaction between the user and the GUI by handling the repetition for us. C# has a predefined class called "MessageBox" that can be used for displaying information to users through it's show() method. MessageBoxButtons.OK MessageBoxButtons.OKCancel MessageBoxIcon.Exclamation State Controlled Loop --------------------- Similar to sentinal-controlled loop, state-controlled loops stop when a certain state is reached. Instead of requiring that the dummy value be entered after all values are processed, a special variable is used with a state-controlled loop. int[] number = {2, 4, 6, 8, 10} foreach (int val in number) { Console.WriteLine(val); } output ====== 2 4 6 8 10 Using the foreach statement -> available in C# only --------------------------- The foreach statement is new to the C#. It is used to move through a collection, such as an array. Values are usually accessed in the array using the identifier and an index representing the location of the element relative to the beginning of the first element. Review ------ namespace ASP.net - web applications compiler C# 100% Object Oriented const - constant, does not change static IDE scope of variables parameters - out / ref / params (Which of the following is not a parameter type?) switch, if/else statements do/while - executes at least once ++p, p++