Industrial Informatics Course 3 Encapsulation Methods Classes Windows

  • Slides: 62
Download presentation
Industrial Informatics Course 3 Encapsulation, Methods, Classes. Windows Forms Applications in C#

Industrial Informatics Course 3 Encapsulation, Methods, Classes. Windows Forms Applications in C#

q Topics • • Encapsulation in C# Methods in C# Classes in C# Windows

q Topics • • Encapsulation in C# Methods in C# Classes in C# Windows Forms Applications in C#

Encapsulation in C# Ø Encapsulation “the process of enclosing one or more items within

Encapsulation in C# Ø Encapsulation “the process of enclosing one or more items within a physical and logical package” § prevents access to implementation details § abstraction and encapsulation - related features in object oriented (OO) programming - abstraction allows making relevant information visible - encapsulation enables a programmer to implement the desired level of abstraction § Encapsulation – implemented using access specifiers => define the scope of visibility of a class member

ØAccess specifiers in C# § Public § Private § Protected § Internal § Protected

ØAccess specifiers in C# § Public § Private § Protected § Internal § Protected internal § Public access specifier • allows a class to expose its member variables and member functions to other functions and objects • any public member can be accessed from outside the class

 • Example: using System; namespace Rectangle. Application { class Rectangle { //member variables

• Example: using System; namespace Rectangle. Application { class Rectangle { //member variables public double length; public double width; public double Get. Area() { return length * width; } public void Display() { Console. Write. Line("Length: {0}", length); Console. Write. Line("Width: {0}", width); Console. Write. Line("Area: {0}", Get. Area()); } }//end class Rectangle class Execute. Rectangle { static void Main(string[]args) { Rectangle r = new Rectangle(); r. length = 4. 5; r. width = 3. 5; r. Display(); Console. Read. Line(); } }//end class Rectangle }//end namespace

- the member variables length and width are declared public => they can be

- the member variables length and width are declared public => they can be accessed from the function Main(), using an instance of the Rectangle class, named r. - the member function Display() and Get. Area() can also access these variables directly without using any instance of the class. - the member functions Display() is also declared public, so it can also be accessed from Main() using an instance of the Rectangle class, named r. § Private access specifier • allows a class to hide its member variables and member functions from other classes • only functions of the same class can access its private members • even an instance of a class cannot access its private members

 • Example: using System; namespace Rectangle. Application { class Rectangle { //member variables

• Example: using System; namespace Rectangle. Application { class Rectangle { //member variables private double length; private double width; public void Acceptdetails() { Console. Write. Line("Enter Length: "); length = Convert. To. Double(Console. Read. Line()); Console. Write. Line("Enter Width: "); width = Convert. To. Double(Console. Read. Line()); } public double Get. Area() { return length * width; } public void Display() { Console. Write. Line("Length: {0}", length); Console. Write. Line("Width: {0}", width); Console. Write. Line("Area: {0}", Get. Area()); } }//end class Rectangle class Execute. Rectangle { static void Main(string[]args) { Rectangle r = new Rectangle(); r. Acceptdetails(); r. Display(); Console. Read. Line(); } }//end class Rectangle }//end namespace

In the preceding example - the member variables length and width are declared private,

In the preceding example - the member variables length and width are declared private, so they cannot be accessed from the function Main() the member functions Accept. Details()and Display() can access these variables - since the member functions Accept. Details() and Display() are declared public, they can be accessed from Main() using an instance of the Rectangle class, named r § Protected access specifier - allows a child class to access the member variables and member functions of its base class - this way it helps in implementing inheritance (to be discussed later) § Internal access specifier • allows a class to expose its member variables and member functions to other functions and objects in the current assembly • any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined

 • Example: using System; namespace Rectangle. Application { class Rectangle { //member variables

• Example: using System; namespace Rectangle. Application { class Rectangle { //member variables internal double length; internal double width; double Get. Area() { return length * width; } public void Display() { Console. Write. Line("Length: {0}", length); Console. Write. Line("Width: {0}", width); Console. Write. Line("Area: {0}", Get. Area()); } }//end class Rectangle class Execute. Rectangle { static void Main(string[]args) { Rectangle r = new Rectangle(); r. length = 4. 5; r. width = 3. 5; r. Display(); Console. Read. Line(); } }//end class Rectangle }//end namespace

§ In the preceding example - the member function Get. Area() - not declared

§ In the preceding example - the member function Get. Area() - not declared with any access specifier • What would be the default access specifier of a class member if we don't mention any? => It is private. § Protected internal access specifier • allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application • also used while implementing inheritance

Methods in C# Ø A method - a group of statements that together perform

Methods in C# Ø A method - a group of statements that together perform a task. § Every C# program has at least one class with a method named Main. § To use a method, you need to: • Define the method • Call the method Ø Defining methods in C# <Access Specifier><Return Type><Method Name>(Parameter List) { Method Body }

Ø Elements of a method § Access Specifier - determines the visibility of a

Ø Elements of a method § Access Specifier - determines the visibility of a variable or a method from another class. § Return type – a method may return a value • The return type - the data type of the value the method returns • If the method is not returning any values=> the return type is void § Method name - is a unique identifier and it is case sensitive; cannot be same as any other identifier declared in the class. § Parameter list - enclosed between parentheses, the parameters are used to pass and receive data from a method; refers to the type, order, and number of the parameters of a method • Parameters – optional => a method may contain no parameters. § Method body - contains the set of instructions needed to complete the required activity

 • Example class Number. Manipulator { public int Find. Max(int num 1, int

• Example class Number. Manipulator { public int Find. Max(int num 1, int num 2) { /* local variable declaration */ int result; if (num 1 > num 2) result = num 1; else result = num 2; return result; }. . . }

 • Calling methods in C# using System; namespace Calculator. Application { class Number.

• Calling methods in C# using System; namespace Calculator. Application { class Number. Manipulator { public int Find. Max(int num 1, int num 2) { /* local variable declaration */ int result; if (num 1 > num 2) result = num 1; else result = num 2; return result; } => static void Main(string[] args) { /* local variable definition */ int a = 100; int b = 200; int ret; Number. Manipulator n = new Number. Manipulator(); //calling the Find. Max method ret = n. Find. Max(a, b); Console. Write. Line("Max value is : {0}", ret ); Console. Read. Line(); } } Max value is : 200

§ You can also call public method from other classes by using the instance

§ You can also call public method from other classes by using the instance of the class § Ex - the method Find. Max belongs to the Number. Manipulator class, you can call it from another class Test § Recursive Method Call • A method can call itself => recursion • Ex. : - function that calculates factorial for a given number using a recursive function using System; namespace Calculator. Application { class Number. Manipulator { public int factorial(int num) { /* local variable declaration */ int result; if (num == 1) { return 1; } else { result = factorial(num - 1) * num; return result; } }

static void Main(string[] args) { Number. Manipulator n = new Number. Manipulator(); //calling the

static void Main(string[] args) { Number. Manipulator n = new Number. Manipulator(); //calling the factorial method Console. Write. Line("Factorial of 6 is : {0}", n. factorial(6)); Console. Write. Line("Factorial of 7 is : {0}", n. factorial(7)); Console. Write. Line("Factorial of 8 is : {0}", n. factorial(8)); Console. Read. Line(); } } } Factorial of 6 is: 720 => Factorial of 7 is: 5040 Factorial of 8 is: 40320

Ø Passing Parameters to a Method • There are three ways in which parameters

Ø Passing Parameters to a Method • There are three ways in which parameters can be passed to a method in C#:

q Passing parameters by values • the default mechanism • when a method is

q Passing parameters by values • the default mechanism • when a method is called, a new storage location is created for each value parameter - the values of the actual parameters are copied into them => the changes made to the parameter inside the method have no effect on the argument • Example: using System; namespace Calculator. Application { class Number. Manipulator { public void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put temp into y */ }

static void Main(string[] args) { Number. Manipulator n = new Number. Manipulator(); /* local

static void Main(string[] args) { Number. Manipulator n = new Number. Manipulator(); /* local variable definition */ int a = 100; int b = 200; Console. Write. Line("Before swap, value of a : {0}", a); Console. Write. Line("Before swap, value of b : {0}", b); /* calling a function to swap the values */ n. swap(a, b); Console. Write. Line("After swap, value of a : {0}", a); Console. Write. Line("After swap, value of b : {0}", b); Console. Read. Line(); } } }

Before swap, value of a : 100 => Before swap, value of b :

Before swap, value of a : 100 => Before swap, value of b : 200 After swap, value of a : 100 After swap, value of b : 200 q Passing parameters by reference • A reference parameter - a reference to a memory location of a variable • When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. • The reference parameters represent the same memory location as the actual parameters that are supplied to the method. • Declare the reference parameters using the ref keyword

 • Example: using System; namespace Calculator. Application { class Number. Manipulator { public

• Example: using System; namespace Calculator. Application { class Number. Manipulator { public void swap(ref int x, ref int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put temp into y */ } static void Main(string[] args) { Number. Manipulator n = new Number. Manipulator(); /* local variable definition */ int a = 100; int b = 200; Console. Write. Line("Before swap, value of a : {0}", a); Console. Write. Line("Before swap, value of b : {0}", b);

/* calling a function to swap the values */ n. swap(ref a, ref b);

/* calling a function to swap the values */ n. swap(ref a, ref b); Console. Write. Line("After swap, value of a : {0}", a); Console. Write. Line("After swap, value of b : {0}", b); Console. Read. Line(); } } } Before swap, value of a : 100 => Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100

q Passing parameters by outputs § A return statement - can be used for

q Passing parameters by outputs § A return statement - can be used for returning only one value from a function § However, using output parameters => you can return two or more values from a function • Example: using System; namespace Calculator. Application { class Number. Manipulator { public void get. Values(out int x, out int y ) { Console. Write. Line("Enter the first value: "); x = Convert. To. Int 32(Console. Read. Line()); Console. Write. Line("Enter the second value: "); y = Convert. To. Int 32(Console. Read. Line()); }

static void Main(string[] args) { Number. Manipulator n = new Number. Manipulator(); /* local

static void Main(string[] args) { Number. Manipulator n = new Number. Manipulator(); /* local variable definition */ int a , b; /* calling a function to get the values */ n. get. Values(out a, out b); Console. Write. Line("After method call, value of a : {0}", a); Console. Write. Line("After method call, value of b : {0}", b); Console. Read. Line(); } } } Enter the first value: 7 => Enter the second value: 8 After method call, value of a : 7 After method call, value of b : 8

v Discussions: §Output parameters - similar to reference parameters, except that they transfer data

v Discussions: §Output parameters - similar to reference parameters, except that they transfer data out of the method rather than into it § The variable supplied for the output parameter - need not be assigned a value § Output parameters - particularly useful when you need to return values from a method through the parameters without assigning an initial value to the parameter

Classes in C# § Defining a class defining a blueprint for a data type

Classes in C# § Defining a class defining a blueprint for a data type § This does not actually define any data, but it does define what the class name means § Objects - instances of a class § Methods and variables that constitute a class - members of the class Ø Defining a class § A class definition - starts with the keyword class followed by the class name § The class body - enclosed by a pair of curly braces

§ The general form of a class definition: <access specifier> class_name { // member

§ The general form of a class definition: <access specifier> class_name { // member variables <access specifier> <data type> variable 1; . . . <access specifier> <data type> variable. N; // member methods <access specifier> <return type> method 1(parameter_list) { // method body }. . . <access specifier> <return type> method. N(parameter_list) { // method body } }

Ø Discussions: § Access specifiers - specify the access rules for the members as

Ø Discussions: § 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. § Data type specifies the type of variable, and return type specifies the data type of the data the method returns, if any. § To access the class members, you use the dot (. ) operator. § The dot operator links the name of an object with the name of a member.

Ø Member functions and encapsulation • A member function of a class - a

Ø Member functions and encapsulation • A member function of a class - a function that has its definition or its prototype within the class definition similar to any other variable • It operates on any object of the class of which it is a member, and has access to all the members of a class for that object methods • Member variables are the attributes of an object (from design perspective) and they are kept private to implement encapsulation => they can only be accessed using the public member functions • Example – set and get the values of different class members: using System; namespace Box. Application { class Box { private double length; // Length of a box private double breadth; // Breadth of a box private double height; // Height of a box public void set. Length( double len ) { length = len; }

 • Other member functions: public void set. Breadth(double bre) { breadth = bre;

• Other member functions: public void set. Breadth(double bre) { breadth = bre; } public void set. Height(double hei) { height = hei; } public double get. Volume() { return length * breadth * height; } }

class Boxtester { static void Main(string[] args) { Box 1 = new Box(); //

class Boxtester { static void Main(string[] args) { Box 1 = new Box(); // Declare Box 1 of type Box Box 2 = new Box(); double volume; // Declare Box 2 of type Box // box 1 specification Box 1. set. Length(6. 0); Box 1. set. Breadth(7. 0); Box 1. set. Height(5. 0); // box 2 specification Box 2. set. Length(12. 0); Box 2. set. Breadth(13. 0); Box 2. set. Height(10. 0); // volume of box 1 volume = Box 1. get. Volume(); Console. Write. Line("Volume of Box 1 : {0}" , volume); // volume of box 2 volume = Box 2. get. Volume(); Console. Write. Line("Volume of Box 2 : {0}", volume); Console. Read. Key(); }}}

Ø C# constructors • A class constructor - a special member function of a

Ø C# constructors • A class constructor - a special member function of a class that is executed whenever we create new objects of that class • A constructor - has exactly the same name as that of the class and it does not have any return type • Example: Using System; namespace Line. Application { class Line { private double length; // Length of a line public Line() { Console. Write. Line("Object is being created"); } public void set. Length(double len) { length = len; }

public double get. Length() { return length; } static void Main(string[] args) { Line

public double get. Length() { return length; } static void Main(string[] args) { Line line = new Line(); // set line length line. set. Length(6. 0); Console. Write. Line("Length of line : {0}", line. get. Length()); Console. Read. Key(); } } } => Oject is being created Length of line : 6

 • A default constructor does not have any parameter (it can even not

• A default constructor does not have any parameter (it can even not being declared within the class definition) but if you need, a constructor can have parameters • Such constructors are called parameterized constructors => this technique helps you to assign initial value to an object at the time of its creation as shown in the following example: using System; namespace Line. Application { class Line { private double length; // Length of a line public Line(double len) //Parameterized constructor { Console. Write. Line("Object is being created, length = {0}", len); length = len; }

public void set. Length(double len) { static void Main(string[] args) { Line line =

public void set. Length(double len) { static void Main(string[] args) { Line line = new Line(10. 0); length = len; Console. Write. Line("Length of line: {0}", line. get. Length()); } public double get. Length() // set line length { line. set. Length(6. 0); return length; } Console. Write. Line("Length of line: {0}", line. get. Length()); Console. Read. Key(); } } } => Object is being created, length = 10 Length of line : 6

Ø C# destructors • A destructor - a special member function of a class

Ø C# destructors • A destructor - a special member function of a class that is executed whenever an object of its class goes out of scope • A destructor - has exactly the same name as that of the class with a prefixed tilde (~) and it can neither return a value nor can it take any parameters • Destructor can be very useful for releasing memory resources before exiting the program=> they don’t require an explicit call in the Main function • Destructors cannot be inherited or overloaded.

 • Example using System; namespace Line. Application { class Line { private double

• Example using System; namespace Line. Application { class Line { private double length; // Length of a line public Line() // constructor { Console. Write. Line("Object is being created"); } ~Line() //destructor { Console. Write. Line("Object is being deleted"); }

public void set. Length(double len) { length = len; } public double get. Length()

public void set. Length(double len) { length = len; } public double get. Length() { return length; } static void Main(string[] args) { Line line = new Line(); // set line length line. set. Length(6. 0); Console. Write. Line("Length of line : {0}", line. get. Length()); } } } => Object is being created Length of line : 6 Object is being deleted

Ø Static members of a C# class • Define class members as static using

Ø Static members of a C# class • Define class members as static using the static keyword • We declare a member of a class as static => no matter how many objects of the class are created, there is only one copy of the static member • The keyword static => only one instance of the member exists for a class • Static variables § used for defining constants because their values can be retrieved by invoking the class § can be initialised outside the member function or class definition § can be initialised inside the class definition, as well • Example: using System; namespace Static. Var. Application { class Static. Var { public static int num=0;

public void count() { num++; } public int get. Num() { return num; }

public void count() { num++; } public int get. Num() { return num; } } class Static. Tester { static void Main(string[] args) { Static. Var s 1 = new Static. Var(); Static. Var s 2 = new Static. Var(); s 1. count(); => s 2. count(); Console. Write. Line("Variable num for s 1: {0}", s 1. get. Num()); Console. Write. Line("Variable num for s 2: {0}", s 2. get. Num()); Console. Read. Key(); } }//class Static. Tester }//namespace 1111 Variable num for s 1: 6 Variable num for s 2: 6

 • Static member functions - can access only static variables • The static

• Static member functions - can access only static variables • The static functions - exist even before the object is created • Call them using the class name, not the object name Example: using System; namespace Static. Var. Application { class Static. Var { public static int num; public void count() { num++; } public static int get. Num() { return num; } } class Static. Tester { static void Main(string[] args) { Static. Var s = new Static. Var(); s. count(); Console. Write. Line("Variable num: {0}", Static. Var. get. Num()); Console. Read. Key(); }}} => Variable num: 3

Windows Forms Applications in C#

Windows Forms Applications in C#

1. What is a Windows Forms based Application?

1. What is a Windows Forms based Application?

Creation of the Windows Forms Applications in C# • The template Windows Forms Application

Creation of the Windows Forms Applications in C# • The template Windows Forms Application represents a strong modality for creating Window – based applications (of type Window). • This template § offers the tools, the structure and the starting code for designing desktop applications § has a friendly graphical interface which allows a complex interaction with the user

The Specific Features of the Windows Forms Application template This template contains the following

The Specific Features of the Windows Forms Application template This template contains the following defining elements: • Forms. Visual surfaces acting as containers for different controls that offer information to the user and accepts information from him. • Events. Actions that could be generated in various ways, such as a mouse click or a key press, or when the program code responds to a certain input information • Controls. Predefined controls offered by IDE (Integrated Development Environment), which can be used in order to build the user interface with the application – e. g. text boxes, buttons, labels, drop-down lists (comboboxes). • Custom Controls that can be built in IDE when the predefined controls don’t satisfy our requirements • Designer Tools that permit the rapid development of the Windows Forms applications by using an IDE with graphic facilities.

2. How can we create a Windows Forms Application project ØProject creation • Open

2. How can we create a Windows Forms Application project ØProject creation • Open Visual Studio • From the menu File, choose New, then Project • Define a new project: • We select the project type, for example Microsoft Visual C# or Visual Basic • We select the corresponding application template (Windows Desktop –> Windows Forms Application) • We insert the application name • We establish the location for the project files • Click on OK => the project will be created

Saving the Project • Open the File menu => two options: • Choose Save

Saving the Project • Open the File menu => two options: • Choose Save All in order to save the entire project • Choose Save <object name> in order to save only the current item

3. Adding elements to a Windows Forms project We can add to the project

3. Adding elements to a Windows Forms project We can add to the project new or already existing components, such as forms belonging to other projects, that can be reused. Adding a new component in a Windows Forms Application Project • In Solution Explorer - right click on the project, select Add from the menu and then New Item • In the Add New Item dialog box, select the component which we want to add, for example a new Windows Form • Click on the Add button, in order to effectively add the component in the project

Adding components Add an already existing component • In Solution Explorer, right click on

Adding components Add an already existing component • In Solution Explorer, right click on the project, choose Add, then Existing Item • In the dialog window Add Existing Item, we use browse in order to localize the item we want to add • When we have localized this item, we press the Add button

4. The properties of a Windows Form object

4. The properties of a Windows Form object

Properties • A Windows Form object - has many properties that establish its aspect

Properties • A Windows Form object - has many properties that establish its aspect and behavior • We could personalize each form independently, according to the application requirements § use the Properties window which displays all the properties associated to the object

q The properties associated to a Windows form

q The properties associated to a Windows form

q The properties associated to a Windows form

q The properties associated to a Windows form

q The Structure of a Windows Forms Applications Project Ø Main files: § Form

q The Structure of a Windows Forms Applications Project Ø Main files: § Form 1. cs • Form 1. Designer. cs ……… § Form_n. cs § Program. cs § Form 1. cs • We can view both the design of the form and the corresponding code: Ø The design: Drag&drop

Ø The Code: using System; using System. Collections. Generic; using System. Component. Model; using

Ø The Code: using System; using System. Collections. Generic; using System. Component. Model; using System. Data; using System. Drawing; using System. Windows. Forms; namespace Windows. Forms. Application 1 { public partial class Form 1 : Form //form class definition { public Form 1() { Initialize. Component(); }

private void button 1_Click(object sender, Event. Args e) { int l, h, b, volume;

private void button 1_Click(object sender, Event. Args e) { int l, h, b, volume; Box box = new Box(); l = Convert. To. Int 32(text. Box 1. Text); h = Convert. To. Int 32(text. Box 2. Text); b = Convert. To. Int 32(text. Box 3. Text); box. set. Breadth(b); box. set. Height(h); box. set. Lenght(l); volume=box. compute. Box. Volume(); text. Box 4. Text = volume. To. String(); } }//end class Form 1 class Box //other class definition {…. } }// end namespace

Ø Remarks: • • The Form class - must be defined first, before any

Ø Remarks: • • The Form class - must be defined first, before any additional classes The other classes – can be defined in the same file, or in separate files, in the same namespace Ø Form 1. Designer. cs § The primary class definition – Form 1 § A Dispose function => free the memory § The attributes (member variables): private System. Windows. Forms. Label label 1; private System. Windows. Forms. Text. Box text. Box 2; private System. Windows. Forms. Label label 2; private System. Windows. Forms. Text. Box text. Box 3; private System. Windows. Forms. Label label 3; private System. Windows. Forms. Text. Box text. Box 4; private System. Windows. Forms. Label label 5; private System. Windows. Forms. Button button 1;

ØProgram. cs • Contains the Main function • Creates the forms and the other

ØProgram. cs • Contains the Main function • Creates the forms and the other components and makes them visible • Puts all together namespace Windows. Forms. Application 1 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] //Single thread model static void Main() { Application. Enable. Visual. Styles(); Application. Set. Compatible. Text. Rendering. Default(false); Application. Run(new Form 1()); } } }

ØFor the project work: Create a new Windows Forms application, following the example below:

ØFor the project work: Create a new Windows Forms application, following the example below: Create a new application • From the Start, chose All Programs then Microsoft Visual Studio 2013 • Maximize the VS 2013 Window • From VS 2013, File menu, choose New and then Project • In the window dialog New Project, create a new project with the following properties: • The project type: choose Visual C# and then choose from Windows Templates: Windows Application • Name: Sales. Application • Location: D: Proiecte C# • Create a directory for the solution : make sure that you checked Create directory for solution • In the dialog box New Project – click the OK button => the project will be created

Setting the properties for the implicit form of the application: • In the Solution

Setting the properties for the implicit form of the application: • In the Solution Explorer window, right click on Form 1 and rename as Main. Form. cs • In the Designer window, click on the form • In the Properties window set up the form properties: • • Form. Border. Style: Fixed. Dialog Size: 425, 200 Start. Position: Center. Screen Text: Main. Form Save and build the solution: • From the File menu choose Save All • In order to compile the application, from the Build menu choose Build Solution

Ø References: • „C# Programming, object-oriented programming”, Copyright Tutorials. Point, 2014, http: //www. tutorialspoint.

Ø References: • „C# Programming, object-oriented programming”, Copyright Tutorials. Point, 2014, http: //www. tutorialspoint. com/csharp_tutorial. pdf • John Sharp, Jon Jagger, “Microsoft Visual C#. NET Step By Step”, Microsoft Corporation, 2002

Thank you for your attention!

Thank you for your attention!