Translate

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, September 5, 2012

Exception Handling in .Net or Handling Exception in C#

Exception Handling or Handling Exception

What is an Exception

An exception is an indication of an error or exceptional condition such as when try to open a file that is not physically exists or when we write a method which throws exception, the calling code must be able to detect and handle exception.
If the calling method code cannot handle the exception, the exception is automatically propagated to the code that invoked the calling code.

The exception is propagated until a section of code handles the occurred exception.
If no code handles the exception, there are 100 percent chances that it will give runtime errors and will report unhandled exception and finally the application will crash.

How Exceptions Propagate in .Net Framework

This is where exceptions in the .NET Framework prove useful. An exception is an indication of an error or exceptional condition. A method can throw an exception when it detects that something unexpected has happened, for example, it tries to open a file, but the file does not exist. When a method throws an exception, the calling code must be prepared to detect and handle this exception. If the calling code does not detect the exception, it is aborted and the exception is automatically propagated to the code that invoked the calling code. This process continues until a section of code takes responsibility for handling the exception. Execution continues in this section of code after the exception-handling logic has completed.

For an example, suppose the ABC method calls the DEF method. As part of its processing,the DEF method calls the GH method. While it is running, the GH method throws an exception. This exception may cause the GH method to abort, and the exception is passed back to the DEF method. If the DEF method is not prepared to handle the exception, it also aborts and the same exception is passed back to the ABC method. If the ABC method handles the exception, execution continues in the ABC method after the exception-handling logic. If the ABC method is not prepared to handle the exception, the exception will be propagated back to the method that called the ABC method. If this is the Main method, and Main is also not prepared to handle the exception, the application reports the unhandled exception to the user and then terminates.
ABC method can catch and handle its own exceptions to provide a degree of robustness that the calling code may not even be aware of. For example, a method that updates a database may catch an exception that occurs if the connection to the database fails. It may try connecting again, possibly with an alternative set of credentials. This process can be hidden from the code that called the method.

Using Try and Catch in C#

try/catch block is the plays a key role in programming. We wrap the code that may fail and cause an exception in a try block, and add one or more catch blocks to handle any exceptions that may occur.

The following example shows about how to implement Try Catch

try
{
// Try block.
}
catch ([catch specification 1])
{
// Catch block 1.
}
catch ([catch specification 2])
{
// Catch block 2.
}
catch ([catch specification 3])
{
// Catch block 3.
}
catch ([catch specification n])
{
// Catch block n.
}

It can have “n” number of catch blocks.

Catch: The catch specification for each block determines what exceptions will be caught and what variable is used to store the exception, if any. we can specify catch blocks for different types of exceptions.
The .NET Framework defines many different exception types for many of the common exceptions that can occur.
Few of exception types in namespace for example System.IO namespace that handle file I/O throw
the FileNotFoundException exception if an application attempts to access a nonexistent file. In addition, the common language runtime (CLR) itself throws a DivideByZeroException exception if you attempt to perform numeric division by zero. When an exception occurs, you do not have to include a catch block for every type of exception, and exceptions that are not matched will be propagated as described earlier.

If we are not specifying exception type in the catch block then it catches any type of exception

For example

//Try Block code
Try
{
}
//Catch Block Code
Catch
{
}

If we want to know what is the exception occurred we can access by using variable of exception declared in catch block

For example
catch (Exception ex)
{
// Catch block, can access exception in ex.
}

In above example “ex” will give the more information about exception

Important to Note:
 Exception types can implement a hierarchy of exceptions.
 For example,
 The .NET Framework provides an exception type called ArithmeticException, which you can   use to indicate an error when evaluating an arithmetic expression. The DivideByZeroException type is a specific classification of ArithmeticException (the .NET Framework also defines two other types of ArithmeticException called OverflowException and NotFiniteNumberException). If you catch the
DivideByZeroException exception, only that exception type is caught. However, if you catch the ArithmeticException exception, this catch block will trap DivideByZeroException, OverflowException, and NotFiniteNumberException. Therefore, if you have multiple catch blocks, you must ensure that you place the blocks.


Raising Exceptions

Creating an Exception object

1.     System.Exception
  System.SystemException
 System.FormatException
 System.ArgumentException
System.NotSupportedException

List describe the different types of Exception



Type
Description
FormatException
It throw this exception if the caller specified an argument that contains data that does not have the required format. For example, if the caller passes a string argument that does not contain information in the format that the method expects, the method should throw a FormatException exception.
ArgumentException
It throw this exception if the caller specifies an argument to a method that does not conform to the requirements of the method. You can use this exception type to indicate generalized errors with arguments, or you can use the ArgumentOutOfRangeException and
ArgumentNullException types to indicate more
specific errors (for example, if you pass the value 100 to a method, and the method expects a value between 1 and 99, or if you pass the value null as an argument).
NotImplementedException
It throw this exception to indicate that you have not yet implemented the code in a method.
This exception is primarily useful while you are
developing code when you have defined the
method, but have not written the code for the
body of the method
NotSupportedException
You can throw this exception if a caller attempts to perform an unsupported operation by using your method, such as specifying arguments that indicate that the caller wants to write to a read-only file.
FileNotFoundException
DirectoryNotFoundException
DriveNotFoundException
You can throw these exceptions in methods that
attempt to open files on behalf of a caller. If the
name of the file that is indicated by arguments that the caller specifies reference a file that does not exist, or the file is in a folder or drive that does not exist.





Friday, August 31, 2012

Using Overriding and Hiding Methods in C#


Overriding in C#


Extend or replace functionality in the base class
It is required to provide an implementation that has the same meaning as the original method, but has an implementation that is specific to the class. Virtual methods typically provide a default implementation that
inheriting classes are expected to replace with their own code.
To override a method in a subclass, you use the override keyword, as the following
code example shows
public Class Employee
{
protected int EmployeeNumber;
protected string EmployeeFirstName;
protected string EmployeeLastname;
protected float Salary;
Protected virtual void WorkAssigned()
{
}
}

//Program Manager class inheriting from  Employee class
Public Class TechnicalManager:Employee
{
Protected  Override void WorkAssigned()
{
}
}


Hiding Methods in C#
You can define methods in an inherited class that have the same name as methods
in a base class, even if they are not marked as virtual, abstract, or override.
However, this means that there is no relationship between your method and the
original method, and new method hides the original method.

Code
Public Class Employee
{
protected void  ActOn()
{
...
}
}
class Manager : Employee
{
public new void  ActOn()
{
// Hiding he ActOn method in the base class
//Code goes here
}

}

Inheriting from Classes and Implementing Interfaces

What is Inheritance or How to define Inheritance in C#


Inheritance is the most feature in the object oriented programming.
Inheritance helps not do the repetition of code the same code in the multiple places when dealing with
different classes  which have several features in common and are related to each other. Even they are
different subclasses of the same type, each with its own distinguishing feature


Declared and Define Inherited Class
Parent/Base Class
public Class Employee
{
protected int EmployeeNumber;
protected string EmployeeFirstName;
protected string EmployeeLastname;
protected float Salary;
Protected void WorkAssigned()
{
}

}

//Program Manager class inheriting from  Employee class
Public Class TechnicalManager:Employee
{
Public void ProgramManagerWorkAssigned()
{
}
}

//Program Technical Manager class inheriting from  Employee class
Public Class TechnicalManager:Employee
{
Public void TechnicalManagerWorkAssigned()
{
}
}


example, Program Manager and  Technical Manager ,Engineer are all employees of a Software Company .
When we are writing an application to simulate the Employee Management System, how would you specify that
Program Manager and Technical Manager and Engineer have several features that are the same, but also
other features that are different? For example, they all have an employee reference  employee number and a name and so on, also each one has different responsibilities. When we want to define class of Program Manager and Technical Manager and Engineer each has to be inheriting the employee. So we don’t need to define the common features in all the classes.

In C# inheritance is implemented by using “:” 

Thursday, August 30, 2012

Using Decision Statements in C# ternary operator If Else

Using Decision Statements in C#

Using the ?: Operator or ternary operator and If Else

C# performs the statements in a program in a sequential manner. However, you frequently need to specify that alternative statements should run depending on the value of an expression or a Boolean condition. To achieve this ,C# provides conditional decision statements. Explain how to use the if else statement.

1.     Using If Else
2.     Using ?: operator.
3.     Using  switch statement


If else
1.
If ([Condition]) //Code to Execute

2
.If ([Condition])
{
//If condition is true
//Code to Execute
}

3.
.If ([Condition1] && [Condition2])
{
//If condition is true
//Code to Execute
}

4.
.If ([Condition1] || [Condition2])
{
//If condition is true
//Code to Execute
}

if statements are very useful when you want to execute a code statement based on a condition. The basic syntax for a one-way if statement is shown in the following code example.

if ([condition]) [code to execute]

if the expression [condition] evaluates to a Boolean true value, [codeto execute] is executed. Notice that the condition must be enclosed in parentheses.You can execute more than one code statement. To do this, you delimit the code to run by using braces. This extends the syntax as the following code example shows.
if ([condition])
{
[code to execute if condition is true]

}
If(a>50)
{
C=a+b;
}

If Else statement
Provides additional code block to execute if [Condition] is evaluates to boolean false

If([Condition])
{
//Execute code
}
Else
{
//Else code to execute
}

Using the ?: Operator or ternary operator
As an alternative to using the if else statements, in some simple cases, you can use
the “?: “ ternary operator.The basic syntax to use the ?: operator is shown in the following code example.

Type result = [condition] ? [true expression] : [false expression]

If the expression [condition] evaluates to true, [true expression] is executed, but if the [condition] evaluates to false, [false expression] is executed.The following code example shows an example of using the ?: operator to check the value of a string, and then return a response.
string penColor = "green";
string response = (penColor == "red") ? "You have a red pen" :"You do not have a red pen";

Wednesday, August 29, 2012

Variable Scope in C#

Variable Scope in C#




Variables can have one of the following levels of scope:
• Block
• Procedure
• Class
• Namespace

Block
Code:
if (sum> 100)
{
int a= sum1+sum2;
}
Here the variable a is defined inside the Block {} and it scope is inside {} and cannot access the “a” outside of the block ,if try to access will give error.





Procedure Scope

code
Internal string  GetConnection()
{
String message=”Hello Procedure Scope”;
Response.Write(message);
}
In this sample message is declared and can be used in the method GetConnection()

Class Scope

Code:
Public static class Sample{
private string myMsg;
void SetMessage ()
{
myMsg = "Hello World!";
}
void ShowMessage ()
{
MessageBox.Show(myMsg);
}
}

In this sample “myMsg” is declared inside the Sample and used in two procedures

Assigning a Value to a Variable in C#

Assigning a Value to a Variable in C#


The assignment operator (=) assigns a value to a variable. The syntax of a variable assignment is shown in the following code.
VaraibleName=AssignedValue;

String helloAssignment=”I am from assignment”;

Declaring and Assigning Variables in C#

Declaring and Assigning Variables


When we need to use a variable we must need to declare by naming the variable which is known as identifier and its data type. To use some value in the variable we need to assigned the value.

Identifier
An identifier must start with a letter or an underscore, it can only contain letters, digits, and underscore characters.

Int a ;


C# Data Types or Data Types in C#

C# Data Types or what are Data Types in C#


A variable holds data that has a specified type. When we declare a variable to store data in an application, we are required to choose an appropriate data type for that data to hold.
It is known that C# is a type-safe language, which means that the compiler guarantees that values that are stored in variables are always of the appropriate type.

Frequently Used Data Types
The following table shows the frequently used data types in C#, and their characteristics.

Type
Size
Range
Description
Long
8
–2,147,483,648 to 2,147,483,647
Number with big range
Int
4
–9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Whole Number
Float
4
+/–3.4 × 10^38
Float
Double
8
+/–1.7 × 10^308
Double
precision
(more
accurate)
floatingpoint
numbers
Decimal
16
28 significant figures
Decimal values
String
2 per character
There is no limit
List of characters
DateTime
8
0:00:00 on 01/01/0001 to 23:59:59 on
12/31/9999
Date and time

Variables in C#

Variables in C#


Variables stores values required by application in temporary memory locations, a variable represents a named location in memory for a piece of data. An application can access a piece of data by using the variable it has been assigned to variables store values that an application can change while it is running. Sometimes it is required to store values temporarily when we perform calculations or pass data between the user, an application, or a database.
A variable has the following six facets:
1.Name. Unique identifier that refers to the variable in code.
2. Address. Memory location of the variable.
3. Data type. Type and size of data that the variable can store.
4. Value. Value at the address of the variable.
5. Scope. Defined areas of code that can access and use the variable.