1. Trang chủ
  2. » Công Nghệ Thông Tin

Giáo trình C# -C# Corner

187 460 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề C# Corner: C# and .NET Developer's Network
Tác giả Amisha Mehta, Vivek Gupta, Rahul Sharma, Yoganand Aiyadurai, G. Gnana Arun Ganesh, Kunal Cheda, Ashish Banerjee, Prasad H.
Trường học C# Corner
Chuyên ngành C# Programming
Thể loại tài liệu
Năm xuất bản 2001
Thành phố unknown
Định dạng
Số trang 187
Dung lượng 1,8 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Giáo trình C#

Trang 1

C# Corner: C# and NET Developer's Network

Working with Data Types

Explains data types in C# and how to work with them

Control Statements: Part 1 By Amisha Mehta

This lesson shows how to use c# control statements, and the difference between these controls in c++/ JAVA and c# Sample includes single selection, if-else, and multi case

Control Statements: Part 2 By Amisha Mehta

This lesson shows how to use while do, for, for each statements

Language Preprocessor Directives By Vivek Gupta

This lesson contains C# language preprocessor directrives including #if, #else,

#define, #undef, #line etc with sample examples

Properties in C#: New cover on old book by Vivek Gupta

Properties are accessor methods whose job it is to retrieve and set the values of fields.

Exception Handling By Amisha Mehta

Exceptions in C# provide a structured, and type-safe way of handling both system level and application level error conditions The exception mechanism in C# is very similar to that of C++

What & Why? Properties: Part 1 by Rahul Sharma

If you were programming in C or C++ before coming to C#, you'll be a little bit confused about properties.

What & Why? Properties: Part 2 by Rahul Sharma

In the part 1 of this series, I discussed about the get method of the properties, with the help of which you can make your variable so that nobody can modify the value of the variable

Difference using Directive and Statement by Yoganand Aiyadurai

This article explains difference between using directive and using statement with sample example.

C# and its Types by G Gnana Arun Ganesh

A detailed tutorial and C# types such as Value and Reference types with sample examples.

Events and Delegates By Kunal Cheda

Events in C# are based on delegates, the Originator defining one or more callback functions

for each: A C# Syntax which Java lacks by Ashish Banerjee

C# has a new iteration syntax called foreach, which I believe has been inherited

from Visual Basic ( correct me if I am wrong).

C# and its features by G Gnana Arun Ganesh

C# is a modern, type safe programming language, object oriented language that enables programmers to quickly and easily build solutions for the microsoft NET platform

Boxing and Unboxing by G Gnana Arun Ganesh

Boxing and unboxing is a essential concept in C#’s type system With Boxing and

unboxing one can link between value-types and reference-types

C# Beginners

Introduction to C#

Working with Data Types C# and its Types Control Statements: Part 1 Control Statements: Part 2 Constructors and Destructors Properties in C#

Exception Handling Using Attributes in C#

Encapsulation in C#

Exploring Delegates Namespaces

http://www.c-sharpcorner.com/language.asp (1 of 4) [11/27/2001 7:17:40 PM]

Trang 2

Operator Overloading in C# by Prasad H.

The Source code below shows how to use OperatorOverloading in C# Operator Overloading is pretty useful concept derived from C++ by C#.

Using Attributes in C# by Rajadurai P

This article shows how to create custom attribute classes, use them in code, and query them.

Using Array class and IEnumeration by Rajadurai P

This article illustrates the usage of Array class and IEnumerator Array class Provides methods for creating, manipulating, searching and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.

Enumerators in C# by Prasad H

Sample example shows you how to use enumerators in C#.

Visual Inheritance in C# by Prasad H

We all know that Inheritance means a extending a class with more Features without worrying about the implementation of features of hidden inside the class to be inherited.

Visual Inheritance Part 2 by Prasad H

We all know that Inheritance means a extending a class with more Features without worrying about the implementation of features of hidden inside the class to be inherited.

Abstract Classes and Methods by Rajesh V.S

This is a detailed analysis of Abstract classes and methods in C# with some concrete examples.

Constructors and Destructors by Rajesh V.S

This detailed article talks about how constructors and destructors work in C# and how to use them in your applications

Encapsulation in C# G G Arun Ganesh

In Object Oriented programming Encapsulation is the first pace Encapsulation is the procedure of covering up of data and functions into a single unit (called class)

Method Parameters in C# G G Arun Ganesh

This article describes different method parameters such as value parameters, reference parameters, output parameters, and parameter arrays

Understanding Properties in C# Rajesh V.S

In C#, properties are nothing but natural extension of data fields They are usually known as ‘smart fields’ in C# community.

Understanding Structures in C# Rajesh V.S

A structure in C# is simply a composite data type consisting of a number elements of other types.

Understanding Enumerators in C# Rajesh V.S

An enumeration (enum) is a special form of value type, which inherits from System.Enum and supplies alternate names for the values of an underlying primitive type.

Inheritance and Polymorphism Rajesh V S

By using the concept of inheritance, it is possible to create a new class from an existing one and add new features to it.

Exploring Delegates By Filip Bulovic

Delegates are a kind of type safe function pointers which are actually declared as class derived from System.MulticastDelegate.

BitWise Operations in C# By Chandra Hundigam

C# has lots of flexibility over manipulating with bits Before I start explaining about bit wise manipulation I would like to give some inputs on binary operations.

http://www.c-sharpcorner.com/language.asp (2 of 4) [11/27/2001 7:17:40 PM]

Trang 3

C# Corner: C# and NET Developer's Network

Pointers in C# Rajesh V S

C# also supports pointers in a limited extent A pointer is nothing but a variable that holds the memory address of another type But in C# pointer can only be declared to hold the memory address of value types and arrays.

Implementing Stacks in C# Danish Sami

With the help of C# we can also implement ADT (Abstract Data Types) with little effort An example of ADT is a simple stack of integers.

Working with Namespaces in C# Rajesh V S

In C#, namespaces are used to logically arrange classes, structs, interfaces, enums and delegates The namespaces in C# can be nested That means one namespace can contain other namespaces also.

Passing const parameters in C#, C++, and VB.NET by Bulent Ozkir

Parameter passing to a function is extremely important in all programming languages

The desire to keep the passed parameter intact forced the compiler designers to add various keywords to

Multiple inheritance in C# by Craig Breakspear

Can you inherit from multiple classes in C#? Simply put, this cannot be done However there are ways around it From a design perspective you must ask yourself, Will a Class fully represent an object?

Interface Component Interoperability by G Gnana Arun Ganesh

The fundamental concept behind both COM and DCOM is the interface An interface is

an agreement between a client and an object about how they will communicate with each other.

Difference between const and readonly

The sample example shows the difference between const and readonly Submitted by Say Gin

C# Language changes from NET Beta 1 to NET Beta 2

This article contains C# language changes from Beta 1 to Beta 2 Submitted by Vivek Gupta Source MSDN documentation.

Using out and ref parameters By Kunal Cheda

When we pass a parameter as ref to a method, the method refers to the same variable and changes made will affect the actual variable.

The out and ref parameters

The out and the ref parameters are used to return values in the same variables, that

you pass an an argument of a method These both parameters are very useful when your method needs to return more than one values.

Serializing Objects in C#

In simple words serialization is a process of storing the object instance to a disk file

Serialization stores state of the objecti.e member variable values to disk

Deserialization is reverse of serialization i.e.

Operator Overloading Example by Prasad

The code uses the feature of Operator Overloading in C# It shows how different operators are overloaded and can be used in a easy manner.

Regular Expressions Example by Prasad

The following example shows the use of Regular Expresssions in C#.This program has basic validation scripts for validation easily useable in all programs.

.

contact: webmaster@c-sharpcorner.com copyright © 2000 c-sharpcorner.com All rights are reserved See terms and condition to use this site and its contents.

http://www.c-sharpcorner.com/language.asp (3 of 4) [11/27/2001 7:17:40 PM]

Trang 4

Sponsors: devexpress microgold apress

http://www.c-sharpcorner.com/language.asp (4 of 4) [11/27/2001 7:17:40 PM]

Trang 5

C# Corner: C# and NET Developer's Network

Installing NET SDK

Installing NET SDK is first step to run C# on your machine You can install NET SDK on Windows

ME, Windows NT, or Windows 2000 But Windows 2000 is recommended After selecting your OS, you need to follow these steps:

Framework SDK

extension Type this in an notepad and save as my.cs

C# Compiler and Editors

.NET SDK Beta 1 release of Microsoft's new platform, NET, incorporated with C# command line compiler You must have to install NET SDK to run a C# program Once you install NET SDK, you can write your C# program in any text editor including notepad, wordpad or Visual Studio

There are some third party editors are available in the market too Some of them are free Check out tools section of C# Corner

Write your first C# program

Writing your first C# program is similar to writing C++ applications You open any text editor, I described in the above paragraph and type this code

using System;

class MyClass {

static void Main() { Console.WriteLine("Hello World!");

}}

Compile your first C# program

Now use command line to compile your cs file C# compiler takes at least one argument i.e., file

name Say your C# file name is myclass.cs then here is command line syntax

Trang 6

Now, lets take a look of your code line by line.

The first line of your program is using System

using System

Why using System? System is a namespace which stores system classes The Console class, I used in the program to display the output on the console is defined in the System namespace That's why this like is there.

Next line is class MyClass The class keyword in C# is used to create a new class

class MyClass {

}

Each class has one static void Main() function This function is the entry point of a C# program

static void Main() { Console.WriteLine("Hello, C# World!");

}

The WriteLine method of the Console class writes text to the console

Mahesh is Admin and the founder of C# Corner He has been programming in C++, MFC, Visual Basic, COM, ATL, Database Programming over 5 years More articles by Mahesh

contact: webmaster@c-sharpcorner.com copyright © 2000 c-sharpcorner.com All rights are reserved See terms and condition to use this site and its contents.

Sponsors: devexpress microgold apress

http://www.c-sharpcorner.com/Language/cs_lang_1.asp (2 of 2) [11/27/2001 7:19:47 PM]

Trang 7

C# Corner: C# and NET Developer's Network

Working with Data Types

First thing a programmer looks for is what kind of data types a programming languages has and how to use them In this part, I will cover C# data types and how to use them in a program

Basic Data Types

Most of the data type in c# are taken from C and C++ This tables lists data types, their description, and a sample example

string String type - sequence of Unicode characters string str = "Mahesh";

long val2 = 34L;

bool Boolean type; a bool value is either true or false bool val1 = true;bool val2 = false;

char Character type; a char value is a Unicode character char val = 'h';

byte val2 = 34U;

ushort val2 = 34U;

uint val2 = 34U;

ulong val2 = 34U;

ulong val3 = 56L;

ulong val4 = 78UL;

Value Types- Value type objects direct contain the actual data in a variables With value types, the

variables each have their own copy of the data, and it is not possible for operations on one to affect the other

int i = 10;

Reference Types- Reference type variables stores the reference of the actual data With reference types,

it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable

http://www.c-sharpcorner.com/Language/cs_lang_2.asp (1 of 2) [11/27/2001 7:20:02 PM]

Trang 8

MyClass cls1 = new MyClass();

Data Type ConversionsC# supports two types of conversions Implicit conversions and explicit conversions

Implicit conversions are direct conversion For example:

int iVal = 34;

long lVal = intValue;

Explicit conversions includes type casting conversion For example:

long lVal = 123456;

int iVal = (int) lVal;

Mahesh is Admin and the founder of C# Corner He has been programming in C++, MFC, Visual Basic, COM, ATL, Database Programming over 5 years More articles by Mahesh

contact: webmaster@c-sharpcorner.com copyright © 2000 c-sharpcorner.com All rights are reserved See terms and condition to use this site and its contents.

Sponsors: devexpress microgold apress

http://www.c-sharpcorner.com/Language/cs_lang_2.asp (2 of 2) [11/27/2001 7:20:02 PM]

Trang 9

C# Corner: C# and NET Developer's Network

This lesson shows how to use c# control statements, and the difference between these controls in c++/ JAVA and c#

The first selection statement is programmer’s favorite “if” statement It has three forms:

1 Single selection

2 if-then-else selection

3 multi-case selection List: 1 IfTest.cs

//understanding if statement

using System;

class IfTest {

public static void Main(){

string s;

int i;

Console.WriteLine("Enter a Number: ");

s = Console.ReadLine();

i = Int32.Parse(s);

//single selection

if(i > 0) Console.WriteLine("The number {0} is positive",i);

//if-then-else selection

if(i > 0) Console.WriteLine("The number {0} is positive",i);

else Console.WriteLine("The number {0} is not positive",i);

//multi-case selection

if(i == 0) Console.WriteLine("The number is zero");

else if(i > 0) Console.WriteLine("The number {0} is positive",i);

else Console.WriteLine("The number {0} is negative",i);

}}

This program reads a number from console Input coming from console is in string format Int32.parse(string) is used to convert string literal to integer

http://www.c-sharpcorner.com/Language/ControlStatements1.asp (1 of 6) [11/27/2001 7:20:30 PM]

Trang 10

The variable i is the object of evaluation here c++ programmers can see that the use of if statement is same in c# Halt it

There is one difference The expression in an if statement must resolve to bool value Take a look at following code.

list: 2

using System;

class IfTest2 {

public static void Main(){

if(1) Console.WriteLine("The if statement executed");

}}

when this code is complied by c# compiler, it will give the error “constant value 1 can not be converted to bool”.

conditional or ( || ) and conditional and ( && ) operators are used in the same manner Consider the following code

List: 3 LeapTest.cs

//Leap yearusing System;

class LeapTest {

public static void Main(){

int year;

Console.WriteLine("enter the year value (yyyy) :");

year = Int32.Parse(Console.ReadLine());

if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ) Console.WriteLine("The year {0} is leap year ",year);

else Console.WriteLine("The year {0} is not leap year ",year);

}}

public static void Main(){

int i = 1;

switch(i){

case 1 : Console.WriteLine("one");

break;

default : Console.WriteLine("default");

}

http://www.c-sharpcorner.com/Language/ControlStatements1.asp (2 of 6) [11/27/2001 7:20:30 PM]

Trang 11

C# Corner: C# and NET Developer's Network

}}

the difference here is if you try to compile above code without putting break statement in case 1, compiler will raise an

error “control can not fall through from one case label” I’m sure c++/Java programmers are going to love this Here is

another good news

The switch expression can evaluate to following types: sbyte, byte,short, ushort, int, uint, long, ulong, char, string or enum So the following code is perfectly OK with c# compiler.

List: 5 SwitchTest2.cs

using System;

class SwitchTest2 { public static void Main(){

string day;

Console.WriteLine("enter the day :");

day = Console.ReadLine();

switch(day){

case "Mon" : case "Monday" : Console.WriteLine("day is Monday: go to work");

break;

default : Console.WriteLine("default");

} }}

Control Statements – Loops

This lesson shows you how to use c# looping statements In c#, there are four iteration constructs rather than three There are familiar for, do, while loops and a new one from Visual basic, foreach

Let us start with while loop

The Do and While Statements

List: 1 WhileTest.cs

//find out the number of digits in a given number

using System;

class WhileTest {

public static void Main(){

int i = 123;

int count = 0;

int n = i;

//while loop may execute zero times

while(i > 0){

++count;

i = i/10;

http://www.c-sharpcorner.com/Language/ControlStatements1.asp (3 of 6) [11/27/2001 7:20:30 PM]

Trang 12

}

Console.WriteLine("Number {0} contains {1} digits.",n,count);

}}

The above code shows simple while loop, which finds out the number of digits in a number for a given number i = 123, the loop will execute tree times and hence the value of count will be three at the end of the while loop

The above code has one logical flaw If the number i is set to 0, the output of the code will be “Number 0 contains 0 digits.” Actually number 0 is of one digit Since the condition for the while loop i>0 is false from beginning for the value i=0, the while loop won’t execute any time and count will be zero here is a solution:

public static void Main(){

int i = 0;

int count = 0;

int n = i;

do{

++count;

i = i/10;

}while(i > 0);

Console.WriteLine("Number {0} contains {1} digits.",n,count);

}}

The Do-While construct checks condition in the end of the loop Thus Do-while loop will execute atleast once even though the condition to be checked is false from beginning

The For Statement

//For loop with break and continue statements

List: 3 Fortest.cs

using System;

class ForTest {

public static void Main(){

for(int i = 0 ; i < 20 ; ++i){

if(i == 10) break;

if(i == 5) continue;

Console.WriteLine(i);

} }

http://www.c-sharpcorner.com/Language/ControlStatements1.asp (4 of 6) [11/27/2001 7:20:30 PM]

Trang 13

C# Corner: C# and NET Developer's Network

The foreach statement

This statement allows to iterate over the elements in arrays and collections here is a simple example

List: 4 ForEach.cs

//foreach loop

using System;

class ForEach {

public static void Main(){

string[] a = {"Chirag","Bhargav","Tejas"};

foreach(string b in a) Console.WriteLine(b);

}

}

Within the foreach loop parenthesis , the expression is made up of two parts separated by keyword in The right hand side

of in is the collection and left hand side is the variable with type identifier matching to whatever type the collection returns

Every time the collection is queried for a new value As long as the collection returns value, the value is put into the variable and expression will return true when the collection is fully traversed, the expression will return false and control will be transferred to the next statement after a loop

http://www.c-sharpcorner.com/Language/ControlStatements1.asp (5 of 6) [11/27/2001 7:20:30 PM]

Trang 14

Sponsors: devexpress microgold apress

http://www.c-sharpcorner.com/Language/ControlStatements1.asp (6 of 6) [11/27/2001 7:20:30 PM]

Trang 15

C# Corner: C# and NET Developer's Network

Author: Amisha Mehta

Control Statements – Loops

This lesson shows you how to use c# looping statements In c#, there are four iteration constructs rather than three There

are familiar for, do, while loops and a new one from Visual basic, foreach.

Let us start with while loop

The Do and While Statements

List: 1 WhileTest.cs

//find out the number of digits in a given number

using System;

class WhileTest {

public static void Main(){

int i = 123;

int count = 0;

int n = i;

//while loop may execute zero times

while(i > 0){

++count;

i = i/10;

}

Console.WriteLine("Number {0} contains {1} digits.",n,count);

}}

The above code shows simple while loop, which finds out the number of digits in a number for a given number i = 123, the loop will execute tree times and hence the value of count will be three at the end of the while loop

The above code has one logical flaw If the number i is set to 0, the output of the code will be “Number 0 contains 0 digits.” Actually number 0 is of one digit Since the condition for the while loop i>0 is false from beginning for the value

i=0, the while loop won’t execute any time and count will be zero here is a solution:

List: 2 DoTest.cs

//find out the number of digits in a given number

using System;

class DoTest {

public static void Main(){

int i = 0;

int count = 0;

http://www.c-sharpcorner.com/Language/ControlStatements2.asp (1 of 3) [11/27/2001 7:20:44 PM]

Trang 16

++count;

i = i/10;

}while(i > 0);

Console.WriteLine("Number {0} contains {1} digits.",n,count);

}}

The Do-While construct checks condition in the end of the loop Thus Do-while loop will execute atleast once even though the condition to be checked is false from beginning

The For Statement

//For loop with break and continue statements

List: 3 Fortest.cs

using System;

class ForTest {

public static void Main(){

for(int i = 0 ; i < 20 ; ++i){

if(i == 10) break;

if(i == 5) continue;

Console.WriteLine(i);

} }}

The For loop is good when we know how many times the loop needs to be executed the output of the above code will be:

Trang 17

C# Corner: C# and NET Developer's Network

post loop action thus 5 is not part of the output when i becomes 10, control will break out of the loop

The foreach statement

This statement allows to iterate over the elements in arrays and collections here is a simple example

List: 4 ForEach.cs

//foreach loop

using System;

class ForEach {

public static void Main(){

string[] a = {"Chirag","Bhargav","Tejas"};

foreach(string b in a) Console.WriteLine(b);

}

}

Within the foreach loop parenthesis , the expression is made up of two parts separated by keyword in The right hand side

of in is the collection and left hand side is the variable with type identifier matching to whatever type the collection returns.

Every time the collection is queried for a new value As long as the collection returns value, the value is put into the variable and expression will return true when the collection is fully traversed, the expression will return false and control will be transferred to the next statement after a loop

Sponsors: devexpress microgold apress

http://www.c-sharpcorner.com/Language/ControlStatements2.asp (3 of 3) [11/27/2001 7:20:44 PM]

Trang 18

Learn C#: C# language's preprocessor directives

C# preprocessor is fundamentally very similar to C preprocessor and the whole concept in C# has been taken from C language specification

“The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation It is called a macro processor because it allows you to define macros,

which are brief abbreviations for longer constructs.”

But in C# only concept has been taken from C But the C# compiler does not have a separate preprocessor, the directives described in this C# are processed as if there was one Unlike C and C++ directives, you cannot use these directives to create macros

A preprocessor directive must be the only instruction on a line Preprocessing directives are lines in your program that start with `#' Whitespace is allowed before and after the `#' The `#' is followed by an

identifier that is the directive name For example, `#define' is the directive

The C# language's preprocessor directives are as follows

Main use of directives are

1 Conditional compilation Using special preprocessing directives, you can include or exclude parts

of the program according to various conditions

2 Line control If you use a program to combine or rearrange source files into an intermediate file,

which is then compiled, you can use line control to inform the compiler of where each source line originally came from

3 Error and Warning reporting: The directive `#error' causes the preprocessor to report a fatal

error and the directive `#warning' is like the directive `#error', but causes the preprocessor to issue a warning and continue preprocessing

Region and Unregion is new directives It was not in C and C++ list of directives I don’t know the intention of C# developers to excludes number of directive from C and C++ list but they picked what people use atmost from list of C and C++ directive Before telling meaning of each preprocessor directive I want to explain how to define preprocessor directive There are two method to define directive

1 Define in your C# program

http://www.c-sharpcorner.com/Language/PreprocessorDirectivesCS.asp (1 of 6) [11/27/2001 7:26:05 PM]

Trang 19

C# Corner: C# and NET Developer's Network

public class MyClass { public static void Main() {

#if (TEST) Console.WriteLine("TEST is defined");

#else Console.WriteLine("TEST is not defined");

#endif }}

#if (TEST) Console.WriteLine("TEST is defined");

#else Console.WriteLine("TEST is not defined");

#endif }}

At compile time user can define as below csc /define:TEST MyClass.java

Output

TEST is defined And if the command line will be like csc MyClass.java

Output TEST is not defined

Now its time to explain about various preprocessor define

#if directive

The `#if' directive in its simplest form consists of

http://www.c-sharpcorner.com/Language/PreprocessorDirectivesCS.asp (2 of 6) [11/27/2001 7:26:05 PM]

Trang 20

Above two example have shown how to use `#if` directive.

`#elif' directives within it have failed `#else' is equivalent to `#elif 1', and `#else' is allowed after any number of `#elif' directives, but `#elif' may not follow `#else'

Example

http://www.c-sharpcorner.com/Language/PreprocessorDirectivesCS.asp (3 of 6) [11/27/2001 7:26:05 PM]

Trang 21

C# Corner: C# and NET Developer's Network

#define DEBUG

#define VC_V6using System;

public class MyClass {

public static void Main() {

#if (DEBUG && !VC_V6) Console.WriteLine("DEBUG is defined");

#elif (!DEBUG && VC_V6) Console.WriteLine("VC_V6 is defined");

#elif (DEBUG && VC_V6) Console.WriteLine("DEBUG and VC_V6 are defined");

#else Console.WriteLine("DEBUG and VC_V6 are not defined");

#endif }}

public class MyClass {

public static void Main() {

#if DEBUG Console.WriteLine("DEBUG is defined");

#else Console.WriteLine("DEBUG is not defined");

#endif }}

Output

DEBUG is not defined

The `#error' and `#warning' Directives

The directive `#error' causes the preprocessor to report a fatal error The tokens forming the rest of the

line following `#error' are used as the error message

The directive `#warning' is like the directive `#error', but causes the preprocessor to issue a warning and

http://www.c-sharpcorner.com/Language/PreprocessorDirectivesCS.asp (4 of 6) [11/27/2001 7:26:05 PM]

Trang 22

continue preprocessing The tokens following `#warning' are used as the warning message.

Example 1

#define DEBUGpublic class MyClass {

public static void Main() {

#if DEBUG #error DEBUG is defined #endif

}}

Example 2

#define DEBUGpublic class MyClass {

public static void Main() {

#if DEBUG #warning DEBUG is defined #endif

}}

#region

#region lets you specify a block of code that you can expand or collapse when using the outlining feature

of the Visual Studio Code Editor

Example

#region MyClass definitionpublic class MyClass {

public static void Main() {

}}

#endregion

http://www.c-sharpcorner.com/Language/PreprocessorDirectivesCS.asp (5 of 6) [11/27/2001 7:26:05 PM]

Trang 23

C# Corner: C# and NET Developer's Network

#endregion

#endregion marks the end of a #region block

About the Author: Vivek K Gupta has done his MCA from REC Allahabad Having 6 year of rich experience on various techs

as C, JAVA ,EJB, UNIX, XML, Oracle and Web related technologies.Currently working on JAVA project and beginner for C# and NET Framework More about Vivek

contact: webmaster@c-sharpcorner.com copyright © 2000 c-sharpcorner.com All rights are reserved See terms and condition to use this site and its contents.

Sponsors: devexpress microgold apress

http://www.c-sharpcorner.com/Language/PreprocessorDirectivesCS.asp (6 of 6) [11/27/2001 7:26:05 PM]

Trang 24

I do not write only because I want to write I always try to present topics in easiest way so that beginner in C# could understand Vivek

Properties are accessor methods whose job it is to retrieve and set the values

of fields It provides a way to protect a field in a class by reading and writing and also support object-oriented concept of encapsulation In other language user can use this feature using getter and setter methods When user wants to wrap a value in attribute of an object or get the value from attribute of an object and when want to use attribute value It is always useful to use setter method to wrap value in attribute and getter method to retrieve value from attribute of an object Properties provide a level of abstraction to user

Most of object-oriented programmer used getter and setter method As in Java language user used accessor method as below

return age;

} public void setAge(int age) //set accessor method {

myAge = age;

} }

In main program user wants to use these set and get method to set and get person age They will use it as

PersonAge boyAge = new PersonAge(); //create instance of object boyAge.setAge(10); // set the age of boy by using setter method of object Syetm.out.println(“ Boy age is “+boyAge.getAge()); // get the age of boy by using

// getter method of object These setter and getter method was very useful in object-oriented world

In NET framework in C# these setter and getter method are presented under the heading properties Now in NET framework way of presentation of

properties is very smoother and useful to the programmer

http://www.c-sharpcorner.com/Language/PropertiesInCS.asp (1 of 5) [11/27/2001 7:36:17 PM]

Trang 25

C# Corner: C# and NET Developer's Network

return age;

} set //set accessor method {

age = value ; }

} }

So when in main program(C#) user wants to use these set and get method to set and get person age They will use it as

PersonAge boyAge = new PersonAge(); //create instance of object

boyAge humanAge = 10 ; // set the age of boy by using setter method of object

int bAge = boyAge humanAge ; // get the age of boy by // using getter method of object

Console.WriteLine(“ Boy age is {0}“+ bAge );

Class PersonAge is property holder class In which humanAge is property implementation I will try to explain about each line how it works.

value : In set method value variable is internal c# variable User no needs to

Now you may notice that the setter doesn't take any arguments The value

being passed is automatically placed in a variable named value that is

accessible inside the setter method

Some one may be wonder that when they are not passing any data for set methods how it works internally

I want also to show that how it internally works I used my favorite ILDASM.exe (Intermediate Language Disassembler) (Read my article to know more about ILDAM )

Run ILDASM.exe XXXX.exe on command prompt User will see output as below

http://www.c-sharpcorner.com/Language/PropertiesInCS.asp (2 of 5) [11/27/2001 7:36:17 PM]

Trang 26

Two classes one main and other property class are displayed (by symbol ) Click on first class user will see some two methods (by symbol )

get_humaneAge: int32 and set_humanAge:void(int32)

You can see the name of the accessor methods because the compiler prefixes

the property name with get_ (for a getter method) or set_ (for a setter

method) So code

boyAge humanAge = 10; is basically boyAge.set_humanAge(10) if you will click on set_ and get_ methods in ILDASM output you will get out put as

.method public hidebysig specialname instance int32

get_humanAge() il managed {

// Code size 11 (0xb)

maxstack 1 .locals (int32 V_0) IL_0000: ldarg.0 IL_0001: ldfld int32 PersonAge::age IL_0006: stloc.0

http://www.c-sharpcorner.com/Language/PropertiesInCS.asp (3 of 5) [11/27/2001 7:36:17 PM]

Trang 27

C# Corner: C# and NET Developer's Network

IL_0007: br.s IL_0009 IL_0009: ldloc.0

IL_000a: ret } // end of method PersonAge::get_humanAge

And

method public hidebysig specialname instance void

set_humanAge(int32 'value') il managed

{ // Code size 8 (0x8) .maxstack 8

IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32 PersonAge::age IL_0007: ret

} // end of method PersonAge::set_humanAge

I am not going to explain bit by bit of above code

WARNING: Never try to use get_ and set_ method of ILDASM output in your code

Compiler will generate error

If still you have some doubts about properties in your mind please mail me

About the Author: Vivek K Gupta has done his MCA from REC Allahabad Having 6 year of rich experience on various techs as C, JAVA ,EJB, UNIX, XML, Oracle and Web related technologies.Currently working on JAVA project and beginner for C# and NET Framework More about Vivek

contact: webmaster@c-sharpcorner.com copyright © 2000 c-sharpcorner.com All rights are reserved See terms and condition to use this site and its contents.

Sponsors: devexpress microgold apress

http://www.c-sharpcorner.com/Language/PropertiesInCS.asp (4 of 5) [11/27/2001 7:36:17 PM]

Trang 28

http://www.c-sharpcorner.com/Language/PropertiesInCS.asp (5 of 5) [11/27/2001 7:36:17 PM]

Trang 29

C# Corner: C# and NET Developer's Network

Author: Amisha Mehta

Exceptions in C# provide a structured, and type-safe way of handling both system level and application level error conditions The exception mechanism in C# is very similar to that of C++, with a few important differences

In C#, all exceptions must be represented by an instance of a class type derived from System.Exception

Causes of exceptions:

in certain circumstances when the operation cannot be completed normally For example, an integer division operation throws a System.DivideByZeroException if the denominator is zero

immediately following the throw

public static void Main(string[] args){

int i = 10/Int32.Parse(args[0]);

Console.WriteLine(i);

} }

Now when we run the above program like

test 5

It will print 2 on console

But suppose if we run it like

test or test hello

Then in that case program will crash We need to handle these situations by modifying our code

Exceptions are handled by try-catch statement

List: 2 Test2.cs

using System;

class Test{

http://www.c-sharpcorner.com/Language/ExceptionHandlingAM.asp (1 of 4) [11/27/2001 7:36:30 PM]

Trang 30

Now, when we run above program, there will be many possibilities

We run it like test 1212121212121212 In this case output will be a string

“Value was either too large or too small for an Int32”

So, there are four situations need to be handled Consider the following code:

List: 3 test3.cs

using System;

class Test3{

public static void Main(string[] args){

Console.WriteLine(e.Message);

} catch(DivideByZeroException e){

Console.WriteLine(e.Message);

} catch(OverflowException e){

Console.WriteLine(e.Message);

}} }

Four catch blocks are included in this code To make the program simple enough, all the catch blocks content is kept same

So depending upon the runtime situation, appropriate catch block will be executed

Consider the following code:

List: 4 Test4.cs

using System;

http://www.c-sharpcorner.com/Language/ExceptionHandlingAM.asp (2 of 4) [11/27/2001 7:36:30 PM]

Trang 31

C# Corner: C# and NET Developer's Network

class Test{

public static void Main(string[] args){

Console.WriteLine("This is finally block");

}} }

This is the example of try-catch-finally block The execution will be either entire try block and then finally block, or exception in try block – catch block – finally block Thus finally block will execute even if exception occurs or not

Common Exception Classes:

The following exceptions are thrown by certain C# operations

System.OutOfMemoryException Thrown when an attempt to allocate memory (via new) fails

System.StackOverflowException Thrown when the execution stack is exhausted by having too

many pending method calls; typically indicative of very deep

or unbounded recursion

System.NullReferenceException Thrown when a null reference is used in a way that causes

the referenced object to be required

System.TypeInitializationException Thrown when a static constructor throws an exception, and

no catch clauses exists to catch in

System.InvalidCastException Thrown when an explicit conversion from a base type or

interface to a derived types fails at run time

System.ArrayTypeMismatchException Thrown when a store into an array fails because the actual

type of the stored element is incompatible with the actual type of the array

System.IndexOutOfRangeException Thrown when an attempt to index an array via an index that

is less than zero or outside the bounds of the array

System.MulticastNotSupportedException Thrown when an attempt to combine two non-null delegates

fails, because the delegate type does not have a void return type

System.ArithmeticException A base class for exceptions that occur during arithmetic

operations, such as DivideByZeroException and OverflowException

System.DivideByZeroException Thrown when an attempt to divide an integral value by zero

Trang 32

About the Author: Amisha Mehta, currently working as Academic Head with STG,Ahmedabad

She has got experience in Microsoft web technology as well as Java and currently started working

on net technology More details

contact: webmaster@c-sharpcorner.com copyright © 2000 c-sharpcorner.com All rights are reserved See terms and condition to use this site and its contents.

Sponsors: devexpress microgold apress

http://www.c-sharpcorner.com/Language/ExceptionHandlingAM.asp (4 of 4) [11/27/2001 7:36:30 PM]

Trang 33

C# Corner: C# and NET Developer's Network

What & Why : Properties :: Part 1

if yo7u were programming in C or C++ before coming to C#, you'll be a little bit confused about properties

But Visual Basic programmers and Visual C++ programmers are familiar to this concept of Microsoft as a powerful tool

Well! I'll explain the concept of properties with some examples to make a clear understanding

So First of all: What are properties?

Just normal variables, like other primitive variables!

Example A:

////////// ExA.cs //////////////

namespace Rahul {

using System ; class Colors {

public static void Main() {

UrChoice UrColor = new UrChoice() ;

//Overwriting your favourite color to yellow UrColor.Color = "Yellow" ;

Console.WriteLine("Your favourite color is " + UrColor.Color) ; }

} public class UrChoice {

// Want to provide the access to everybody.

public string Color ;

// Default Constructor setting up your favourite color public UrChoice()

{

http://www.c-sharpcorner.com/Language/RSProperties.asp (1 of 5) [11/27/2001 7:36:49 PM]

Trang 34

} }

Compile the program as: csc ExA.cs Now type ExA and press enter (return) key

Output is: Your favorite color is Yellow

In Example 'A', I have declared two classes in Rahul namspace:

One is UrChoice (as the names are self explanatory) is talking about your choice, not all of your choices but here we are discussing about your favorite color and you have fixed your favorite color as “White” (Just for an instance) Now everybody is free to know about your favorite color and he can tell others about your choice But there is a problem!

Somebody has changed the value of your favorite color and now your favorite color is Yellow

Hey! That’s cheating!!!!

Yes! Of course but is there any way to protect your variable or your choice?

Here comes the turn of properties

Properties are like normal variables but with more power and flexibility

Now we convert the color variable in a property with the same name.

Example B:

////////// ExB.cs //////////////

namespace Rahul {

using System ; class Colors {

public static void Main() {

UrChoice UrColor = new UrChoice() ; //Overwriting your favourite color to yellow

UrColor.Color = "Yellow" ; Console.WriteLine("Your favourite color is " + UrColor.Color) ; }

}

http://www.c-sharpcorner.com/Language/RSProperties.asp (2 of 5) [11/27/2001 7:36:49 PM]

Trang 35

C# Corner: C# and NET Developer's Network

public class UrChoice {

// your private variable to store your favourite color private string MyColor ;

// Defining property, Want to provide the access to everybody

public string Color {

get{

return MyColor ; }

} // Default Constructor setting up your favourite color public UrChoice()

{ MyColor = "White" ; }

} }

This time we didn't define color variable as a normal variable rather we defined a property named Color

But in this case we had to define a new variable MyColor to store the initial and right value of your favorite color (also making it private to hide it from outside world)

This time when we try to compile our program as: csc ExB.cs

If we discuss the syntax of the property, this is really very easy

Decide a name to the property that can reflect its use and the Data Type of the property and start with the braces, Like in our example:

// Declaring its scope as public so that everybody can use it.

// Data Type is string public string Color {

http://www.c-sharpcorner.com/Language/RSProperties.asp (3 of 5) [11/27/2001 7:36:49 PM]

Trang 36

} Now put the value of the variable in the return statement of the get block, so that somebody can only get the value but can not write the value to the property In our example:

public string Color {

get { return MyColor ; }

} That’s it!!!

Can we do the same security of our data by some other means

Yes! I'll be discussing another method to do the same thing in the PART 2 of this series and also about the "set" block of a property, so that we can make a variable

in which everybody can write but can not read

Hey! This is not all about properties, there is a lot

Something more than this!

Will continue in PART 2

Rahul Sharma

Maxutil Softwares.

Maxutil Computer Skills.

B-43, Sector-B, Aliganj, Lucknow [INDIA]

Mail me at: rahul@maxutil.com http://www.maxutil.com

About the Author: Currently Rahul is working as NET Architect and Planning Director at "Maxutil Softwares" at Lucknow in INDIA and also promoting (providing the professional classes on NET technology with an Engineering Appraoch to computer educaion) the latest technology through

"Maxutil Computer Skills"(An computer education effort from Maxutil) I'm the First Green Card Holder in Germany (Brandenburg) and have worked for many companies in Germany.Writing two

http://www.c-sharpcorner.com/Language/RSProperties.asp (4 of 5) [11/27/2001 7:36:49 PM]

Trang 37

C# Corner: C# and NET Developer's Network

books right now for renouned publications

contact: webmaster@c-sharpcorner.com copyright © 2000 c-sharpcorner.com All rights are reserved See terms and condition to use this site and its contents.

Sponsors: devexpress microgold apress

http://www.c-sharpcorner.com/Language/RSProperties.asp (5 of 5) [11/27/2001 7:36:49 PM]

Trang 38

What & Why : Properties :: Part 2

In the part 1 of this series, sharpcorner.com/Language/RSProperties.asp, I discussed about the get method

http://www.c-of the properties, with the help http://www.c-of which you can make your variable so that nobody can modify the value of the variable This was really a great use of properties and win-win situation over normal variables

At the end of the part 1, I asked you about some another method to do the same thing (By which no body can change the value of your variable) and the solution is read only variables.

Read only variables are the variables, you can set the value of the variable once only and can not change it later and that is actually exactly what we want

Example C : /////////// ExC.cs ////////////

namespace Rahul {

using System ;

class Colors {

public static void Main() {

UrChoice UrColor = new UrChoice() ;

//Overwriting your favorite color to yellow UrColor.Color = "Yellow" ; // This line causes an error

http://www.c-sharpcorner.com/Language/RSProperties2.asp (1 of 10) [11/27/2001 7:37:02 PM]

Trang 39

C# Corner: C# and NET Developer's Network

public class UrChoice {

// Want to provide the access to everybody

public readonly string Color ;

// Default Constructor setting up your favorite color public UrChoice()

{ Color = "White" ; }

}

}

So when we try to compile this program as: csc ExC.cs

We get this error:

A readonly field can not be assigned to (except in a constructor or a variable initializer)

And the result is, that nobody can change the value of a readonly variable once this is set in the constructor (As we did in Example 'C') or when initializing at the time of declaration Now once you have set the value of your readonly variable, nobody can change it later in the program and if he does so he gets an error like

we got in our Example 'C' because we tried to change the value of readonly variable 'Color' to "Yellow" in Main method

Now remove the line

http://www.c-sharpcorner.com/Language/RSProperties2.asp (2 of 10) [11/27/2001 7:37:02 PM]

Trang 40

UrColor.Color = "Yellow" ; // This line causes an error From your C# code and again try to compile the program as: csc ExC.cs Program has been compiled successfully

Now run your program as: ExC (Press Enter Key) Output is: Your favorite color is White

Yes! Of course we got the right output

Now we'll discuss about the set method of the properties

What if I want a variable to allow everybody to modify it by his own value but can not read it

We are having a powerful tool to provide such strength to our normal variable and again the answer is property but this time we'll forget about the get method of the properties rather we'll use set method of the properties

As name suggests that get method of a property provides you the access to the value of the variable (you can read the value of the variable or can get the value) while set method provides you to modify the value of the variable (you can modify

or set the value of variable).

Example D:

////////// ExD.cs //////////////

namespace Rahul {

using System ;

class Colors {

public static void Main() {

http://www.c-sharpcorner.com/Language/RSProperties2.asp (3 of 10) [11/27/2001 7:37:02 PM]

Ngày đăng: 14/11/2012, 17:18

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w