PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Slides:



Advertisements
Similar presentations
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
Advertisements

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Road Map Introduction to object oriented programming. Classes
VBA Modules, Functions, Variables, and Constants
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter 11: Classes and Data Abstraction
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
1.  A method describes the internal mechanisms that actually perform its tasks  A class is used to house (among other things) a method ◦ A class that.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
More about Class 靜宜大學資工系 蔡奇偉副教授 ©2011. 大綱 Instance Class Members Class members can be associated with an instance of the class or with the class as a.
Learners Support Publications Classes and Objects.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Classes and Multiform Projects.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Session 7 Methods Strings Constructors this Inheritance.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 5 Introduction to Defining Classes
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Introduction to Object-Oriented Programming Lesson 2.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
C# for C++ Programmers 1.
Creating Your Own Classes
Classes (Part 1) Lecture 3
Static data members Constructors and Destructors
Object-Oriented Programming: Classes and Objects
Chapter 3: Using Methods, Classes, and Objects
Chapter 3 Introduction to Classes, Objects Methods and Strings
CIS 199 Final Review.
Chengyu Sun California State University, Los Angeles
Presentation transcript:

PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1

Chapter 3- Objects and Types The differences between classes and structs Class members Passing values by value and by reference Method overloading Constructors and static constructors Read - only fields Partial classes Static classes The Object class, from which all other types are derived Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 2

Classes And Structs Classes and structs are essentially templates from which objects can be created. Each object contains data and has methods to manipulate and access that data. The class defines what data and functionality each particular object (called an instance ) of that class can contain. Examples: Class Struct class PhoneCustomer struct PhoneCustomerStruct{public int CustomerID;public string FirstName;public string LastName;} Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 3

Classes and Structs Structs differ from classes in the way that they are stored in memory and accessed Structs don’t support inheritance, and are used for smaller data types for performance reasons Instantiation of a class and Struct PhoneCustomer myCustomer = new PhoneCustomer(); // works for a class PhoneCustomerStruct myCustomer2 = new PhoneCustomerStruct();// works for a struct Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 4

Classes The data and functions within a class are known as the class’s members. Classes can contain nested types (such as other classes). Accessibility to the members can be public, protected, internal protected, private, or internal. Data Members Data members are those members that contain the data for the class — fields, constants, and events. Data members can be static. A class member is always an instance member unless it is explicitly declared as static. Fields are any variables associated with the class. Syntax to access the fields: Object. FieldName PhoneCustomer Customer1 = new PhoneCustomer(); Customer1.FirstName = "Simon"; //access the field Events are class members that allow an object to notify a caller whenever something noteworthy happens. Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 5

Function Members Function members are those members that provide some functionality for manipulating the data in the class. They include methods, properties, constructors, finalizers, operators, and indexers. Methods are functions that are associated with a particular class. Properties are sets of functions that can be accessed from the client in a similar way to the public fields of the class. Constructors are special functions that are called automatically when an object is instantiated. Finalizers are similar to constructors but are called when the CLR detects that an object is no longer needed. Operators, at their simplest, are actions such as + or –. Operator overloading is also possible with C#. Indexers allow your objects to be indexed in the same way as an array or collection. Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 6

Methods Declaring Methods: The definition of a method consists of any method modifiers, the type of the return value, followed by the name of the method, followed by a list of input arguments enclosed in parentheses, followed by the body of the method enclosed in curly braces. [modifiers] return_type MethodName([parameters]) { // Method body } Each parameter consists of the name of the type of the parameter, and the name by which it can be referenced in the body of the method. public bool IsSquare(Rectangle rect) { return (rect.Height == rect.Width); } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 7

Invoking Methods code snippet MathTest.cs class MathTest { static void Main(string[] args) { // Try calling some static functions. Console.WriteLine("Pi is " + MathTest.GetPi()); int x = MathTest.GetSquareOf(5); Console.WriteLine("Square of 5 is " + x); // Instantiate at MathTest object MathTest math = new MathTest(); // this is C#'s way of // instantiating a reference type // Call nonstatic methods math.value = 30; Console.WriteLine( "Value field of math variable contains " + math.value); Console.WriteLine("Square of 30 is " + math.GetSquare()); Console.ReadLine(); } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 8

class MathTest { public int value; public int GetSquare() { return value * value; } public static int GetSquareOf(int x) { return x * x; } public static double GetPi() { return ; } Results: Pi is Square of 5 is 25 Value field of math variable contains 30 Square of 30 is 900 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 9

Passing Parameters to Methods parameters can be passed into methods by reference or by value. When a variable is passed by reference, the called method gets the actual variable — so any changes made to the variable inside the method persist when the method exits. when a variable is passed by value, the called method gets an identical copy of the variable — which means any changes made are lost when the method exits. In C#, all parameters are passed by value unless specified. It also requires that variables be initialized with a starting value before they are referenced Example: code snippet ParameterTest.cs Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 10

class ParameterTest { static void SomeFunction(int[] ints, int i) { ints[0] = 100; i = 100; } public static int Main() { int i = 0; int[] ints = { 0, 1, 2, 4, 8 }; // Display the original values. Console.WriteLine("i = " + i); Console.WriteLine("ints[0] = " + ints[0]); Console.WriteLine("Calling SomeFunction."); // After this method returns, ints will be changed, // but i will not. SomeFunction(ints, i); Console.WriteLine("i = " + i); Console.WriteLine("ints[0] = " + ints[0]); Console.ReadLine(); return 0; } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 11

The output of this is: i = 0 ints[0] = 0 Calling SomeFunction... i = 0 ints [0] = 100 The value of i remains unchanged, but the value changed in ints is also changed in the original array. Strings don’t display the typical reference-type behavior as they are immutable. ref Parameters To force value parameters to be passed by reference, the ref keyword is used. static void SomeFunction(int[] ints, ref int i) { ints[0] = 100; i = 100; // The change to i will persist after SomeFunction() exits. } To invoke: SomeFunction(ints, ref i); Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 12

out Parameters The out parameter enables the functions to output more than one value from a single routine by assigning the output values to variables that have been passed to the method by reference. When a method’s input argument is prefixed with out, that method can be passed a variable that has not been initialized. static void SomeFunction(out int i) { i = 100; } To invoke: int i; // note how i is declared but not initialized. SomeFunction(out i); Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 13

Named Arguments Typically, parameters need to be passed into a method in the same order that they are defined. Named arguments allows to pass in parameters in any order. string FullName(string firstName, string lastName) { return firstName + " " + lastName; } The following method calls will return the same full name: FullName("John", "Doe"); FullName(lastName: "Doe", firstName: "John"); Optional Arguments Parameters can also be optional. A default value for optional parameters is required. Optional parameter(s) must be the last ones defined void TestMethod(int notOptionalNumber, int optionalNumber = 10) { System.Console.Write(optionalNumber + notOptionalNumber); } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 14

Method Overloading Method overloading - several versions of the method that have different signatures. Different signatures mean the same name, but a different number of parameters and/or different parameter data types. Method overloading carries with it the potential for subtle runtime bugs if the wrong overload is called. It is not sufficient for two methods to differ only in their return type or only by virtue of a parameter having been declared as ref or out. class ResultDisplayer { void DisplayResult(string result) { // implementation } void DisplayResult(int result) {// implementation } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 15

Properties The idea of a property is a method or pair of methods that is dressed to look like a field. The get accessor takes no parameters and must return the same type as the declared property. The compiler assumes that the set accessor takes one parameter, which is of the same type and is referred to as value. private int age; public int Age {get {return age; } set {age = value; } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 16

Properties contd. Read-Only and Write-Only Properties are created by simply omitting the set accessor and get accessor from the property definition respectively. C# does allow the set and get accessors to have differing access modifiers. It allows a property to have a public get and a private or protected set. If there isn’t going to be any logic in the properties set and get, then auto - implemented properties can be used. public string Age {get; set;} The declaration private int age; is not needed. Auto - implemented properties implement the backing member variable automatically. public string Age {get; private set;}// also allowed Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 17

Constructors A method that has the same name as the containing class and that does not have any return type. public class MyClass {public MyClass(){} // rest of class definition } It’s not necessary to provide a constructor, the compiler will make up a default one that initializes all the member fields by zeroing them out. Constructors follow the same rules for overloading as other methods. If any constructors that take parameters is provided, the compiler will not automatically supply a default one. The this keyword to distinguish member fields from parameters of the same name. It is possible to define constructors as private or protected. Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 18

Static Constructor It is also possible to write a static no-parameter constructor for a class. As opposed to the constructors written so far, which are instance constructors that are executed whenever an object of that class is created, Static constructors are executed only once. One reason for writing a static constructor is if a class has some static fields or properties that need to be initialized from an external source before the class is first used. The static constructor does not have any access modifiers. It’s never called by any other C# code, but always by the.NET runtime when the class is loaded. It is possible to have a static constructor and a zero-parameter instance constructor defined in the same class Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 19

Static Constructor Example public class UserPreferences { public static readonly Color BackColor; static UserPreferences() { DateTime now = DateTime.Now; if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday) BackColor = Color.Green; else BackColor = Color.Red; } private UserPreferences() { } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 20

Calling Constructors from Other Constructors class Car {private string description; private uint nWheels; public Car(string description, uint nWheels) {this.description = description; this.nWheels = nWheels; } public Car(string description) {this.description = description; this.nWheels = 4; }// this constructor can be written as follows public Car(string description): this(description, 4) { //Calling Constructors from Other Constructors } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 21

readonly fields The readonly field, is used on an occasion, when some variable’s value shouldn’t be changed, but the value is not known until runtime. The readonly keyword gives a bit more flexibility than const. public class DocumentEditor { public static readonly uint MaxDocuments; static DocumentEditor() {MaxDocuments = DoSomethingToFindOutMaxNumber(); } It is not required to assign a value to a readonly field in a constructor, a default value of its datatype is assigned automatically. That applies to both static and instance readonly fields. Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 22

Anonymous Types The var keyword, when used with the new keyword, anonymous types can be created. If an object that contains a person’s first, middle, and last name is to be created anonymously, the declaration would look like this: var doctor = new {FirstName = "Leonard", MiddleName = "", LastName = "McCoy"}; var captain = new {FirstName = "James", MiddleName = "T", LastName = "Kirk"}; [or] var captain = new {person.FirstName, person.MiddleName, person.LastName}; Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 23

Structs When only a small data structure is needed, for performance reasons a struct is probably preferred to a class. Structs are value types, not reference types. Structs do not support inheritance. The compiler always supplies a default no-parameter constructor for structs, which are not permitted to be replaced. With a struct, the specification on how the fields are to be laid out in memory can be done by the programmer. struct Dimensions { public double Length = 1; // error. Initial values not allowed public double Width = 2; // error. Initial values not allowed } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 24

Struct Example struct Dimensions { public double Length; public double Width; public Dimensions(double length, double width) {Length=length; Width=width; } public double Diagonal { get { return Math.Sqrt(Length*Length + Width*Width); } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 25

Partial Classes The partial keyword allows the class, struct, method or interface to span across multiple files. Typically, a class will reside entirely in a single file, but when it resides in multiple files then a partial class comes into play. For example, the class TheBigClass resides in two separate source files, BigClassPart1.cs and BigClassPart2.cs When the project that these two source files are part of is compiled, a single type called TheBigClass will be created with two methods, MethodOne() and MethodTwo() //BigClassPart1.cs partial class TheBigClass {public void MethodOne(){} } //BigClassPart2.cs partial class TheBigClass {public void MethodTwo(){} } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 26

Static Classes If a class contains nothing but static methods and properties, the class itself can become static. It is the same as creating a class with a private static constructor. An instance of the class can never be created and if created a compiler error occurs. static class StaticUtilities { public static void HelperMethod() { } To call the method: StaticUtilities.HelperMethod(); Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 27

The Object Class All.NET classes are ultimately derived from System.Object System.Object Methods ToString() - A fairly basic, quick-and-easy string representation which displays the contents of an object. GetHashCode() – If objects are placed in a data structure known as a map(Hash table), this method is used to determine where to place an object in the structure. Equals() (both versions) and ReferenceEquals() - Aimed at comparing the equality of objects. Finalize() - is called when a reference object is garbage collected to clean up resources. Hence the object is ignored by the garbage collector. GetType() - Returns an instance of a class derived from System.Type so this object can provide information about the class of which the object is a member, including base type, methods, properties, and so on. MemberwiseClone() - simply makes a copy of the object and returns a reference (or in the case of a value type, a boxed reference) to the copy. Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 28

The Tostring() method It provides the most convenient way to get a quick string representation of an object. Object.ToString() is actually declared as virtual. Public Class MainEntryPoint{ static void Main(string[] args) {Money cash1 = new Money(); cash1.Amount = 40M; Console.WriteLine("cash1.ToString() returns: " + cash1.ToString()); Console.ReadLine(); } public class Money {private decimal amount; public decimal Amount {get{return amount;} set{amount = value;} } public override string ToString() {return "$" + Amount.ToString();} } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 29

Extension Methods There are many ways to extend a class, like inheritance. Extension methods can help by allowing us to change a class without requiring the source code for the class. Extension methods are static methods that can appear to be part of a class without actually being in the source code for the class. For an extension method, the first parameter is the type that is being extended preceded by the this keyword. In the extension method, all the public methods and properties of the type being extended are accessible If the extension method has the same name as a method in the class, the extension method will never be called. Any instance methods already in the class take precedence. Example: public static class MoneyExtension { public static void AddToAmount(this Money money, decimal amountToAdd) { money.Amount += amountToAdd;} } Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 30

SUMMARY Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 31