
C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#
.pdf
static void Main()
{
int Num1, Num2, Result;
Console.WriteLine("Enter any Number.");
String s1 = Console.ReadLine();
Num1 = int.Parse(s1);
Console.WriteLine("Enter another Number.");
String s2 = Console.ReadLine();
Num2 = int.Parse(s2);
try
{
Result = Num1/Num2;
Console.WriteLine("The result of the
division is:{0}", Result);
}
catch (Exception e)
{
Console.WriteLine("You tried division by zero!!");
}
finally
{
Console.WriteLine("You will definitely see this sentence.");
}
}
}
In this code, the user needs to enter two numbers, Num1 and Num2. The result of division of Num1 by Num2 is stored in the variable Result. The user might enter the value of Num2 as 0. This is an exception and needs to be handled. Therefore, the expression Result = Num1/Num2 has been placed in the try block. In case an exception is raised (a user enters 0 as the value of Num2), the control is transferred to the catch block, which displays the message "You tried division by zero!!" You also view another message "You will definitely see this sentence." because it is a part of the finally block. The output of the code is shown in Figure D-11.
Figure D-11: Output of the exception-handling code
Summary
In this appendix, you learned about the various data types and variables that are supported by C#. You also learned about the various looping structures, such as while, do, for, and foreach. Then, you learned about the decision structures that help an application to determine the action to be taken under different circumstances. These
decision structures in C# include the if...else and switch...case structures. Finally, you learned to handle unexpected events that can cause your program or your computer to behave abnormally by using the try, catch, and finally blocks.
Appendix E: C# Classes
Overview
C# is an object-oriented programming (OOP) language and it uses classes like any other OOP language. A class is a set of defined behaviors using primitive data types such as int, float, and char. In other words, a class defines the operations that its objects can perform, and defines a value that holds the state of its objects. Here, you must note that although CLR defines these primitive data types, their usage does not guarantee portability. For example, C# supports unsigned int, but VB does not. Thus, a class created in C# that uses unsigned int, will be difficult to use in VB.
Some of the members of a typical class are constants, methods, properties, indexers, and events. These class members have associated access specifiers, such as private or public, which define the scope of the members. This appendix explains how to create and use classes. It also covers the concepts and implementation of indexers and events.
Creating and Using Classes
Classes are an integral part of an object-oriented language. An object is defined as an instance of a class. When you create a class, you need to decide the members of the class and their accessibility. You specify the accessibility of the members of a class by using the access specifiers. Table E-1 describes various access specifiers that can be used for the members in a class.
|
Table E-1: Access specifiers |
|
|
|
|
|
|
|
|
|
Access Specifier |
|
Description |
|
|
|
|
|
|
|
public |
|
Indicates |
|
|
|
|
|
|
|
|
|
that the |
|
|
|
|
class |
|
|
|
|
member can |
|
|
|
|
be accessed |
|
|
|
|
from |
|
|
|
|
anywhere in |
|
|
|
|
the |
|
|
|
|
application. |
|
|
|
|
|
|
|
private |
|
Indicates |
|
|
|
|
|
|
|
|
|
that the |
|
|
|
|
class |
|
|
|
|
members |
|
|
|
|
cannot be |
|
|
|
|
accessed |
|
|
|
|
from outside |
|
|
|
|
the |
|
|
|
|
containing |
|
|
|
|
class. |
|
|
|
|
|
|
|
protected |
|
Indicates |
|
|
|
|
|
|
|
|
|
that the |
|
|
|
|
class |
|
|
|
|
member can |
|
|
|
|
|
|

Table E-1: Access specifiers
|
Access Specifier |
|
|
Description |
|
|
|
|
|
|
|
|
|
|
|
be accessed |
|
|
|
|
|
from within |
|
|
|
|
|
the |
|
|
|
|
|
containing |
|
|
|
|
|
class or |
|
|
|
|
|
from the |
|
|
|
|
|
derived |
|
|
|
|
|
class. |
|
|
|
|
|
|
|
|
internal |
|
|
Indicates |
|
|
|
|
|
|
|
|
|
|
|
that the |
|
|
|
|
|
class |
|
|
|
|
|
member can |
|
|
|
|
|
be accessed |
|
|
|
|
|
from |
|
|
|
|
|
anywhere |
|
|
|
|
|
within the |
|
|
|
|
|
program |
|
|
|
|
|
that has the |
|
|
|
|
|
containing |
|
|
|
|
|
class. |
|
|
|
|
|
|
|
|
protected internal |
|
|
Indicates |
|
|
|
|
|
|
|
|
|
|
|
that the |
|
|
|
|
|
class |
|
|
|
|
|
member can |
|
|
|
|
|
be accessed |
|
|
|
|
|
from |
|
|
|
|
|
anywhere |
|
|
|
|
|
within the |
|
|
|
|
|
program |
|
|
|
|
|
that has the |
|
|
|
|
|
containing |
|
|
|
|
|
class or |
|
|
|
|
|
from the |
|
|
|
|
|
derived |
|
|
|
|
|
class. |
|
|
|
|
|
||
|
Cross- |
To learn more about the concept of classes and objects, |
|
||
|
Reference |
refer to Appendix C, "Visual Basic Object-Oriented |
|
||
|
|
Programming." |
|
You use the keyword class to declare a class. To declare a typical class, the following syntax is used:
[modifi er] class <class name>
{
class body
}
The following list describes the elements in this syntax:
§[modifier] refers to modifiers, such as abstract and sealed, and access specifiers, such as public and private. This attribute is optional.
Note An abstract class is a class that cannot be instantiated and is intended to act only as a base class for other classes. While declaring an abstract class, you need to use the abstract modifier. The sealed class prevents other classes from inheriting it.
§class is the keyword used to declare the class.
§<class name> refers to the name of the class.
§class body refers to the body of the class. You declare the class members in this part of the class declaration.
While deciding on the name of a class, keep in mind the following naming guidelines:
§Use a noun or a noun phrase as a class name.
§Use PascalCasing notation in a class name. In PascalCasing notation, the first
character of every noun is capitalized. For example, a class named EmployeeDetails uses the PascalCasing notation.
§Do not use abbreviations in a class name.
§Do not use underscores in a class name.
You can use various members in a class depending on the requirement. Some class members are described in the following sections.
Constants
These class members refer to a constant value that can be assigned when the program is compiled. A constant in a class can depend on another constant only if no circular dependency exists. You can declare a constant by using the following code:
const int X;
In this code, the keyword const indicates that X is a constant. The data type of the constant X is integer.
CrossReference
Properties
These class members refer to the attributes of a class. For example, color and size can be the properties for a class named Cloth. When you define and declare a property, you use accessors. Accessors are a set of executable statements that are used to read or write a property. In a property declaration, you use the get and/or the set accessor, depending on the requirement. A get accessor is used to read the property, whereas a set accessor is used to write the property. The syntax for get and set accessors is given as follows:
get
{
statements
}
set
{
statements
}
Usually, the get and set accessors are used in pairs when declaring a property. When used in pairs, the accessors allow a property to be read as well as written. However, if you want a property to be read-only, you use only the get accessor. To declare a writeonly property, you use only the set accessor.
The following code declares a property called EmployeeCode, which uses both the get and set accessors. Therefore, you can read as well as write this property.
public class Employee
{
private string ECode;
public string EmployeeCode
{
§Use a verb or verb phrase that suggests the functionality of the method as the method name. For example, you can name a method that calculates salary for employees as CalculateSalary.
§Use PascalCasing in a method name.
CrossReference
To understand methods better, let us look at the following code snippet that declares a method called GetDetails in the Employee class. This method prompts users for the employee code and employee name.
public class Employee
{
private string EmpCode;
private string EmpName;
public void GetDetails()
{
Console.WriteLine("Please enter the employee code");
EmpCode=Console.ReadLine();
Console.WriteLine("Please enter the employee name");
EmpName=Console.ReadLine();
}
}
Then, you can access the GetDetails method by creating the object of the Employee class:
Employee emp;
emp=new Employee();
emp.GetDetails();
Constructor
A constructor is a class member that is used to initialize the data members of a class. A constructor always has the same name as the class. However, it does not have a return type. Here, it is important to mention that constructors are not the same as methods with a return type of void. A constructor does not have a return type, whereas a method must have a return type. In case a method does not return a value, the return type is specified as void. Also, a method is called explicitly, whereas a constructor is called automatically as soon as the object is created. A constructor may or may not take parameters. C# has three types of constructors, described next: default constructors, instance constructors, and static constructors.
Default constructor
The default constructor does not take any parameters. If you do not specify a constructor in a class, the default constructor is automatically provided. The following is the syntax to declare a default constructor for a class:
[modifier] <classname>()
{
}
This following list describes the elements in this syntax:
§[modifier] refers to the constructor modifier, which can be public, private, internal, or protected. This is optional. By default, it is
public. However, if the class is abstract, the default constructor is protected.
§<classname> refers to the name of the constructor, which is always the name of the class.
Instance constructor
This constructor is invoked for every instance of the class. An instance constructor is invoked as soon as the object of the class to which it belongs is created. It defines the actions that are required to initialize an object of the class. Unlike the default constructor, the instance constructor takes parameters. The following is the syntax to declare an instance constructor for a class:
[modifier] <classname>([parameter list])
{
<instance member>= <value>;
}
In this syntax:
§[modifier] refers to the constructor modifier, which can be public, private, internal, or protected. This is optional.
§<classname> refers to the name of the constructor, which is always the name of the class.
§[parameter list] specifies the parameters that the constructor takes. This parameter list is optional. The parameters in the parameter list are separated by commas.
§<instance member> = <value> assigns the specified value to the instance members that have been defined in the class.
Static constructor
This constructor is invoked only once for a class regardless of the number of instances of the class. A static constructor defines the actions that are required to initialize the static members of a class. A static constructor does not take any parameters and it cannot be invoked explicitly. The following is the syntax to declare a typical static constructor:
static <classname>()
{
< static member>= value;
}
In this syntax:
§static is the keyword that is used to specify that the constructor is static.
§<classname> refers to the name of the constructor, which is always the name of the class.
§<static member> = <value> assigns the specified value to the static members that have been defined in the class.
Destructor
This class member defines the actions that need to be performed to destroy an instance (object) of the class. In a destructor, the data members are deinitialized. A destructor is called automatically when the instance of a class goes out of scope. A destructor cannot be called explicitly and it does not take parameters. A destructor of the base class is not
inherited by the derived class. A destructor has the same name as the class and is preceded by a tilde (~). The following is the syntax used to declare a destructor:
~<class name>()
{
statements;
}
Where:
§~<classname> refers to the name of the destructor.
§statements refer to the statements that would be executed when the instance of the class is destroyed.
Console applications
Using C#, you can create Console, Windows, and Web applications. The following sections discuss the procedure of creating Console applications using Notepad and Visual Studio .NET.
You can create a Console application by using Notepad or Visual Studio .NET. Irrespective of the way it is created, the output of a Console application is always displayed on the console.
Creating a Console application using Notepad
You can use the following steps to create a Console application using Notepad:
1.Type the code for the application in Notepad. For example, to create a Console application that displays "Hello World!!" on the console, type the following code in Notepad:
2.using System;
3.
4.
5.public class HelloWorld
6.{
7.public static void Main()
8.{
9. Console.WriteLine("Hello World!!");
10.}
}
In this code, a public class HelloWorld is created. It has a Main() method, which is the entry point in the application. Here, Main() is a static member of the class HelloWorld and has no return type. The WriteLine() method of the Console class is used to display the text specified in the parentheses on the command prompt.
11.Save the file with the extension .cs. For example, you would save the file that contains class HelloWorld as HelloWorld.cs.
12.Go to the command prompt.
13.Navigate to the folder in which you have saved the CS file.
14.At the command prompt, type the following:
csc <filename>.cs
The preceding command is used to compile the file <filename>.cs. If there are no compilation errors, <filename>.exe is created.
Note During compilation, if any errors are displayed on the command prompt, you need to debug the code, save it, and then recompile it before moving to the next step.
15. At the command prompt, type the following:
<filename>.exe
This command displays the output of the application on the console.
Creating a Console application using Visual Studio .NET
If you decide to use Visual Studio .NET to create a Console application, you need to proceed as follows:
1.Select File → New → Project to open the New Project dialog box.
2.In the New Project dialog box, select Visual C# Project in the left pane and select Console Application in the right pane.
3.Specify a name and path for the new project, if necessary, and click
OK.
4.The code window that contains the basic structure of the class opens.
5.Create a class with the required class members.
6.After typing the code, save the code and build it. If no errors are detected during compilation, the output is displayed on the console. However, if errors are detected, you need to debug the code, save
it, and again build it to view the output.
For example, to create a class Employee that takes the employee name and sales made by the employee as input, and calculates a commission on the basis of the sales, you can use the following code:
using System;
public class Employee
{
public Employee()
{
}
public void Print(string str)
{
Console.WriteLine("The employee name is: {0}",str);
}
public void Calculate(int x)
{
double SalesValue;
if (x<2000)
{
SalesValue =x*.15;
}
else
{
SalesValue =x*.20;
}
Console.WriteLine("The commission is: {0}", SalesValue);
}
static void Main(string[] args)
{
Employee emp1;

emp1 = new Employee();
string EmployeeName;
string Sales;
int x;
Console.WriteLine("Enter the employee name");
EmployeeName=Console.ReadLine();
Console.WriteLine("Enter the employee sales");
Sales=Console.ReadLine();
x=int.Parse(Sales);
emp1.Print(EmployeeName);
emp1.Calculate(x);
}
}
In the preceding code, a class Employee has been created. It has a default constructor, Employee(). In the class, two methods, Print() and Calculate(), have been defined. The Main() method is the entry point of the application. Notice the declaration of the Main() method, which is generated by VS.NET automatically. In this declaration, the Main() method takes a string array that is used to pass command-line arguments to invoke the program. An object emp1 of the Employee class is created and initialized. The Main() method takes the employee name and sales from the user as input.
To read the user input from the console, you use the ReadLine() method of the Console class. The user input is then stored in the variables, EmployeeName and Sales. The int.Parse() method is used to convert the string value in the variable Sales to an integer value, which is then stored in an integer type variable x. After taking the user input, the Print() method is called, using the statement emp1.Print(EmployeeName). The value in the variable EmployeeName is passed as a parameter to the method Print(). This method prints the employee name entered by the user on the console. The return type of this method is void.
The Calculate() method is called using the statement emp1.Calculate(x). This method takes the integer value of sales stored in the variable x as a parameter. The Calculate() method uses the value stored in x to calculate the commission for the employee. The Calculate() method includes an if...else decision structure that tests whether the value of x (sales made) is less than 2,000. If the value is less than 2,000, commission is calculated as 15 percent of the value. However, if the value is greater than 2,000, the commission is calculated as 20 percent of the value. This calculated commission is then displayed on the screen using the
Console.WriteLine() method.
When you build and run the code specified, "Enter the Employee Name" is displayed on the console. When you enter the employee name and press Enter, "Enter the Employee Sales" is displayed on the console. The values that you enter are used by Print() and Calculate() methods to display the employee name and the commission. A sample output of the code is shown in Figure E-1.
Figure E-1: A sample output of a Console application
Windows applications
Windows applications are created using Visual Studio .NET. Windows applications have a form that is used to take user input and display the output.