Web-based programming - 5

int Nam;

int Month; int Day; int Hour; int Minute; int Second;

}

public class Tester

{

static void Main()

{

Time t = new Time(); t.ExecutingTime();

}

}

The ThoiGian class has only one main method, the ThoiGianHienHanh() function, the body of this method is defined inside the ThoiGian class. This is different from the C++ language, C# does not require a declaration before defining a method and also does not support declaring a method in one file and then defining it in another file.

C# does not have header files, so all methods are defined entirely within the class. The last part of the class definition is the declaration of the member variables: Nam, Thang, Ngay, Gio, Min, and Giay.

After defining the ThoiGian class, the next step is to define the Tester class, which contains a function called Main(). Inside the Main function, an instance of the ThoiGian class is created and assigned a value to the t object. Because t is an instance of the ThoiGian object, the Main() function can use t's methods:

t.ActualTime();

Access properties:

Accessibility attributes determine whether methods of other classes can see and use member variables or methods within the class.

The following table summarizes the access properties of a class in C#.


Properties

Access Restrictions

public

No restrictions. Members marked public can

used by any methods of the class including other classes.

Maybe you are interested!

Web-based programming - 5


private

A member in a class A marked as private is only

accessed by methods of class A.

protected

Members of class A marked as protected can only be

methods inside class A and methods derived from class A access.

internal

Members in class A marked as internal are accessible

accessed by methods of any class in the same assembly as A.

protected internal

Members in class A marked as protected internal are accessible by methods of class A, methods of derived classes of A, and any class in the same assembly block.

A's language

C# considers private attributes as default, so class member variables are private. Only class member methods can access the value of the variable. Therefore, we do not declare access attributes for 6 variables, so they are private by default:

// Private member variables

int Year; int Month; int Day; int Hour; int Minute; int Second;

Since the Tester class and the ThoiGianHienHanh member method of the ThoiGian class are declared public, any class can access them.

Method parameters:

In programming languages, parameters and arguments are considered the same thing, similarly when talking about object-oriented languages, we call a function a method or a behavior. All these names are similar to each other.

A method can take any number of parameters, which come after the method name and are enclosed in parentheses (). Each parameter must be declared with a data type. For example, we have a declaration defining a method named Method, which does not return any value (declares the return value as void) and has two parameters, an int and a button:

void Method( int param1, button param2)

{

//...

}

Inside the body of the method, these parameters are treated as local variables, just like declaring variables inside the method and initializing their values ​​with values.

of the parameters passed. The following example illustrates passing parameters to a method, in this case the two parameters are of type int and float.

Example: Passing parameters to a method

using System; public class Class1

{

public void SomeMethod(int p1, float p2){ Console.WriteLine(“Receiving two parameters:”, p1,p2);

}

}

public class Tester

{

static void Main(){

int var1 = 5; float var2 = 10.5f; Class1 c = new Class1(); c.SomeMethod( var1, var2 );

}

}

The SomeMethod method takes two parameters int and float and displays them on the screen using the Console.WriteLine() function. These parameters named p1 and p2 are considered as local variables inside the method.

In the Main method, two local variables are created, var1 and var2. When these two variables are passed to the SomeMethod method, they are mapped to two parameters p1 and p2 in the order of the variable list. In the above example, the two parameters int p1 and float p2 in the function SomeMethod(int p1, float p2) are also called formal parameters, the two parameters var1 and var2 in the function call SomeMethod(var1, var2) are called actual parameters.

2.7.2. Create object

a) Create object

Standard C# data types like int, char, float,… are value data types and variables created from these data types are stored on the stack. However, reference data type objects are created on the heap, using the new keyword to create an object:

Time t = new Time();

The variable t does not contain the value of the ThoiGian object, it only contains the address of the object created on the heap, so t only contains a reference to one object.

b) Destroy the object

C# provides garbage collection and therefore there is no need to explicitly declare destructors. However, for clarity, it is necessary to explicitly declare destructors to release resources.

~Class1()

{

// Do some work

}

2.8. Exception Handling

C#, like any other object-oriented language, allows handling errors and unusual conditions with exceptions. An exception is an object that encapsulates information about a program's failure to behave normally.

It is important to distinguish between bugs, errors and exceptions. A bug is a programming error that can be fixed before the source code is committed. Exceptions are not protected and are in contrast to bugs. Although a bug can cause an exception, do not rely on exceptions to handle bugs in the program, it is better to fix the bugs.

An error is caused by a user action. For example, the user enters a number but instead enters a letter. Again, the error may cause an exception to be raised, but this can be prevented by catching the error with valid code. Errors can be anticipated and prevented.

Even if all bugs are removed and all user errors are anticipated, unexpected problems may occur, such as out of memory, lack of system resources, etc. These may be caused by other programs running at the same time. These exceptions cannot be prevented, but they can be handled so that they do not harm the program.

When a program encounters an exceptional situation, such as a lack of memory, it raises an exception. When an exception is raised, the execution of the current function is suspended until a corresponding exception handler is found.

This means that if the currently running function does not handle the exception, then it will terminate and the calling function will receive the change to handle the exception. If the calling function does not handle the exception, the exception will be handled prematurely by the CLR, which will cause the program to terminate.

An exception handler is a block of program code designed to handle exceptions that arise in the program. Exception handling is implemented in the catch statement.

If an exception is caught and handled, the program can correct the problem and continue execution. If the program does not continue, by catching the exception it prints meaningful messages and terminates the program cleanly.

If a piece of code executes regardless of any exceptions that may be encountered (such as when freeing a resource that the program has allocated), it is possible to put this code in a finally block, which will then ensure that it is executed even if an exception occurs.

In C#, only objects of the System.Exception type, or objects derived from this type, can be thrown. The CLR's System namespace contains a number of exception handling types that can be used in programs. These exception types include ArgumentNull-Exception, InValidCastException, and OverflowException, as well as many others.

2.8.1. The throw statement

To report an anomaly in a class in C# language an exception is thrown. To do this use the throw keyword. The following line of code creates a new instance of System.Exception and then throws it:

throw new System.Exception();

When an exception occurs, execution immediately stops while the CLR searches for an exception handler. If an exception handler is not found in the current method, the CLR continues searching in the calling method until it finds one. If the CLR returns to Main() without finding any exception handler, it terminates the program.

Example: Throw exception

namespace Programming_CSharp

{

using System; public class Test

{

public static void Main(){ Console.WriteLine(“Enter Main....”); Test t = new Test(); t.Func1(); Console.WriteLine(“Exit Main...");

}

public void Func1()

{

Console.WriteLine(“Enter Func1...");

Func2();

Console.WriteLine(“Exit Func1...");

}

public void Func2()

{

Console.WriteLine(“Enter Func2..."); throw new System.Exception(); Console.WriteLine(“Exit Func2...");

}

}

}

This example writes information to the console as it enters a function and exits from a function. The Main() function creates a new instance of type Test and then calls Func1(). After printing the message “Enter Func1”, this Func1() calls Func2(). Func2() prints the first message and raises an exception of type System.Exception. Execution stops immediately and the CLR searches for an exception handler in Func2(). Since it does not find one, the CLR goes down the stack to get the previously called function, i.e. Func1, and searches for an exception handler. Again, there is no exception handler in Func1. And the CLR returns to the Main function. There is no exception handler in Main either, so the CLR calls the default exception handler, which simply outputs an error message.

2.8.2. The catch statement

In C#, an exception handler or a piece of code that handles exceptions is called a catch block and is created with the catch keyword.

In the following example, the throw statement is executed inside the try block and a catch block is used to declare that an error has been handled.

Example: Catching exceptions

namespace Programming_CSharp

{

using System; public class Test

{

public static void Main()

{

Console.WriteLine(“Enter Main..."); Test t = new Test();

t.Func1();

Console.WriteLine(“Exit Main...");

}

public void Func1()

{

Console.WriteLine(“Enter Func1..."); Func2();

Console.WriteLine(“Exit Func1...");

}

public void Func2()

{

Console.WriteLine(“Enter Func2..."); try {

Console.WriteLine(“Entering try block..."); throw new System.Exception(); Console.WriteLine(“Exiting try block...");

}

catch {

Console.WriteLine(“Exception caught and handled.”);

}

Console.WriteLine(“Exit Func2...");

}

}

}

The Throw exception example and the Catch exception example above are similar except that the program in the Throw exception example is enclosed in a try/catch block. It is common to place a try block around potentially dangerous sections of code, such as file access, memory allocation, etc. The try block is followed by a general catch statement. The catch statement in this example is general because it does not specify what type of exception to catch. In this general case, the catch block will catch any exception that is thrown.

In the example of catching an exception, the catch block simply reports that an exception was caught and handled. In the specific example, we can take the correct action to fix the problem that caused the exception. For example, if the user is trying to open a file that has a read-only attribute, we can call a method that allows the user to change the file's attributes. If the program runs out of memory, we can issue a

use the opportunity to close other applications. Even in the worst case we cannot fix it, this catch block can print an error message to let the user know.

In the exception catching example, we see code going into each function like Main(), Func1(), Func2() and the try block. We never see it exit the try block (i.e. print the message “Exiting try block…”, or execute this statement), even though it still exits Func2(), Func1() and Main() in the same order. What happens?

When an exception is raised, the execution is immediately halted and the execution is passed through the catch block. It never returns to the original execution thread, i.e. the statements after the exception is raised in the try block are not executed. In this case we will never get the message “Exiting try block....". The catch block handles the error and then passes the program execution to the statements after the catch block. There is no return to the previous function call in the stack. The exception is now handled, nothing happens and the program continues to function normally. This becomes clearer if we move the try/catch block up to the Func1 function as in the example below.

Example: Catch in function call

namespace Programming_CSharp

{

using System; public class Test

{

public static void Main()

{

Console.WriteLine(“Enter Main..."); Test t = new Test();

t.Func1();

Console.WriteLine(“Exit Main...");

}

public void Func1()

{

Console.WriteLine(“Enter Func1..."); try {

Console.WriteLine(“Entering try block..."); Func2();

Console.WriteLine(“Exiting try block...");

}

Comment


Agree Privacy Policy *