Presentation is loading. Please wait.

Presentation is loading. Please wait.

Prof. Yousef B. Mahdy -2014-2015, Assuit University, Egypt Visual programming Using C# Prof. Yousef B. Mahdy Chapter four Classes and Objects.

Similar presentations


Presentation on theme: "Prof. Yousef B. Mahdy -2014-2015, Assuit University, Egypt Visual programming Using C# Prof. Yousef B. Mahdy Chapter four Classes and Objects."— Presentation transcript:

1 Prof. Yousef B. Mahdy -2014-2015, Assuit University, Egypt Visual programming Using C# Prof. Yousef B. Mahdy Chapter four Classes and Objects

2 2 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Introduction n Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. There are some basic programming concepts in OOP: »Abstraction »Polymorphism »Encapsulation »Inheritance n The abstraction is simplifying complex reality by modeling classes appropriate to the problem. The polymorphism is the process of using an operator or function in different ways for different data input. The encapsulation hides the implementation details of a class from other objects. The inheritance is a way to form new classes using classes that have already been defined.

3 3 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Objects n Objects are basic building blocks of a C# OOP program. An object is a combination of data and methods. The data and the methods are called members of an object. In an OOP program, we create objects. These objects communicate together through methods. Each object can receive messages, send messages and process data. n There are two steps in creating an object. First, we define a class. A class is a template for an object. It is a blueprint which describes the state and behavior that the objects of the class all share. A class can be used to create many objects. Objects created at runtime from a class are called instances of that particular class.

4 4 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Class n A class is a template that defines the form of an object. It specifies both the data and the code that will operate on that data. n C# uses a class specification to construct objects. Objects are instances of a class. Thus, a class is essentially a set of plans that specify how to build an object. It is important to be clear on one issue: A class is a logical abstraction. n It is not until an object of that class has been created that a physical representation of that class exists in memory. n If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable.static

5 5 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Class Definition n When you define a class, you declare the data that it contains and the code that operates on it. While very simple classes might contain only code or only data, most real-world classes contain both. n In general terms, data is contained in data members defined by the class, and code is contained in function members. It is important to state at the outset that C# defines several specific flavors of data and function members. For example, data members (also called fields) include instance variables and static variables. Function members include methods, constructors, destructors, indexers, events, operators, and properties. n For now, we will limit our discussion of the class to its essential elements. The other types of members are described in later chapters.

6 6 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. Following is the general form of a class definition:

7 7 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n Please note that: n Access specifiers specify the access rules for the members as well as the class itself, if not mentioned then the default access specifier for a class type is internal. Default access for the members is private. n Data type specifies the type of variable, and return type specifies the data type of the data, the method returns, if any. n To access the class members, you will use the dot (.) operator. n The dot operator links the name of an object with the name of a member.

8 8 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 n An access specifier which specifies how the member can be accessed. The access specifier is optional, and if absent, then the member is private to the class. Members with private access can be used only by other members of their class. While the members with public access can be used by all other code—even code defined outside the class. access type var-name; n The general form for declaring an instance variable is shown here: access type var-name; n Here, access specifies the access; type specifies the type of variable; and var-name is the variable’s name. Thus, aside from the access specifier, you declare an instance variable in the same way that you declare local variables.

9 9 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Access modifiers n Access modifiers set the visibility of methods and member fields. n C# has four access modifiers: public, protected, private and internal. n The public members can be accessed from anywhere. n The protected members can be accessed only within the class itself and by inherited and parent classes. n The private members are limited to the containing type, e.g. only within its class or interface. n The internal members may be accessed from within the same assembly (exe or DLL). n Access modifiers protect data against accidental modifications. They make the programs more robust.

10 10 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example

11 11 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1

12 12 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Objects Are Created n The following line was used to declare an object of type Building: n Box Box1 = new Box(); // Declare Box1 of type Box n This declaration performs three functions. First, it declares a variable called house of the class type Box. This variable is not, itself, an object. Instead, it is simply a variable that can refer to an object. Second, the declaration creates an actual, physical copy of the object. n This is done by using the new operator. Finally, it assigns to Box1 a reference to that object. Thus, after the line executes, Box1 refers to an object of type Building. n The new operator dynamically allocates (that is, allocates at runtime) memory for an object and returns a reference to it.

13 13 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n This reference is then stored in a variable. Thus, in C#, all class objects must be dynamically allocated. The fact that class objects are accessed through a reference explains why classes are called reference types. n As you might expect, it is possible to separate the declaration of house from the creation of the object to which it will refer, as shown here: ; // declare reference to object n Box Box1; // declare reference to object // allocate a Building object n Box1 = new Box(); // allocate a Building object n The first line declares Box1 as a reference to an object of type Box. Thus, Box1 is a variable that can refer to an object, but it is not an object, itself. The next line creates a new Box object and assigns a reference to it to Box1. Now, Box1 is linked with an object.

14 14 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Using new with Value Types n At this point, you might be asking why you don’t need to use new for variables of the value types, such as int or float? In C#, a variable of a value type contains its own value. Memory to hold this value is automatically provided when the program is run. Thus, there is no need to explicitly allocate this memory using new. Conversely, a reference variable stores a reference to an object. The memory to hold this object must be allocated dynamically, during execution. n As a point of interest, it is permitted to use new with the value types, as shown here: n int i = new int(); n Doing so invokes the default constructor for type int, which initializes i to zero. For example: n // Use new with a value type.

15 15 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 using System; class newValue { static void Main() { int i = new int(); // initialize i to zero Console.WriteLine("The value of i is: " + i); } n The output from this program is n The value of i is: 0 n In general, invoking new for a value type invokes the default constructor for that type. It does not, however, dynamically allocate memory. Frankly, most programmers do not use new with the value types.

16 16 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Garbage Collection and Destructors n As you have seen, objects are dynamically allocated from a pool of free memory by using the new operator. Of course, memory is not infinite, and the free memory can be exhausted. Thus, it is possible for new to fail because there is insufficient free memory to create the desired object. For this reason, one of the key components of any dynamic allocation scheme is the recovery of free memory from unused objects, making that memory available for subsequent reallocation. n In many programming languages, the release of previously allocated memory is handled manually. For example, in C++, the delete operator is used to free memory that was allocated. However, C# uses a different, more trouble-free approach: garbage collection. n C#’s garbage collection system reclaims objects automatically— occurring transparently, behind the scenes, without any programmer intervention.

17 17 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n It works like this: When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object is eventually released and collected. This recycled memory can then be used for a subsequent allocation. n It is possible to define a method that will be called just prior to an object’s final destruction by the garbage collector. This method is called a destructor, and it can be used in some highly specialized situations to ensure that an object terminates cleanly. For example, you might use a destructor to ensure that a system resource owned by an object is released. n Destructors have this general form: ~class-name( ) { // destruction code }

18 18 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# The this Keyword n When a method is called, it is automatically passed a reference to the invoking object (that is, the object on which the method is called). This reference is called this. Therefore, this refers to the object on which the method is acting. To understand this, first consider a program that creates a class called Rect that encapsulates the width and height of a rectangle and that includes a method called Area( ) that returns its area. using System; class Rect { public int Width; public int Height; public Rect(int w, int h) { Width = w; Height = h;}

19 19 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 public int Area() { return Width * Height; } class UseRect { static void Main() { Rect r1 = new Rect(4, 5); Rect r2 = new Rect(7, 9); Console.WriteLine("Area of r1: " + r1.Area()); Console.WriteLine("Area of r2: " + r2.Area()); }

20 20 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n As you know, within a method, the other members of a class can be accessed directly, without any object or class qualification. Thus, inside Area(), the statement n return Width * Height; n means that the copies of Width and Height associated with the invoking object will be multiplied together and the result returned. However, the same statement can also be written like this: n return this.Width * this.Height; n Here, this refers to the object on which Area( ) was called. Thus, this.Width refers to that object’s copy of Width, and this.Height refers to that object’s copy of Height. For example, if Area() had been invoked on an object called x, then this in the preceding statement would have been referring to x. Writing the statement without using this is really just shorthand. n Actually, no C# programmer would use this as just shown because nothing is gained and the standard form is easier. However, this has some important uses.

21 21 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 n For example, the C# syntax permits the name of a parameter or a local variable to be the same as the name of an instance variable When this happens, the local name hides the instance variable. You can gain access to the hidden instance variable by referring to it through this. For example, the following is a syntactically valid way to write the Rect() constructor: public Rect(int Width, int Height) { this.Width = Width; this.Height = Height; }

22 22 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Function Members n A function member contains executable code that performs work for the class. The following are examples of function members in C#: n Methods n Properties n Events n Indexers n User - defined operators n Constructors n Destructors

23 23 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Methods n A method is a code block containing a series of statements. Methods must be declared within a class or a structure. It is a good programming practice that methods do only one specific task. Methods bring modularity to programs. Proper use of methods bring the following advantages: »Reducing duplication of code »Decomposing complex problems into simpler pieces »Improving clarity of the code »Reuse of code »Information hiding n Basic characteristics of methods are: »Access level »Return value type »Method name & Method parameters »Parentheses »Block of statements

24 24 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n Access level of methods is controlled with access modifiers. They set the visibility of methods. They determine who can call the method. n Methods may return a value to the caller. In case our method returns a value, we provide its data type. If not, we use the void keyword to indicate that our method does not return values. n Method parameters are surrounded by parentheses and separated by commas. Empty parentheses indicate that the method requires no parameters. n The method block is surrounded with { } characters. The block contains one or more statements that are executed, when the method is invoked. It is legal to have an empty method block. return type n A method signature is a unique identification of a method for the C# compiler. The signature consists of a method name and the type and kind (value, reference, or output) of each of its formal parameters. Method signature does not include the return type. n Any legal character can be used in the name of a method. By convention, method names begin with an uppercase letter.

25 25 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n As explained, instance variables and methods are two of the primary constituents of classes. In C#, every function must be associated with a class. A function defined with a class is known as a method. n Methods are subroutines that manipulate the data defined by the class and, in many cases, provide access to that data. Typically, other parts of your program will interact with a class through its methods. The general form of a method is shown here: access ret-type name(parameter-list) { // body of method } n Here, access is an access modifier that governs what other parts of your program can call the method. The ret-type specifies the type of data returned by the method. This can be any valid type, including class types that you create.

26 26 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 n If the method does not return a value, its return type must be void. n The name of the method is specified by name. This can be any legal identifier other than those that would cause conflicts within the current declaration space. The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. n There are two forms of return: one for use in void methods (those that do not return a value) and one for returning values. n In a void method, you can cause the immediate termination of a method by using this form of return: n return ;

27 27 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 4 n When this statement executes, program control returns to the caller, skipping any remaining code in the method. For example, consider this method: public void MyMeth() { int i; for(i=0; i<10; i++) { if(i == 5) return; // stop at 5 Console.WriteLine(); }} n Here, the for loop will only run from 0 to 5, because once i equals 5, the method returns. It is permissible to have multiple return statements in a method. For example, public void MyMeth() { if(done) return; if(error) return; }

28 28 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 5 n To review: A void method can return in one of two ways—its closing curly brace is reached, or a return statement is executed. n Example: public void setLength( double len ) { length = len; } n Although methods with a return type of void are not rare, most methods will return a value. In fact, the ability to return a value is one of a method’s most useful features. Methods return a value to the calling routine using this form of return: return value; n Here, value is the value returned.

29 29 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 6 n As an example: public double getVolume() { return length * breadth * height; } n It is possible to pass one or more values to a method when the method is called. A value passed to a method is called an argument. Inside the method, the variable that receives the argument is called a formal parameter, or just parameter, for short. Parameters are declared inside the parentheses that follow the method’s name. The parameter declaration syntax is the same as that used for variables. The scope of a parameter is the body of its method.

30 30 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example using System; class ChkNum { // Return true if x is prime. public bool IsPrime(int x) { if(x <= 1) return false; for(int i=2; i <= x/i; i++) if((x %i) == 0) return false; return true; } class ParmDemo { static void Main() { ChkNum ob = new ChkNum(); for(int i=2; i < 10; i++) if(ob.IsPrime(i)) Console.WriteLine(i + " is prime.");

31 31 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 else Console.WriteLine(i + " is not prime."); } n Here is the output produced by the program: 2 is prime. 3 is prime. 4 is not prime. 5 is prime. 6 is not prime. 7 is prime. 8 is not prime. 9 is not prime.

32 32 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n A method can have more than one parameter. Simply declare each parameter, separating one from the next with a comma. For example, here the ChkNum class is expanded by adding a method called LeastComFactor(), which returns the smallest factor that its two arguments have in common. In other words, it returns the smallest whole number value that can evenly divide both arguments. using System; class ChkNum { // Return true if x is prime. public bool IsPrime(int x) { if(x <= 1) return false; for(int i=2; i <= x/i; i++) if((x %i) == 0) return false; return true; }

33 33 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 // Return the least common factor. public int LeastComFactor(int a, int b) { int max; if(IsPrime(a) || IsPrime(b)) return 1; max = a < b ? a : b; for(int i=2; i <= max/2; i++) if(((a%i) == 0) && ((b%i) == 0)) return i; return 1; }

34 34 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 4

35 35 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 5 n Notice that when LeastComFactor( ) is called, the arguments are also separated by commas. The output from the program is shown here: 2 is prime. 3 is prime. 4 is not prime. 5 is prime. 6 is not prime. 7 is prime. 8 is not prime. 9 is not prime. Least common factor for 7 and 8 is 1 Least common factor for 100 and 8 is 2 Least common factor for 100 and 75 is 5

36 36 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# How Arguments Are Passed n let’s review the two ways in which an argument can be passed to a subroutine. n The first way is call-by-value. This method copies the value of an argument into the formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument used in the call. n By default, C# uses call-by-value, which means that a copy of the argument is made and given to the receiving parameter. Thus, when you pass a value type, such as int or double, what occurs to the parameter that receives the argument has no effect outside the method.

37 37 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example using System; class Test { public void NoChange(int i, int j) { i = i + j; j = -j; }} class CallByValue { static void Main() { Test ob = new Test(); int a = 15, b = 20; Console.WriteLine("a and b before call: " +a+ " " + b); ob.NoChange(a, b); Console.WriteLine("a and b after call: " + a+ " " + b); } The output from this program is shown here: a and b before call: 15 20 a and b after call: 15 20

38 38 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n The second way an argument can be passed is call-by-reference. In this method, a reference to an argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this reference is used to access the actual argument specified in the call. This means that changes made to the parameter will affect the argument used to call the subroutine. n When you pass a reference to a method, the reference, itself, is still passed by value. Thus, a copy of the reference is made and changes to the parameter will not affect the argument. However— and this is a big however—changes made to the object being referred to by the parameter will affect the object referred to by the argument. Let’s see why. n Recall that when you create a variable of a class type, you are only creating a reference to an object. Thus, when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument. Therefore, the argument and the parameter will both refer to the same object.

39 39 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n This means that objects are passed to methods by what is effectively call-by-reference. Thus, changes to the object inside the method do affect the object used as an argument. For example, consider the following program: using System; class Test { public int a, b; public Test(int i, int j) { a = i; b = j; } public void Change(Test ob) { ob.a = ob.a + ob.b; ob.b = -ob.b; }

40 40 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 class CallByRef { static void Main() { Test ob = new Test(15, 20); Console.WriteLine("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.Change(ob); Console.WriteLine("ob.a and ob.b after call: " + ob.a + " " + ob.b); } This program generates the following output: ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 35 -20

41 41 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 4 n As you can see, in this case, the actions inside Change( ) have affected the object used as an argument. n To review: When a reference is passed to a method, the reference itself is passed by use of call-by-value. Thus, a copy of that reference is made. However, the copy of that reference will still refer to the same object as its corresponding argument. This means that objects are implicitly passed using call-by-reference.

42 42 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Use ref and out Parameters n C# supports two ways of passing arguments to methods: by value and by reference. The default passing of arguments is by value. When we pass arguments by value, the method works only with the copies of the values. This may lead to performance overheads when we work with large amounts of data. n You can, however, alter this behavior. Through the use of the ref and out keywords, it is possible to pass any of the value types by reference. Doing so allows a method to alter the argument used in the call. n Before going into the mechanics of using ref and out, it is useful to understand why you might want to pass a value type by reference. In general, there are two reasons: to allow a method to alter the contents of its arguments or to allow a method to return more than one value.

43 43 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n As you know, a return statement enables a method to return a value to its caller. However, a method can return only one value each time it is called. What if you need to return two or more pieces of information? n For example, what if you want to create a method that decomposes a floating-point number into its integer and fractional parts? To do this requires that two pieces of information be returned: the integer portion and the fractional component. This method cannot be written using only a single return value. The out modifier solves this problem. n Often you will want a method to be able to operate on the actual arguments that are passed to it. The quintessential example of this is a Swap() method that exchanges the values of its two arguments.

44 44 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n Since value types are passed by value, it is not possible to write a method that swaps the value of two ints, for example, using C#’s default call-by-value parameter passing mechanism. The ref modifier solves this problem. n Which way of passing arguments should we use? It depends on the situation. Say we have a set of data, for example salaries of employees. If we want to compute some statistics of the data, we do not need to modify them. We can pass by values. If we work with large amounts of data and the speed of computation is critical, we pass by reference. If we want to modify the data, e.g. do some reductions or raises to the salaries, we might pass by reference.

45 45 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 using System; class RefTest { public void Sqr(ref int i) { i = i * i; } class RefDemo { static void Main() { RefTest ob = new RefTest(); int a = 10; Console.WriteLine("a before call: " + a); ob.Sqr(ref a); // notice the use of ref Console.WriteLine("a after call: " + a); } The output from this program: a before call: 10 a after call : 100

46 46 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 4 n Using ref, it is now possible to write a method that exchanges the values of its two value-type arguments. n Here is one important point to understand about ref: An argument passed by ref must be assigned a value prior to the call. The reason is that the method that receives such an argument assumes that the parameter refers to a valid value. Thus, using ref, you cannot use a method to give an argument an initial value. n If your intention is to use the variables solely to obtain some return values from the method, you can use the out keyword, which is identical to the ref keyword except that it does not require the variables passed in to be initialized first.

47 47 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 5 using System; class Decompose { /* Decompose a floating-point value into its integer and fractional parts. */ public int GetParts(double n, out double frac) { int whole; whole = (int) n; frac = n - whole; // pass fractional part back through frac return whole; // return integer portion } class UseOut { static void Main() { Decompose ob = new Decompose(); int i;

48 48 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 6 double f; i = ob.GetParts(10.125, out f); Console.WriteLine("Integer portion is " + i); Console.WriteLine("Fractional part is " + f); } n The output from the program is shown here: Integer portion is 10 Fractional part is 0.125 n The GetParts() method returns two pieces of information. First, the integer portion of n is returned as GetParts( )’s return value. Second, the fractional portion of n is passed back to the caller through the out parameter frac. As this example shows, by using out, it is possible for one method to return two values.

49 49 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 7 n The out keyword is similar to the ref keyword. The difference is that when using the ref keyword, the variable must be initialized before it is being passed. With the out keyword, it may not be initialized. Both the method definition and the method call must use the out keyword.

50 50 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Use ref and out on References n The use of ref and out is not limited to the passing of value types. They can also be used when a reference is passed. When ref or out modifies a reference, it causes the reference, itself, to be passed by reference. This allows a method to change what object the reference refers to. Consider the following program, which uses ref reference parameters to exchange the objects to which two references are referring: // Swap two references. using System; class RefSwap { int a, b; public RefSwap(int i, int j) { a = i; b = j; } public void Show() { Console.WriteLine("a: {0}, b: {1}", a, b);}

51 51 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 // This method changes its arguments. public void Swap(ref RefSwap ob1, ref RefSwap ob2) { RefSwap t; t = ob1; ob1 = ob2; ob2 = t; } class RefSwapDemo { static void Main() { RefSwap x = new RefSwap(1, 2); RefSwap y = new RefSwap(3, 4); Console.Write("x before call: "); x.Show(); Console.Write("y before call: ");

52 52 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 y.Show(); Console.WriteLine(); x.Swap(ref x, ref y); Console.Write("x after call: "); x.Show(); Console.Write("y after call: "); y.Show(); } n The output from this program is shown here: x before call: a: 1, b: 2 y before call: a: 3, b: 4 x after call: a: 3, b: 4 y after call: a: 1, b: 2

53 53 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example n A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself.reference type n To do that, pass the parameter using the ref or out keyword. For simplicity, the following examples use ref.refout class PassingRefByVal { static void Change(int[] pArray) { pArray[0] = 888; pArray = new int[5] {-3, -1, -2, -3, -4}; System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]); }

54 54 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 static void Main() { int[] arr = {1, 4, 5}; System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr [0]); Change(arr); System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr [0]); } n Output:

55 55 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Use a Variable Number of Arguments n Sometimes you will want to create a method that can be passed an arbitrary number of arguments. For example, consider a method that finds the smallest of a set of values. Such a method might be passed as few as two values, or three, or four, and so on. In all cases, you want that method to return the smallest value. Such a method cannot be created using normal parameters. Instead, you must use a special type of parameter that stands for an arbitrary number of parameters. This is done by creating a params parameter. n A method can take variable number of arguments. For this we use the params keyword. No additional parameters are permitted after the params keyword. Only one params keyword is permitted in a method declaration. n The params modifier is used to declare an array parameter that will be able to receive zero or more arguments. The number of elements in the array will be equal to the number of arguments passed to the method. Your program then accesses the array to obtain the arguments.

56 56 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example using System; public class SumOfValues{ static void Main(){ Sum(1, 2, 3); Sum(1, 2, 3, 4, 5); } static void Sum(params int[] list){ Console.WriteLine("There are {0} items", list.Length); int sum = 0; foreach (int i in list) { sum = sum + i; } Console.WriteLine("Their sum is {0}", sum); }

57 57 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n We create a Sum() method which can take variable number of arguments. The method will calculate the sum of values passed to the method: Sum(1, 2, 3); Sum(1, 2, 3, 4, 5); n We call the Sum() method twice. In one case, it takes 3 arguments, in the second case 5. We call the same method. The Sum() method can take variable number of integer values. All values are added to the list array. We compute the sum of the values in the list. n Output: n There are 3 items n Their sum is 6 n There are 5 items n Their sum is 15

58 58 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example using System; class Min { public int MinVal(params int[] nums) { int m; if(nums.Length == 0) { Console.WriteLine("Error: no arguments."); return 0; } m = nums[0]; for(int i=1; i < nums.Length; i++) if(nums[i] < m) m = nums[i]; return m; }

59 59 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1

60 60 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n The output from the program is shown here: n Minimum is 10 n Minimum is -1 n Minimum is 3 n Minimum is 8

61 61 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Return Objects n A method can return any type of data, including class types. For example, the following n version of the Rect class includes a method called Enlarge( ) that creates a rectangle that n is proportionally the same as the invoking rectangle, but larger by a specified factor: // Return an object. using System; class Rect { int width; int height; public Rect(int w, int h) { width = w; height = h; } public int Area() { return width * height; }

62 62 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 public void Show() { Console.WriteLine(width + " " + height); } public Rect Enlarge(int factor) { return new Rect(width * factor, height * factor); }} class RetObj { static void Main() { Rect r1 = new Rect(4, 5); Console.Write("Dimensions of r1: "); r1.Show(); Console.WriteLine("Area of r1: " + r1.Area()); Console.WriteLine(); Rect r2 = r1.Enlarge(2);

63 63 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 Console.Write("Dimensions of r2: "); r2.Show(); Console.WriteLine("Area of r2: " + r2.Area()); } n The output is shown here: Dimensions of r1: 4 5 Area of r1: 20 Dimensions of r2: 8 10 Area of r2: 80

64 64 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 n When an object is returned by a method, it remains in existence until there are no more references to it. At that point, it is subject to garbage collection. Thus, an object won’t be destroyed just because the method that created it terminates.

65 65 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Return an Array n Since in C# arrays are implemented as objects, a method can also return an array. (This differs from C++ in which arrays are not valid as return types.) For example, in the following program, the method FindFactors( ) returns an array that holds the factors of the argument that it is passed: using System; class Factor { public int[] FindFactors(int num, out int numfactors) { int[] facts = new int[80]; // size of 80 is arbitrary int i, j; for(i=2, j=0; i < num/2 + 1; i++) if( (num%i)==0 ) { facts[j] = i; j++; } numfactors = j; return facts; } }

66 66 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 class FindFactors { static void Main() { Factor f = new Factor(); int numfactors; int[] factors; factors = f.FindFactors(1000, out numfactors); Console.WriteLine("Factors for 1000 are: "); for(int i=0; i < numfactors; i++) Console.Write(factors[i] + " "); Console.WriteLine(); } n The output is shown here: Factors for 1000 are: 2 4 5 8 10 20 25 40 50 100 125 200 250 500

67 67 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Avoiding Unreachable Code n When creating methods, you should avoid causing a situation in which a portion of code cannot, under any circumstances, be executed. This is called unreachable code, and it is considered incorrect in C#. The compiler will issue a warning message if you create a method that contains unreachable code. For example: public void MyMeth() { char a, b; if(a==b) { Console.WriteLine("equal"); return; } else { Console.WriteLine("not equal"); return;} Console.WriteLine("this is unreachable");}

68 68 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n Here, the method MyMeth( ) will always return before the final WriteLine( ) statement is executed. If you try to compile this method, you will receive a warning. In general, unreachable code constitutes a mistake on your part, so it is a good idea to take unreachable code warnings seriously.

69 69 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Named and Optional Arguments n Visual C# 2010 introduces named and optional arguments. n Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. n Optional arguments enable you to omit arguments for some parameters. n Both techniques can be used with methods, indexers, constructors, and delegates. n When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list. n Named and optional parameters, when used together, enable you to supply arguments for only a few parameters from a list of optional parameters.

70 70 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Named arguments n Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. For example, a function Calculate can be called in the standard way by sending arguments for weight and height by position, in the order defined by the function. n Calculate (123, 64); n If you do not remember the order of the parameters but you do know their names, you can send the arguments in either order, weight first or height first. n Calculate (weight: 123, height: 64); n Calculate (height: 64, weight: 123); n A named argument can follow positional arguments, as shown here. n CalculateBMI(123, height: 64); n However, a positional argument cannot follow a named argument. The following statement causes a compiler error. n //CalculateBMI(weight: 123, 64);

71 71 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 Optional Arguments n The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. n Each optional parameter has a default value as part of its definition. n If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions: »a constant expression; »an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;enumstruct »an expression of the form default(ValType), where ValType is a value type.default(ValType)

72 72 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. n Comma-separated gaps in the argument list are not supported. For example, in the following code, instance method ExampleMethod is defined with one required and two optional parameters. n public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10) n The following call to ExampleMethod causes a compiler error, because an argument is provided for the third parameter but not for the second. n //anExample.ExampleMethod(3,,4);

73 73 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n However, if you know the name of the third parameter, you can use a named argument to accomplish the task. n anExample.ExampleMethod(3, optionalint: 4); n IntelliSense uses brackets to indicate optional parameters, as shown in the following illustration. n Optional parameters in ExampleMethod

74 74 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example n In the following example, the constructor for ExampleClass has one parameter, which is optional. Instance method ExampleMethod has one required parameter, required, and two optional parameters, optionalstr and optionalint. The code in Main shows the different ways in which the constructor and method can be invoked. namespace OptionalNamespace{ class OptionalExample{ static void Main(string[] args){ //Instance anotherExample does not send an argument for the // constructor's optional parameter. ExampleClass anExample = new ExampleClass(); anExample.ExampleMethod(1, "One", 1); anExample.ExampleMethod(2, "Two"); anExample.ExampleMethod(3);

75 75 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 //Instance anotherExample sends an argument for the // constructor's optional parameter. ExampleClass anotherExample = new ExampleClass("Provided name"); anotherExample.ExampleMethod(1, "One", 1); anotherExample.ExampleMethod(2, "Two"); anotherExample.ExampleMethod(3); anExample.ExampleMethod(3, optionalint: 4); } class ExampleClass { private string _name; public ExampleClass(string name = "Default name“){ _name = name; }

76 76 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10) { Console.WriteLine("{0}: {1}, {2}, and {3}.", _name, required, optionalstr, optionalint); } The output:

77 77 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Not everything derives from object n First off, no pointer types derive from object, nor are any of them convertible to object. Unsafe pointer types are explicitly outside of the normal type rules for the language. (If you want to treat a pointer as a value type, convert it to System.IntPtr, and then you can use it as a value type.) We'll leave pointer types aside for the rest of this discussion. n Interface types, not being classes, are not derived from object. They are all convertible to object, to be sure, because we know that at runtime the instance will be a concrete type. But interfaces only derive from other interface types, and object is not an interface type. n In a generic type or method definition, a type parameters is a placeholder for a specific type that a client specifies when they instantiate a variable of the generic type. A generic class, such as GenericList cannot be used as-is because it is not really a type; it is more like a blueprint for a type.

78 78 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n To use GenericList, client code must declare and instantiate a constructed type by specifying a type argument inside the angle brackets. The type argument for this particular class can be any type recognized by the compiler. n "Open" type parameter types are also not derived from object. They are, to be sure, types. You can make a field whose type is a type parameter type. And since generic types and methods ultimately are only ever used at runtime when fully "constructed" with "concrete" type arguments, type parameter types are always convertible to object. n The way to correct this myth is to simply replace "derives from" with "is convertible to", and to ignore pointer types: every non- pointer type in C# is convertible to object.

79 79 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# The dynamic keyword n Here is a short example that demonstrates some of the benefits and problems of using the object keyword. n object obj = 10; Console.WriteLine(obj.GetType()); n // obj = obj + 10; n A compiler error, because at compile time the type of obj is System.Object. n You need to explicitly cast obj to a necessary type. obj = (int)obj + 10; n As you can see, although obj stores an integer, the compiler does not let you to perform any mathematical operations without a cast. It may look like casting helps you to ensure that you really have an integer, but it doesn’t. You can cast to a completely different type and the compiler will not detect it. As a result, you get a run-time exception (Example : MessageBox.Show((obj =(string)obj+10).ToString());).

80 80 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n So you have to perform an explicit cast that does not guarantee anything just because the compiler doesn’t let you to run your program without a cast. n Here is where the new dynamic keyword in C# 4.0 comes in. It tells the compiler not to enforce additional rules upon your code.dynamic n // Same as "object". dynamic dyn = 10; Console.WriteLine(dyn.GetType()); n // Also, this operation will succeed for all numeric or other types that support a “+” operation. n dyn = 10.0; n dyn = dyn + 10; n dyn = "10"; n dyn = dyn + 10;

81 81 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n This is one of the main differences between object and dynamic – with dynamic you tell the compiler that the type of an object can be known only at run time, and the compiler doesn’t try to interfere. As a result, you can write less code. And I want to emphasize that this is no more dangerous than using the original object keyword. However, it is not less dangerous either, so all the type-checking techniques that you need to use when operating with objects (such as reflection) have to be used for dynamic objects as well. n The dynamic keyword is new to C# 4.0, and is used to tell the compiler that a variable's type can change or that it is not known until runtime. Think of it as being able to interact with an Object without having to cast it. dynamic cust = GetCustomer(); cust.FirstName = "foo"; // works as expected cust.Process(); // works as expected cust.MissingMethod(); // No method found!

82 82 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 n Notice we did not need to cast nor declare cust as type Customer. Because we declared it dynamic, the runtime takes over and then searches and sets the FirstName property for us. Now, of course, when you are using a dynamic variable, you are giving up compiler type checking. This means the call cust.MissingMethod() will compile and not fail until runtime. The result of this operation is a RuntimeBinderException because MissingMethod is not defined on the Customer class. n Example: decimal foo = GetDecimalValue(); foo = foo / 2.5; // Does not compile foo = Math.Sqrt(foo); // Does not compile string bar = foo.ToString("c");

83 83 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 4 n The second line does not compile because 2.5 is typed as a double and line 3 does not compile because Math.Sqrt expects a double. Obviously, all you have to do is cast and/or change your variable type, but there may be situations where dynamic makes sense to use. dynamic foo = GetDecimalValue(); // still returns a decimal foo = foo / 2.5; // The runtime takes care of this for us foo = Math.Sqrt(foo); // Again, the DLR works its magic string bar = foo.ToString("c");

84 84 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# The dynamic keyword n The dynamic keyword and the Dynamic Language Runtime (DLR) are major new features in C# 4 and the Microsoft.NET Framework 4. n What Is Dynamic? n Programming languages are sometimes divided into statically typed and dynamically typed languages. C# and Java are often considered examples of statically typed languages, while Python, Ruby and JavaScript are examples of dynamically typed languages. n Generally speaking, dynamic languages don’t perform compile-time type checks and identify the type of objects at run time only. This approach has its pros and cons: Often the code is much faster and easier to write, but at the same time you don’t get compiler errors and have to use unit testing and other techniques to ensure the correct behavior of your application.

85 85 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n Originally, C# was created as a purely static language, but with C# 4, dynamic elements have been added to improve interoperability with dynamic languages and frameworks. The C# team considered several design options, but finally settled on adding a new keyword to support these features: dynamic. n The dynamic keyword acts as a static type declaration in the C# type system. This way C# got the dynamic features and at the same time remained a statically typed language. n Examples: dynamic d = "test"; Console.WriteLine(d.GetType()); // Prints "System.String". d = 100; Console.WriteLine(d.GetType()); // Prints "System.Int32".

86 86 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n As you can see, it’s possible to assign objects of different types to a variable declared as dynamic. The code compiles and the type of object is identified at run time. However, this code compiles as well, but throws an exception at run time: dynamic d = "test"; // The following line throws an exception at run time. d++; n The reason is the same: The compiler doesn’t know the runtime type of the object and therefore can’t tell you that the increment operation is not supported in this case.

87 87 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Dynamic, Object or Var? n So what’s the real difference between dynamic, object and var, and when should you use them? Here are short definitions of each keyword and some examples. n The object –keyword represents the System.Object type, which is the root type in the C# class hierarchy. This keyword is often used when there’s no way to identify the object type at compile time, which often happens in various interoperability scenarios. n You need to use explicit casts to convert a variable declared as object to a specific type: object objExample = 10; Console.WriteLine(objExample.GetType()); n This obviously prints System.Int32. However, the static type is System.Object, so you need an explicit cast here: objExample = (int)objExample + 10;

88 88 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n You can assign values of different types because they all inherit from System.Object: objExample = "test"; n The var keyword, since C# 3.0, is used for implicitly typed local variables and for anonymous types. When a variable is declared by using the var keyword, the variable’s type is inferred from the initialization string at compile time. The type of the variable can’t be changed at run time. If the compiler can’t infer the type, it produces a compilation error: var varExample = 10; Console.WriteLine(varExample.GetType()); n This prints System.Int32, and it’s the same as the static type. In the following example, no cast is required because varExample’s static typed is System.Int32: varExample = varExample + 10;

89 89 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n This line doesn’t compile because you can only assign integers to varExample: varExample = "test"; n The dynamic keyword, introduced in C# 4, makes certain scenarios that traditionally relied on the object keyword easier to write and maintain. In fact, the dynamic type uses the System.Object type under the hood, but unlike object it doesn’t require explicit cast operations at compile time, because it identifies the type at run time only: dynamic dynamicExample = 10; Console.WriteLine(dynamicExample.GetType()); n This prints System.Int32. n In the following line, no cast is required, because the type is identified at run time only: dynamicExample = dynamicExample + 10;

90 90 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 n You can assign values of different types to DynamicExample: dynamicExample = "test"; n What sometimes causes confusion is that all of these keywords can be used together—they’re not mutually exclusive. For example, let’s take a look at this code: dynamic dynamicObject = new Object(); var anotherObject = dynamicObject; n What’s the type of anotherObject? The answer is: dynamic. Remember that dynamic is in fact a static type in the C# type system, so the compiler infers this type for the anotherObject. n It’s important to understand that the var keyword is just an instruction for the compiler to infer the type from the variable’s initialization expression; var is not a type.

91 91 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 4 n With the dynamic keyword, this code looks as simple as this one: dynamic calc = GetCalculator(); int sum = calc.Add(10, 20); n The assumptions are the same: There’s some object with an unknown type that we expect to have the Add method. And similar to the previous example, you don’t get IntelliSense for this method. But the syntax is much easier to read and use and looks similar to calling a typical.NET method.

92 92 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 5 n COM Interop is a technology included in the.NET Framework Common Language Runtime (CLR) that enables Component Object Model (COM) objects to interact with.NET objects, and vice versa. n COM Interop aims to provide access to the existing COM components without requiring that the original component be modified. It tries to make the.NET types equivalent to the COM types. In addition, COM Interop allows COM developers to access managed objects as easily as they access other COM objects.

93 93 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Easy Access to COM Objects n An object is said to be dynamic when its structure and behavior aren’t fully described by a statically defined type that the compiler knows thoroughly. Admittedly, the word dynamic sounds a bit generic in this context, so let’s look at a simple example. In a scripting language such as VBScript, the following code runs successfully: n Set word = CreateObject("Word.Application") n The CreateObject function assumes that the string it gets as an argument is the progID of a registered COM object. It creates an instance of the component and returns its IDispatch automation interface. The details of the IDispatch interface are never visible at the level of the scripting language. What matters is that you can write code such as:

94 94 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 Set word = CreateObject("Word.Application") word.Visible = True Set doc = word.Documents.Add() Set selection = word.Selection selection.TypeText "Hello, world" selection.TypeParagraph() doc.SaveAs(fileName) n In this code, you first create a reference to a component that automates the behavior of the underlying Microsoft Office Word application. Next, you make the Word main window visible, add a new document, write some text into it and then save the document somewhere. n The reason this works, however, is due to a particular capability offered by VBScript—late binding. Late binding means that the type of a given object isn’t known until the execution flow hits the object.

95 95 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n When this happens, the runtime environment first ensures that the member invoked on the object really exists and then invokes it. No preliminary check whatsoever is made before the code is actually executed.

96 96 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example (Word Automation using C# 4.0) n Word Automation through C# is all about programmatically generating the Word Document using C# code. Working on Word is considered to be straightforward, but doing the same programmatically gets a little intricate. Word automation almost completely involves working with objects and reference types. n Almost all of the tasks which we perform on word can be done programmatically using C# or VB. Tasks like Inserting Table of Contents, Linking documents, Mail Merge, Inserting Documents, Embedding documents, inserting pictures, watermark... etc can all be done programmatically. n In the next slide, we will demonstrate a simple example.

97 97 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n To add a reference: n In Solution Explorer, right-click your project's name and then click Add Reference. The Add Reference dialog box appears. n On the.NET page, select Microsoft.Office.Interop.Word in the Component Name list. n Click OK. n To add necessary using directives: n In Solution Explorer, right-click the Program.cs file and then click View Code. n Add the following using directives to the top of the code file. n using Word = Microsoft.Office.Interop.Word;

98 98 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2

99 99 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3

100 100 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 4

101 101 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 5

102 102 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 6

103 103 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Understanding static n There will be times when you will want to define a class member that will be used independently of any object of that class. Normally, a class member must be accessed through an object of its class, but it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is Main( ), which is declared static because it must be called by the operating system when your program begins. n Outside the class, to use a static member, you must specify the name of its class followed by the dot operator. No object needs to be created. In fact, a static member cannot be accessed through an object reference.

104 104 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Static Members n Static data members belong to the class rather than to each instance of the class. You use the static keyword to define them. For example, here the Contact class has a static member named count : public class Contact { public static int count; public int ID; public string FirstName; public string LastName; public string Email; } n The count static member can be used to keep track of the total number of Contact instances, and thus it should not belong to any instances of the Contact class but to the class itself.

105 105 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n To use the count static variable, access it through the Contact class: Contact.count = 4; Console.WriteLine(Contact.count); n Constants defined within a class are implicitly static, as the following example shows: public class Contact { public const ushort MAX_EMAIL = 5; public static int count; public int ID; public string FirstName; public string LastName; public string Email; }

106 106 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Method overloading n Method overloading allows the creation of several methods with the same name which differ from each other in the type of the input. n The key is, while two methods can have the same name, they can't have the same "signature". A method's signature is defined as the combination of the method name and the types and order of the parameters that get passed in. Note that this does not include the parameters' names, just their types. (This is because when you call a method, the C# compiler can figure out which of the different "overloads" is supposed to be used based on the method name and the kinds of data that are being passed in, though the actual names of the variables don't matter when you're calling a method, so they are ignored.)

107 107 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n As an example, to help illustrate what a method signature is, take the following example: static int Multiply(int a, int b){ return a * b; } n This has a signature that looks like this: static int Multiply(int, int). You can only overload a method if you use a different signature. So for instance, the following code snippet works: static int Multiply(int a, int b){ return a * b; } static int Multiply(int a, int b, int c){ return a * b * c; n }

108 108 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n This works, because the two multiply methods have a different number of parameters, and so as a result, a different signature. We could also define a Multiply method that has no parameters (just int Multiply()) or one parameter (int Multiply(int)) though, admittedly, in this particular case, I can't imagine how either of those two methods would do multiplication with zero or one things. (Hey, it's just an example!). n Also, you can have the same number of parameters, if their types are different: static int Multiply(int a, int b){ return a * b; } static double Multiply(double a, double b){ return a * b; }

109 109 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 using System; public class Sum{ public int GetSum(){ return 0; } public int GetSum(int x){ return x; } public int GetSum(int x, int y) { return x + y; } } public class Overloading{ static void Main(){ Sum s = new Sum(); Console.WriteLine(s.GetSum()); Console.WriteLine(s.GetSum(20)); Console.WriteLine(s.GetSum(20, 30)); } }

110 110 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 n The magic of method overloading is that you can have many methods that do very similar work on different types of data (like the int multiplication and the double multiplication above) without having to have a completely different method name. It makes things easier on the people calling the method (yourself, for starters, but the other people on your team as well). With different signatures, the C# compiler can determine which of the overloaded methods to use.

111 111 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Recursion n Recursion, in mathematics and computer science, is a way of defining methods in which the method being defined is applied within its own definition. In other words, a recursive method calls itself to do its job. n The recursion, it is where you call a method from inside itself. Here's a trivial example (which happens to break on you when you run it): static void MethodThatUsesRecursion() { MethodThatUsesRecursion(); } n Like I said (repeatedly), this example is going to break on you, because it just keeps going into deeper and deeper methods.

112 112 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n The problem with this first example, is that there is no "base case". It will never get to a point where it is done, and can start returning from the method calls, back up to the starting point. n A base case is a situation where there is no need to keep going further, and the method can simply return without "recursing" further. n Perhaps you remember from math classes that the factorial, written as an exclamation mark by a number (like "7!") means 7 * 6 * 5 * 4 * 3 * 2 * 1. 72! Would be 72 * 71 * 70 * 69 * … * 3 * 2 * 1. n In this case, we know that 1! is 1. This can function as a base case. Every other number, say 7!, can be thought of as the number multiplied by the factorial of the number one less than it (7 * 6!).

113 113 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example using System; public class Recursion{ static void Main(){ Console.WriteLine(Factorial(6)); Console.WriteLine(Factorial(10)); } static int Factorial(int n){ if (n == 0){ return 1; } else{ return n * Factorial(n-1); }

114 114 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example-The Fibonacci Numbers n The Fibonacci numbers are the numbers in the following sequence: 0,1,1,2,3,5,8,13,21,34,55,… If F0 = 0 and F1= 1 then: Fn = Fn-1 + Fn-2 n The following code is a method to compute Fn (no recursive and high performance): public long Fib(int n){ if (n < 2) return n; long[] f = new long[n+1]; f[0] = 0; f[1] = 1; for (int i = 2; i <= n; i++) f[i] = f[i - 1] + f[i - 2]; return f[n]; }

115 115 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n If we use recursive method, our code will be more simple, but a very poor performance: public long Fib(int n) { if (n == 0 || n == 1) return n; return Fib(n- 2) + Fib(n - 1); }

116 116 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Method scope n A variable declared inside a method has a method scope. The scope of a name is the region of program text within which it is possible to refer to the entity declared by the name without the qualification of the name. A variable which is declared inside a method has a method scope. It is also called a local scope. The variable is valid only in this particular method. n The Main() method is an entry point to the C# console and GUI application. In C#, the Main() method is required to be static. Before the application starts, no object is created yet. To invoke non-static methods, we need to have an object instance. Static methods exist before a class is instantiated so static is applied to the main entry point.

117 117 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 using System; public class Basic{ static int Id = 2321; public static void ShowInfo() { Console.WriteLine("This is Basic class"); Console.WriteLine("The Id is: {0}", Id); }} public class StaticMethod{ static void Main(){ Basic.ShowInfo(); } n In our code example, we define a static ShowInfo() method. A static method can only work with static variables. To invoke a static method, we do not need an object instance. We call the method by using the name of the class and the dot operator.

118 118 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# The constructor n A constructor is a special kind of a method. It is automatically called when the object is created. Constructors do not return values. The purpose of the constructor is to initiate the state of an object. Constructors have the same name as the class. The constructors are methods, so they can be overloaded too. n Also, usually, access is public because constructors are normally called from outside their class. n Constructors cannot be inherited. They are called in the order of inheritance. If we do not write any constructor for a class, C# provides an implicit default constructor. If we provide any kind of a constructor, then a default is not supplied.

119 119 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 using System; public class Being{ public Being(){ Console.WriteLine("Being is created");} public Being(string being){ Console.WriteLine("Being {0} is created", being);} } public class Constructor{ static void Main() { new Being(); new Being("Tom"); } n We have a Being class. This class has two constructors. The first one does not take parameters; the second one takes one parameter.

120 120 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 public Being(string being){ Console.WriteLine("Being {0} is created", being);} n This constructor takes one string parameter. n new Being(); n An instance of the Being class is created. This time the constructor without a parameter is called upon object creation. n Output: n Being is created n Being Tom is created n In the next example, we initiate data members of the class. Initiation of variables is a typical job for constructors.

121 121 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 using System; public class MyFriend{ private DateTime born; private string name; public MyFriend(string name, DateTime born){ this.name = name; this.born = born; } public void Info() { Console.WriteLine("{0} was born on {1}", this.name, this.born.ToShortDateString()); }

122 122 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 4 public class Constructor2{ static void Main() { string name = "Lenka"; DateTime born = new DateTime(1990, 3, 5); MyFriend fr = new MyFriend(name, born); fr.Info(); } n In the constructor, we initiate the two data members. The this variable is a handler used to reference the object variables. n

123 123 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Constructor chaining n Constructor chaining is the ability of a class to call another constructor from a constructor. To call another constructor from the same class, we use the this keyword. using System; public class Circle { public Circle(int radius){ Console.WriteLine("Circle, r={0} is created", radius); } public Circle() : this(1) { }

124 124 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 public class ConstructorChaining{ static void Main(){ new Circle(5); new Circle(); } n We have a Circle class. The class has two constructors. One that takes one parameter and one that does not take any parameters. public Circle(int radius){ Console.WriteLine("Circle, r={0} is created", radius);} n This constructor takes one parameter — the radius. public Circle() : this(1) {} n This is the constructor without a parameter. It simply calls the other constructor and gives it a default radius of 1.

125 125 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Class constants n C# enables to create class constants. These constants do not belong to a concrete object. They belong to the class. By convention, constants are written in uppercase letters. using System; public class Math{ public const double PI = 3.14159265359; } public class ClassConstants{ static void Main(){ Console.WriteLine(Math.PI); } } n The const keyword is used to define a constant. The public keyword makes it accessible outside the body of the class.

126 126 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# The ToString() method The default implementation returns the fully qualified name of the type of the Object. n Each object has a ToString() method. It returns a human- readable representation of an object. The default implementation returns the fully qualified name of the type of the Object. Note that when we call the Console.WriteLine() method with an object as a parameter, the ToString() is being called. using System; public class Being { public override string ToString() { return "This is Being class“; }} public class ToStringMethod{ static void Main() { Being b = new Being(); object o = new Object(); Console.WriteLine(o.ToString()); Console.WriteLine(b.ToString()); Console.WriteLine(b); } }

127 127 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n Each class created inherits from the base object. The ToString() method belongs to this object class. So, We have a Being class in which we override the default implementation of the ToString() method. We use the override keyword to inform that we are overriding a method. n Output: System.Object This is Being Class

128 128 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Properties n A field is a variable that is declared directly in a class or struct. A class or struct may have instance fields or static fields or both. Generally, you should use fields only for variables that have private or protected accessibility. Data that your class exposes to client code should be provided through methods, properties and indexers. By using these constructs for indirect access to internal fields, you can guard against invalid input values. n A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

129 129 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set accessor is used to assign a new value. n Property reads and writes are translated to get and set method calls. Accessing variables with a field notation (e.g. object.Name) is easier than with custom method calls (e.g. object.GetName()). However with properties, we still have the advantage of encapsulation and information hiding. In other words, properties shield the data from the outside world while having a convenient field access. n A property is much like a combination of a variable and a method - it can't take any parameters, but you are able to process the value before it's assigned to our returned.

130 130 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 n A property consists of 2 parts, a get and a set method, wrapped inside the property: private string color; public string Color { get { return color; } set { color = value; } } n The get method should return the variable, while the set method should assign a value to it. Our example is as simple as it gets, but it can be extended. Another thing you should know about properties is the fact that only one method is required - either get or set, the other is optional. This allows you to define read-only and write-only properties.

131 131 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example using System; public class Person { private string _name; public string Name{ get { return _name; } set { _name = value;} } public class CSharpApp{ static void Main() { Person p = new Person(); p.Name = "Jane"; Console.WriteLine(p.Name); }

132 132 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n We have a simple Person class with one property. We have a property that is called Name. It looks like a regular method declaration. The difference is that it has specific accessors called get and set. n A get property accessor is used to return the property value, and a set accessor is used to assign a new value. The value keyword is used to define the value being assigned by the set indexer.

133 133 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Read-only properties n It is possible to create read-only properties. To create a read-only property, we omit the set accessor and provide only the get accessor in the implementation. using System; public class Person { private string _name = "Jane"; public string Name{ get { return _name; } } public class ReadonlyProperties{ static void Main() { Person p = new Person(); // p.Name = "Beky"; Eroor Console.WriteLine(p.Name); }

134 134 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Creating a Write-Only Property n You can assign values to, but not read from, a write-only property. A write-only property only has a set accessor. using System; public class Customer{ private int m_id = -1; public int ID{ set { m_id = value; } private string m_name = string.Empty; public string Name{ set { m_name = value; }

135 135 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 public void DisplayCustomerData() { Console.WriteLine("ID: {0}, Name: {1}", m_id, m_name); } public class WriteOnlyCustomerManager{ public static void Main() { Customer cust = new Customer(); cust.ID = 1; cust.Name = "Amelio Rosales"; cust.DisplayCustomerData(); Console.ReadKey(); }} n This time, the get accessor is removed from the ID and Name properties of the Customer class. The set accessors have been added, assigning value to the backing store fields, m_id and m_name.

136 136 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Automatic properties n The patterns you see here, where a property encapsulates a property with get and set accessors, without any other logic is common. It is more code than we should have to write for such a common scenario. That's why C# 3.0 introduced a new syntax for a property, called an auto-implemented property, which allows you to create properties without get and set accessor implementations. n We can mark properties with access modifiers like public, private or protected. Properties can be also static, abstract, virtual and sealed. Their usage is identical to regular methods.

137 137 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 using System; public class Customer{ public int ID { get; set; } public string Name { get; set; } } public class AutoImplementedCustomerManager{ static void Main(){ Customer cust = new Customer(); cust.ID = 1; cust.Name = “Asd Asd"; Console.WriteLine( "ID: {0}, Name: {1}“,cust.ID,cust.Name); Console.ReadKey(); }

138 138 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Object Initializers n With C# 3.0, initializing both objects and collections have become much easier. Consider this simple Car class, where we use the automatic properties described before: class Car{ public string Name { get; set; } publi c Color Color { get; set; } } n Now, in C# 2.0, we would have to write a piece of code like this to create a Car instance and set its properties: Car car = new Car(); car.Name = "Chevrolet Corvette"; car.Color = Color.Yellow; n It's just fine really, but with C# 3.0, it can be done a bit more cleanly, thanks to the new object initializer syntax:

139 139 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n Car car = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow }; n As you can see, we use a set of curly brackets after instantiating a new Car object, and within them, we have access to all the public properties of the Car class. This saves a bit of typing, and a bit of space as well. The cool part is that it can be nested too. Consider the following example, where we add a new complex property to the Car class, like this: class Car{ public string Name { get; set; } public Color Color { get; set; } public CarManufacturer Manufacturer { get; set; } }

140 140 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 2 class CarManufacturer{ public string Name { get; set; } public string Country { get; set; } } n To initialize a new car with C# 2.0, we would have to do something like this: Car car = new Car(); car.Name = "Corvette"; car.Color = Color.Yellow; car.Manufacturer = new CarManufacturer(); car.Manufacturer.Name = "Chevrolet"; car.Manufacturer.Country = "USA";

141 141 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 3 n With C# 3.0, we can do it like this instead: Car car = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow, Manufacturer = new CarManufacturer { Name = "Chevrolet", Country = "USA" } };

142 142 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Extension Methods n Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type. n An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended. n Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

143 143 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Benefits of extension methods n Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. n If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced, in other words extension methods. n This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design. n An extension method is a special kind of static method that allows you to add new methods to existing types without creating derived types. n The extension methods are called as if they were instance methods from the extended type, For example: x is an object from int class and we called it as an instance method in int class.

144 144 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# 1 n Suppose that you want to extend int class in.NET by adding a factorial method to it using recursion technique. n One way of thinking is to inherit int class and add your new method to it and use your new methods in your code. This is a valid solution but let us see what extension methods can provide us. n Using extension methods, you can use your new methods as a part of int class in.NET. n How to Create my Extension Method? n Simply, you create your own static method in your class and put this keyword in front of the first parameter in this method (the type that will be extended).

145 145 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example namespace ConsoleApplication1 { class Program { static void Main(string[] args){ int x = 3; Console.WriteLine(x.factorial()); Console.ReadLine(); } public static class MyMathExtension { public static int factorial(this int x) { if (x <= 1) return 1; if (x == 2) return 2; else return x * factorial(x - 1); } }

146 146 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# tips n This keyword has to be the first parameter in the extension method parameter list. n It is important to note that extension methods can't access the private methods in the extended type. n If you want to add new methods to a type, you don't have the source code for it, the ideal solution is to use and implement extension methods of that type. n If you create extension methods that have the same signature methods inside the type you are extending, then the extension methods will never be called.

147 147 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C# Example public static class Extensions{ public static string GetFirstThreeCharacters(this String str) { if(str.Length < 3){ return str; } else { return str.Substring(0,3); } String str = "my new String"; str = str.GetFirstThreeCharacters();

148 148 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C#

149 149 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C#

150 150 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C#

151 151 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C#

152 152 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C#

153 153 - Prof Yousef B. Mahdy- 10/25/2015 Visual programming- C#


Download ppt "Prof. Yousef B. Mahdy -2014-2015, Assuit University, Egypt Visual programming Using C# Prof. Yousef B. Mahdy Chapter four Classes and Objects."

Similar presentations


Ads by Google