Original source: http:
//
Www.codeguru.com/cs_syntax/csharp.html
Author: Aisha Ikram on some of the terms I try to make use of the environment consistent with the terms of the Chinese data on MSDN: .NET, C #, Win XP, Win
2000
Introduction C # is a language, with C
Features, like Java-like programming style, and like Basic's rapid development model. If you already know C
This article will allow you to quickly grasp the syntax of C # within an hour of time. Familiar with Java is better, because Java's program structure, packages and garbage collection concept help you know C # faster. So when I discuss the C # configuration, I will assume that you understand C.
. This article discusses the construction and characteristics of C # language, and uses a concise and you can understand some code examples. We will try to let you see these codes to understand these concepts. Note: This article is not written for the C # master (C # Gurus). This is a Chinese article on C # learning or initiator. Below is a directory of the C # issue to be discussed: Program Structure Name Space Data Type Variable Operator and Expression Enumeration Herald (STRUCTS) Modifiers Properties (Interfaces) Method parameters Arrays Indexer (Indexers) Packaging and Unpacking Operation Delegation (delegates) inheritance and polymorphism The following content will not be discussed: C
With C # Who is more common with type conversion exception handling .NET library, such as garbage recycling, thread, and file processing.
-------------------
Program structure
-------------------
This is like C
, C # is a language that is sensitive to uppercase letters, the semicolon ";" is a separator between statements. C
Different, C # Declare code files (header files) and implementation code files (CPP files) are not independently existing, all code (class declarations, and class implementations) are located in a file extension CS. Let us look at the Hello World program in C #.
Using
System;
Namespace
MyNamespace
{Class HelloWorld {static void main (string [] args) {console.writeline ("Hello World");}}}
Everything in C # is packaged into a class, and the class C # is encapsulated into a namespace (just like a file in a folder). Similar to C
The main method is the entry point of your program. C
Main function call name is
"
main
"
And the C # main function is the name of the uppercase letter M as the starting point.
"
Main
"
. There is no need to put the semicolon separator in the class sentence block or the structure definition. This is in c
It is required, but it is not in C #.
-------------------
Namespaces
-------------------
Each class is packaged into a namespace. Concept and C of Namespace
The same, but use the frequency of the namespace in C # more than C
Also high. You can access a class using a dot qulifier. In the top of the Hello World program, MyNameSpace is a namespace. Now think about this problem now, you want to access the HelloWorld this class how to operate from the namespace of some other classes. This has an example:
Using
System;
Namespace
Anothernamespace
{Class Anotherclass {public void func () {console.writeline ("Hello World");}}}
Now, from your HelloWorld class, you can access the namespace of this AnotherNameSpace this:
Using
System;
Using
Anothernamespace;
//
You will add this using stat
Namespace
MyNamespace
{Class HelloWorld {static void main (string [] args) {annotherclass obj = new anotherclass (); obj.func ();}}}
In the .NET library, System is located in the top layer named space, and other namespaces have this namespace. By default, there is a global namespace, so a class defined outside the namespace will directly under this global namespace; therefore, you can access this class without any point limiter. You can also define nested namespaces below. USING C
In the middle
"
#include
"
Indicates C #
"
Using
"
The keyword replaces, it follows the name of a named space. As
"
Using system
"
.
"
SYSTEM
"
It is other than all packaged namespaces and the most underlying namespaces in the class. The base class of all objects is derived from the Object class in the System namespace.
-------------------
variable
-------------------
In addition to the following, the variables in C # are almost c.
Same: with C
Different, the C # variable must be initialized before being accessed; otherwise it will be reported when compiling. Therefore, it is impossible to access a uninterected variable. You will not access an uncertain pointer in C #. (Translator Note: Strictly speaking C # has been synchronized by the pointer, limiting more stringent. Some information will say C # cancel the pointer concept) An expression that exceeds the array boundaries is irreparable. There is no global variable or global function in C #, the overall way is implemented by static functions and static variables.
-------------------
type of data
-------------------
All C # data types are derived from base class Object. Here are two types of data types: basic type
/
Built-in user-defined one of the following C # built-in type list: Type byte interpretation
Byte
1
No symbolic byte type
Sbyte
1
Signature byte type
Short
2
Symbolic short-character type
Ushort
2
No symbolic short-character type
int
4
Symbolic
Uint
4
No symbolic integer
Long
8
Have symbol length
Ulong
8
No symbolic long integer
Float
4
Floating point number
Double
8
Double precision
Decimal
8
Number of fixed precision
String
Unicode string type
charr
Unicode characters
Bool
True and false Boolean Note: C # Type range and C
Different; for example, C
The long type is 4 bytes, while in C # is 8 bytes. Similarly, the BOOL type and String are different from C.
. The BOOL type only accepts both of True and False. Do not accept any integer type. User-defined types include: class types (
Class
) structure type(
Struct
) Interface Type(
Interface
Data types of memory allocation forms are divided into two types: Value Types Reference Type: Value type data is assigned in the stack. They include: all basic or built-in types (excluding String types), structural types, enumerated types (
ENUM
TYPE) Reference Type: The reference type is allocated in the heap, which will be collected by garbage when they are no longer used. They use the New operator to create, in turn, there is no C
DELETE operators are different from C
It will explicitly use the delete operator to release this type of creation. In C #, these types are automatically collected by the garbage collector. The reference type includes: class type, interface type, set type type, string type, enumeration type enumeration type and C
The concept is very similar. They are all defined by an enum keyword. Example:
ENUM
Weekdays
{Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday}
Comparison of class types and structural types In addition to outside the memory allocation, the concept of class and structure is completely complete and c
the same. The objects of the class are allocated in the heap and create through New, but the structure is created by New but assigned in the stack. In C #, the structure is suitable for quick access and has a small number of data types. If there is more, you should create a class to implement him. (Translator Note: This is related to the characteristics of the allocation structure of the stack and the stack. In short, the stack is a sequential memory; the stack is not necessarily a continuous memory space. For details, you need to see the relevant information) :
Struct
Date
{Int day; int month; int year;
Class
Date
{Int day; int month; int year; string weekday; string monthName; public int GetDay () {return day;} public int GetMonth () {return month;} public int GetYear () {return year;} public void SetDay ( INT day {day = day;} public void setMonth (int month) {month = month;} public void setYear (int year) {year = year;} public bool isleApyear () {return (YEAR / 4 == 0) } Public void setdate (int day, int month, int year) {}} -------------------
Attributes
-------------------
If you are familiar with C
The way of an object object, you must have a concept of an attribute. In the example above, in C
In view of the point of view, the properties of the DATA class are DAY, MONTH and YEAR. With C # mode, you can write them into GET and SET methods. C # provides a more convenient, simple, direct way to access properties. Therefore, the above class can be written:
Using
System;
Class
Date
{Public int days;} set {day = value;}} int day; public int month {get {return month;} set {month = value;}} int year {Get {return Year;} set {year = value;}} int year; public bool isleApyear (int year) {return Year% 4 == 0? true: false;} public void setdate (int day, int month, int year) {THIS .day = day; this.month = month; this.year = year;}}
You can get and set these properties here:
Class
User
{Public static void main () {date date = new date (); Date.day = 27; Date.Month = 6; Date.Year = 2003; console.writeline ("Date: {0} / {1} / { 2} ", Date.day, Date.month, Date.year);}} -------------------
Modifier
-------------------
You must already know public,
Private
, Protected these often in c
The modifier used is used. Here I will discuss some new modifiers introduced by C #.
Readonly
(Read-only) Readonly modifiers are only used in data members of the class. As prompted by this name,
Readonly
Data members can only read only read only, they can only assign a value at a constructor or directly initialize operation. Readonly is different from the Const data member,
Const
Ask you to initialize in the statement, which is done. Look at the sample code below:
Class
Myclass
{Const Int constint = 100; // Direct initialization readonly int myint = 5; // Direct initialization readonly int myint2; // Translator Note: Only declaration, not initialization public myclass () {Myint2 = 8; // Indirect } Public func () {Myint = 7; // illegal operation (Translator Note: No value is double) console.writeline (Myint2.toString ());}}
SeaD
(Sealed) The sealing is not allowed to inherit, it is not derived. So you can use Sealed keywords for classes you don't want to be inherited.
SeaD
Class
Cannotbetheparent
{INT a = 5;}
Unsafe
(Not safe) You can use the unsafe modifier to define an unsafe context. In an unsafe context, you can write some c
Unsafe code such as pointer. Look at the sample code below:
public
Unsafe
Myfunction
int
*
PINT,
Double
*
PDOUBLE)
{INT * PANOTHERINT = New Int; * panotherint = 10; PINT = Panotherint; * PDOUBLE = 8.9;}
-------------------
Interface
(interface)
-------------------
If you have a COM concept, you will know what I want to talk about. An interface is an abstract base class, which only contains function description, and the implementation of these functions is done by subclasses. C # You have to use the interface keyword to define a class like an interface. .NET is based on such an interface. C # you do not support C
The allowable class multiple inheritance (translator Note: A derived class can be derived from two or more parent classes). But multi-inheritance can be obtained through an interface. That is to say that you can derive it from multiple interfaces.
Using
System;
Interface
MyDrawing
{Int Originx {get; set;} int originy {get; set;} void draw (Object shape);
Class
Shape: mydrawing
{Int Orix; Int Oriy; PUBLIC INTURN = Value;}} public int originy {get {return or = value;}} public void draw (Object Shape) {// do something} // Class's OWN Method Public Void MoveShape (int newx, int newy) {..}}
-------------------
Arrays (array)
-------------------
Array ratio C
The performance is better. The array is assigned in the heap and is therefore a reference type. You can't access elements that exceed a array boundary. Therefore, C # will prevent such a type of bug. Some auxiliary methods can cycle the function of accessing array elements in turn, and Foreach is such a statement. C
Compared to the characteristics of the C # in the array syntax: square brackets are placed behind the data type instead of the variable name. Creating an array element To use a New operator. C # supports one-dimensional, multi-dimensional and interleave arrays (arrays in arrays). Example:
int
Array
=
New
int
[
10
];
//
Integer one-dimensional array
for
(
int
i
=
0
I
<
Array.Length; i
Array [i]
=
i;
int
Array2
=
New
int
[
5
,
10
];
//
Integer 2D array
Array2 [
1
,
2
]
=
5
;
int
[,] Array3
=
New
int
[
5
,
10
,
5
];
//
Integer 3D array
Array3 [
0
,
2
,
4
]
=
9
;
int
[] ArrayofArray
=
=
New
int
[
2
];
//
Integer interlaced array (arrays in arrays)
ArrayofArray [
0
]
=
New
int
[
4
ArrayofArray [
0
]
=
New
int
[]
{1,2,15}
;
-------------------
Indexer
-------------------
The indexer is used to write a method of accessing a collection element, a collection
"
[]
"
This kind of direct way is similar to an array. What you have to do is to list an index list of access instances or elements. The type of property belt is an input parameter, and the indexer is the index table of the element, in addition to this, the same grammar of both. Example: Note: CollectionBase is a library class for making a collection. List is a Protected CollectionBase member, stores a list of collections.
Class
Shapes: CollectionBase
{Public Void Add (SHP) {List.Add (SHP);} // Indexer Public Shape this [int index] {get {return (shape) list [index];} set {list [index] = value; }
-------------------
Packing and unpacking operation (boxing
/
Unboxing
-------------------
C # packing ideas are brand new. The above mentioned all data types, whether it is built-in or user-defined, all from a base class Object from the namespace SYSTEM. Therefore, the basic or original type is converted to the Object type is called the box, in turn, the inverse operation of this method is called a split. Example:
Class
Test
{Static void main () {int myint = 12; object obj = myint; // box int myint2 = (int) obj; // unpack}}
The example shows the boxes and unpacking operations. A integer value is converted into an Object type and then converts back to the integer. When a value type variable needs to be converted into a reference type, an Object's box will be assigned a space that houses this value, which will be copied into this box. In contrast, the data in an Object box is converted into its original value type, this value will be copied from the box to the appropriate storage location.
English original:
Environment: .NET, C #, WIN XP, WIN
2000
Introduction C #
IS
A Language with the Features of C
, Programming Style Like Java, and The Rapid Application Model of Basic. If you already know the c
language, it will take you less than an hour to quickly go through the syntax of C #. Familiarity with Java will be a plus because the Java program structure, the concept of packages, and garbage collection will definitely help you learn C # more quickly. Sowhile
Discussing C # Language Constructs, I Will Assume That you know C
THIS ARTICLE DICUSS The C # Language Constructions and Features,
Using
Code Examples
in
A Brief and Comrehensive Way So That You Can, Just By Having a Glance At The Code, Understand The Concepts. Note: this article
IS
NOT
for
C # Gurus. There Must Be Some Other Beginner
'
S Articles On C #, But this is Yet Another One.
The following topics of the C # langauge are discussed: Program Structure Namespaces Data Types Variables Operators and Expressions Enumerations Statements Classes and Structs Modifiers Properties Interfaces Function Parameters Arrays Indexers Boxing and Unboxing Delegates Inheritance and Polymorphism The following topics are not discussed: Things that are common
in
C
And C # Concepts Such
AS
Garbage Collection, Threading, File Processing, and So Forth Data Type Conversions Exception Handling .NET LIBRARY Program Structure Like C
, C #
IS
Case
-
Sensitive. The semicolon,;
IS
The Statement Separator. Unlike C
, There Are No Separate Declaration (Header) And Implementation (CPP) FILES
in
C #. All Code
Class
Declarative and importation
IS
Placed
in
One File with a cs extention. Have a look at
THIS
Hello World Program
in
C #.
Using
System;
Namespace
MyNamespace
{Class HelloWorld {static void main (string [] args) {console.writeline ("Hello World");}}} everything
in
C #
IS
Packed Into a
Class
And classes
in
C # Are Packed INTO Namespaces (Just Like Files)
in
a folder. Like C
, A main method
IS
The Entry Point of Your Program. c
'
S main function is caled "main", WHEREAS C #
'
S Main Function Starts with a Capital M and
IS
Named
"
Main
"
There
IS
No Need to Put A SEMICOLON AFTER A
Class
Block OR
Struct
Definition. it was reguired
in
C
, But not
in
C #. Namespace Every
Class
IS
Packaged Into A
Namespace
. Namespaces Are EXACTLY The Same Concept
AS
in
C
, But
in
C # we use namespaces more frequently Than
in
C
YOU CAN Access A
Class
in
a
Namespace
Using
Dot. Qualifier. MyNamespace
IS
THE
Namespace
in
The Hello World Program Above. Now, Consider That you want to access the helloworld
Class
From Some Other
Class
in
Some Other
Namespace
.
Using
System;
Namespace
Anothernamespace
{Class Anotherclass {public void func () {console.writeline ("Hello World");}}}
Now, from your helloworld
Class
You can access it
AS
:
Using
System;
Using
Anothernamespace;
//
You will add this using stat
Namespace
MyNamespace
{Class HelloWorld {static void main (string [] args) {annotherclass obj = new anotherclass (); obj.func ();}}}
In The .NET Library, System
IS
THE TOP
-
Level
Namespace
in
Which other namespaces exist. by
DEFAULT
, There EXISTS A GLOBAL
Namespace
SO A
Class
Defined Outside Anamespace
Goes Directly Into
THIS
Global
Namespace
Hence, You CAN Access
THIS
Class
WITHOUT Any Qualifier. You can also define nested namespaces. Using the #include Directive
IS
Replaced with the
"
Using
"
Keyword, Which
IS
FOLLOWED BY A
Namespace
Name. JUST
AS
in
"
Using system
"
ABOVE.
"
SYSTEM
"
IS
THE
Base
-
Level
Namespace
in
Which All Other namespaces and classes are packed. The
Base
Class
for
all
Object
IS
Object
in
The system
Namespace
Variables variables
in
C # are almost the same
AS
in
C
, Except
for
THESE DIFFERENCES: VARIABLES
in
C # (Unlike C
Always Need To Be Initialized Before You Access Them; OtherWise, You Will
get
a Compile Time Error. Hence, IT
'
S Impossible to Access An Uninitialized Variable.
You can
'
T Access a .dangling. Pointer In C #.
An Expression That Indexes An Array Beyond ITS Bounds
IS
Also Not Accessible. There Are No Global Variables or Functions
in
C # and the behavior of globals
IS
Acheived through
Static
Functions and
Static
Variables. Data Types All Types of C # are deived from a
Base
-
Class
Object
. There is the Types of data type: Basic
/
BUILT
-
in
Types User
-
Defined Types Following
IS
A Table That Lists Built
-
in
C # types: type bytes desc
Byte
1
unsigned
Byte
Sbyte
1
Signed
Byte
Short
2
Signed
Short
Ushort
2
unsigned
Short
int
4
Signed integer
Uint
4
Unsigned integer
Long
8
Signed
Long
Ulong
8
unsigned
Long
Float
4
FLOATING POINT NUMBER
Double
8
Double
Precision Number
Decimal
8
Fixed
Precision Number
String
Unicode
String
charr
Unicode
charr
Bool
True,
False
Boolean Note: Type Range
in
C # and c
Are Different;
for
EXAMPLE,
Long
in
C
IS
4
Bytes, And
in
C # IT
IS
8
Bytes. Also, The
Bool
TYPE AND
String
Types Are Different THOSE
in
C
Bool Accepts ONLY
True
and
False
And not any integer. User
-
Defined Types Interface: Classes Structs Interfaces Memory Allocation of The Data Types Divides Theim Into Types: Value Types Reference Types Value Types Value Types Arection
in
The Stack. They Include: All Basic or Built
-
in
Types Except Strings Strus ENUM TYPES REFERENCE TYPE Reference Types area allocated on the heap and limited garbage collection. They area created
Using
THE
New
Operator
, And there
IS
No delete
Operator
for
Thase Types, Unlike
in
C
, WHERE TOEER HAS TO EXPLICITELY Delete the Types Created
Using
Delete
Operator
In C #, the Garbage Collector. Reference Types include: Classes Interfaces Collection Types Such
AS
Arrays String Enumeration Enumerations
in
C # are exactly like C
They area
ENUM
Keyword. EXAMPLE:
ENUM
Weekdays
{Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday}
Classes and structs classes and structs are same
AS
in
C
, Except
in
The Difference of Their Memory Allocation. Objects of Classes Are Allocated
in
The Heap, And Are Created
Using
New
WHERE
AS
Structs are allocated
in
The Stack. Structs
in
C # Are Very Light and fast datatypes. For Heavy DataTypes, You Should Create Classes. EXAMPLES:
Struct
Date
{Int day; int month; int year;} class
Date
{Int day; int month; int year; string weekday; string monthName; public int GetDay () {return day;} public int GetMonth () {return month;} public int GetYear () {return year;} public void SetDay ( INT day {day = day;} public void setMonth (int month) {month = month;} public void setYear (int year) {year = year;} public bool isleApyear () {return (YEAR / 4 == 0) } Public void setdate (int day, int month, int year) {}}
Properties if you familiar with the
Object
-
Oriented Way of C
YOU Must Have an IDEA of Properties. Properties. Properties. Properties. Properties. Properties
in
The Above Example of The Date
Class
Are Day, Month, And Year
for
Which
in
C
YOU WRITE GET AND SET METHODS. C # provides a More Convinient, Simple, And StraightForward Way of Accessing Properties. So, The Above
Class
Can Be Written
AS
:
Using
System;
Class
Date
{Public int days;} set {day = value;}} int day; public int month {get {return month;} set {month = value;}} int year {Get {return Year;} set {year = value;}} int year; public bool isleApyear (int year) {return Year% 4 == 0? true: false;} public void setdate (int day, int month, int year) {this .day = day; this.month = month; this.year = year;}} here
IS
The Way you Will
get
and
set
Thase Properties:
Class
User
{Public static void main () {date date = new date (); Date.day = 27; Date.Month = 6; Date.Year = 2003; console.writeline ("Date: {0} / {1} / { 2} ", Date.day, Date.month, Date.year);}}
Modifiers you must be aware of
public
,
Private
, And
protected
MODIFERS THAT ARE Commonly Used
in
C
I Will Discuss Some
New
Modifiers introducesd by c #.
Readonly
THE
Readonly
Modifier
IS
Used Only
for
THE
Class
Data MEMBERS. As the name indeicates, the name
Readonly
Data MEMBERS CAN ONLY Be Read Once The Written Either Directly Initializing Them or Assigning Values To Them
in
Constructor. The Difference Between THE
Readonly
and
Const
Data MEMBERS
IS
That
Const
Requires you to initialize with the declaration, That
IS
Directly. See
THIS
Example Code:
Class
Myclass
{Const Int constint = 100; // Directly Readonly Int Myint = 5; // Directly Readonly Int Myint2; Public MyClass () {Myint2 = 8; // Indirectly} Public Func () {Myint = 7; // Illegal console. WriteLine (Myint2.toString ());}} Sealed
THE
SeaD
Modifier with a
Class
Doesn
'
T Let You Deive Any Class from It. so, you use this seled keyword for the classes this you do
'
Twant to be inherited from.
SeaD
Class
Cannotbetheparent
{INT a = 5;}
Unsafe
You can define an
Unsafe
Context
in
C # by
Using
AN
Unsafe
MODIFIER. in the
Unsafe
Context, You Can Write an
Unsafe
CODE;
for
EXAMPLE, C
Pointers and So Forth. See The Following Code:
public
Unsafe
Myfunction
int
*
PINT,
Double
*
PDOUBLE)
{INT * PANOTHERINT = New Int; * panotherint = 10; PINT = Panotherint; * PDOUBLE = 8.9;}
Interfaces if you have an idea of the com, you will immediately know what i ammediately know.
Interface
IS
THE
Abstract
Base
Class
Containing Only the Function Signatures Whose Implementation
IS
Provided by the child
Class
In C #, You Define Such Classes
AS
Interfaces
Using
THE
Interface
Keyword. note
IS
Based on Such Interfaces. in C #, Where you can
'
T Use Multiple Class Inheritance, Which Was Previously Allowed In C , The Essence of Multiple Inheritance IS Acheived Through Interfaces. That
'
S how your child
Class
May IMPLEMENT MULTIPLE INTERFCES.
Using
System;
Interface
MyDrawing
{Int Originx {get; set;} int originy {get; set;} void draw (object shape);} Class
Shape: mydrawing
{Int Orix; Int Oriy; PUBLIC INTURN = Value;}} public int originy {get {return or = value;}} public void draw (Object Shape) {// do something} // Class's OWN Method Public Void MoveShape (int newx, int newy) {..}}
Arrays arrays
in
C # are much better Than
in
C
ARRAYS Are Allocated
in
The Heap and Thus are of the reference type. You CAN
'
t access an out-of-bound element in an array. So, C # prevents you from that type of bug. Also, some helper functions to iterate array elements are provided. foreach is the statement for such an iteration. The difference between the syntax of the c and c # Array IS:
The Square Brackets Are Placed After The Type and Not After The Variable Name. You create element location
Using
New
Operator
. C # Supports Single Dimensional, Multi Dimensional, And Jagged Array (Array of An Array). Examples:
int
Array
=
New
int
[
10
];
//
SINGLE-DIMENSIAL
//
Array of int
for
(
int
i
=
0
I
<
Array.Length; i
Array [i]
=
i;
int
Array2
=
New
int
[
5
,
10
];
//
2-Dimensional Array
//
Of int
Array2 [
1
,
2
]
=
5
;
int
[,] Array3
=
New
int
[
5
,
10
,
5
];
//
3-Dimensional Array
//
Of int
Array3 [
0
,
2
,
4
]
=
9
;
int
[] ArrayofArray
=
=
New
int
[
2
];
//
Jagged array -
//
Array of Array of ARRAY OF
//
int
ArrayofArray [
0
]
=
New
int
[
4
ArrayofArray [
0
]
=
New
int
[]
{1,2,15}
Indexers An Indexer
IS
Used to write a method to access an element from a collection
Using
The Straight Way of
Using
[], Like an array. All you need
IS
To Specify The Index to Access An Instance OR Element. The syntax of an indexer
IS
Same
AS
That of
Class
Properties, Except The Take The Input Parameter, That
IS
The index of the element. eXample: NOTE: CollectionBase
IS
THE LIBRARY
Class
Used
for
Making collections. List
IS
THE
protected
Member of CollectionBase, Which Stores The Collection List.
Class
Shapes: CollectionBase
{Public Void Add (SHP) {List.Add (SHP);} // Indexer Public Shape this [int index] {get {return (shape) list [index];} set {list [index] = value; }
Boxing
/
Unboxing the idea of boxing
IS
New
in
C #. As Mentioned Above, All Data Types, BUILT
-
in
OR user defined, Are Derived from A
Base
Class
Object
in
The system
Namespace
So, The Packing of Basic or Primitive Types Into AN
Object
IS
Called boxing, Whereas the reverse of
THIS
KNown
AS
Unboxing. EXAMPLE:
Class
Test
{Static void main () {int myint = 12; Object obj = myint; // boxing int myint2 = (int) obj; // unboxing}}
The Example Shows Both boxing and unboxing. AN
int
Value Can Be Converted to an AN
Object
And Back Again to an AN
int
. When a variable of a value type need needed to be converted to a reference type, an
Object
Boxis
Allocated to Hold The Value, and the value
IS
Copied Into the Box. Unboxing
IS
Just the oppositive. When An
Object
Box
IS
Cast Back to Its Original Value Type, The Value
IS
Copied
OUT
Function parameters parameters. Function Parameters Parameters
in
C # are of three type: by
-
Value
/
In Parameters by
-
Reference
/
In
-
Out parameters out pParameters if you have an idea of the COM
Interface
And ITS Parameters Types, You Will Easily UnderStand The C # parameter type. by
-
Value
/
In Parameters The Concept of Value Parameters
IS
The Same
AS
in
C
The value of the passed value
IS
Copied Into a location and
IS
Passed to the function. EXAMPLE: SETDAY
5
);
Void
Setday
int
DAY)
{.}
BY
-
Reference
/
In
-
Out Parameters the Reference Parameters
in
C
Are Passed Either Through Pointers Or A Reference
Operator
,
&
In C #, Reference Parameters Are Less Error Prone. Reference Parameters Are Also Called in
-
Out Parameters Because You Pass A Reference Address of The Location, So You Pass An Input Value and
get
An Output Value from That Function. You Cannot Pass An Uninitialized Reference Parameter Into A Function. C # Uses a Keyword
Ref
for
The Reference Parameters. You Also Have To Use Keyword
Ref
With an argument
While
Passing it to a function
-
Demanding Reference Parameter. EXAMPLE:
int
a
=
5
Functiona
Ref
a);
//
Use ref with argument or you Will
//
Get a Compiler Error
Console.writeline (a);
//
PRINTS 20
Void
Functiona (
Ref
int
VAL)
{INT x = Val; VAL = x * 4;}
Out parameter the out parameter
IS
The Parameter That Only Returns a value from the function. The Input valueis
NOT Required. c # Uses the keyword
OUT
for
THE
OUT
Parameters EXAMPLE:
int
Val; GetNodeValue (VAL);
Bool
GetNodeValue
OUT
int
VAL)
{Val = value; return true;}
Variable Number of Parameters and arrays arrays
in
C # Are Passed THROUGH a Keyword
Params
AN array
-
Type Parameter SHOULD Always Be The Right
-
Most Argument of The Function. Only One Parameter Can Be of The Array Type. You CAN Pass Any Number of Elements
AS
An Argument of Type of That Array. You Can Better Understand It From The Following Example. EXAMPLE:
Void
Func
Params
int
[] Array)
{Console.WriteLine ("Number of Elements {0}", array.length);}
Func ();
//
PRINTS 0
Func
5
);
//
PRINTS 1
Func
Seduce
,
9
);
//
PRINTS 2
Func
New
int
[]
{3, 8, 10}
);
//
PRINTS 3
int
Array
=
New
int
[
8
]
{1, 3, 4, 5, 5, 6, 7, 5}
Func (array);
//
PRINTS 8
Operators and Expressions Operators Are Exactly the Same
AS
OM C
And thus the expression, also. however, some
New
And useful operators have been added. Some of the present discussed here.
IS
Operator
THE
IS
Operator
IS
Used to Check WHETHER THE OPERAND TYPES Are Equal OR Convertable. The
IS
Operator
IS
Particularly useful
in
The Polymorphism Scenarios. The
IS
Operator
Takes Two Operands and The Result
IS
a boolean. See The Example:
Void
FUNCTION
Object
PARAM)
{IF (param is classa) // do something else if (param is mystruct) // do something}
}
AS
Operator
THE
AS
Operator
Checks WHether The Type of the Operands Are Convertable or Equal
AS
IS
Done by
IS
Operator
) And
IF
IT
IS
, The result
IS
a converted or boxed
Object
(
IF
The Operand Can Be Boxed Into The Target Type, See Boxing
/
UNBOXING). IF The Objects Are Not Convertable OR Boxable, THE
Return
IS
a
NULL
. Have a look at the example below to better understand the concept. Shape SHP
=
New
Shape (); Vehicle Veh
=
SHP
AS
Vehicle;
//
Result is Null, Types Are Not
//
Convertable
Circle Cir
=
New
Circle (); Shape SHP
=
Cir; Circle Cir2
=
SHP
AS
Circle;
//
Will Be Converted
Object
[] Objects
=
New
Object
[
2
]; OBJECTS [
0
]
=
"
Aisha
"
;
Object
[
1
]
=
New
Shape ();
String
Str;
for
(
int
i
=
0
I
& <
Objects.length; i
)
{Str = Objects [i] as string; if (str == null) Console.writeline ("can not be conveilted"); Else Console.writeline ("{0}", str);}
Output: Aisha Can Not Be Converted Statements Statements
in
C # arejust Like
in
C
Except Some Additions of
New
Statements and modifications
in
Some Statements. The Following Are
New
STATEMENTS:
Foreach
For ity of collections, such
AS
Arrays, And So Forth. EXAMPLE:
Foreach
(
String
s
in
Array) Console.WriteLine (s);
LOCK
Used
in
Threads
for
Locking a block of code, Making it a critical section.
Checked
/
unchecked
The Statements Are
for
Overflow Checking
in
Numeric Operations. EXAMPLE:
int
x
=
INT32.MaxValue; x
;
//
Overflow checked
{x ; // Exception}
unchecked
{x ; // overflow}}
The Following Statements Are Modified: Switch The Switch Statementis
Modified
in
C #. Now, after Executing A
Case
Statement, Program Flow Cannot Jump to the next
Case
, Which Was Previously Allowed
in
C
EXAMPLE:
int
VAR
=
100
;
Switch
(var)
{CASE 100: console.writeline ("
OUTPUT
in
C
:
<
Value
IS
100
> <
Value
IS
200
>
IN C #, you
get
A Compile Time error: Error CS0163: Control Cannot Fall THROUGH FROM ONE
Case
Label
'
Case 100:
'
) To Another howare, you can
DO
THIS
Similarly to the Way you
DO
IT
in
C
:
Switch
(var)
{CASE 100: Case 200: Console.WriteLine ("100 or 200
You Also Can Use Constant Variables
for
Case
VALUES: EXAMPLE:
Const
String
WEEKEND
=
"
Sunday
"
;
Const
String
Weekday1
=
"
Monday
"
;.
String
Weekday
=
Console.readline ();
Switch
(Weekday)
{Case Weekend: Console.writeline ("It's Weekend !!"); Break; Case Weekday1: Console.writeline ("It's Monday"; Break;}
Delegates delegates let us store function references Into a variable. In c
,
THIS
IS
Like
Using
And Storing a Function Pointer
for
Which we uasnelly use typef. delegates Are Declared
Using
A Keyword
Delegate
Have a look at
THIS
Example, and you will understand what delegates Are: Example:
Delegate
int
Operation
int
VAL1,
int
VAL2);
public
int
Add (
int
VAL1,
int
VAL2)
{RETURN VAL1 VAL2;}
public
int
Subtract
VAL1,
int
VAL2)
{RETURN VAL1- VAL2;}
public
Void
Perform ()
{Operation Oper; "ENTER OR -"); string Optor = console.readline (); console.writeline ("Enter 2 Operands"); string opnd1 = console.readline (); string opnd2 = console. Readline (); Int Val1 = Convert.TOINT32 (OPND1); INT VAL2 = Convert.Toint 32 (OPND2); if (Optor == " ") Oper = new operation (add); else Oper = new operation (subtract); Console.writeline ("Result = {0}", Oper (VAL1, VAL2));
Inheritance and Polymorphism ONLY SINGLE inheritance
IS
allowed
in
C #. Mutiple inheritance can becomheived by
Using
Interfaces. EXAMPLE:
Class
Parent
{}
Class
Child: Parent Virtual Functions Virtual Functions Implement The Concept of Polymorphism Are The Same
AS
in
C #, Except That you use the the
Override
Keyword with the
Virtual
Function Implementaion
in
THE CHILD
Class
THE PARENT
Class
Uses the same
Virtual
Keyword. EVERY
Class
That Overrides the
Virtual
Method Will Use the
Override
KEYWORD.
Class
Shape
{Public Virtual Void Draw () {Console.writeline ("Shape.Draw");}}
Class
Rectangle: Shape
{Public override void draw () {console.writeLine ("Rectangle.Draw");}}
Class
Square: Rectangle
{Public override void draw () {console.writeLine ("Square.Draw");}}
Class
Mainclass
{Static void main (string [] args) {shape [] shp = new shape [3]; Rectangle Rect = new Rectangle (); SHP [0] = new shape (); SHP [1] = Rect; SHP [2 ] = New square (); SHP [0] .draw (); SHP [1] .draw (); SHP [2] .draw ();}} Output: Shape.Draw Rectangle.draw Square.draw Hiding Parent Functions
Using
"
New
"
You can define
in
a child
Class
a
New
Version of a function, Hiding the one which
IS
in
Base
Class
. A
New
Keyword
IS
Used to define a
New
Version. Consider the Example Below, Which
IS
A Modified Version of the Above Example and Note The Output
THIS
Time, When I Replace the
Override
Keyword with a
New
Keyword
in
The Rectangle
Class
.
Class
Shape
{Public Virtual Void Draw () {Console.writeline ("Shape.Draw");}}
Class
Rectangle: Shape
{Public new void draw () {console.writeLine ("Rectangle.DRAW");}}
Class
Square: Rectangle
{// Wouldn't let you override it here public new void draw () {console.writeline ("Square.Draw");}}
Class
Mainclass
{Static void main (String [] args) {Console.writeline ("Using Polymorphism:"); Shape [] SHP = New Shape [3]; Rectangle Rect = New Rectangle (); SHP [0] = New Shape () ; SHP [1] = Rect; SHP [2] = new Square (); SHP [0] .draw (); SHP [1] .draw (); SHP [2] .draw (); console.writeline Using wely Polymorphism: "); Rect.draw (); Square sqr = new Square (); sqr.draw ();}}
Output: Using Polymorphism Shape.draw Shape.draw Shape.draw Using With Polymorphism: Rectangle.draw Square.draw The Polymorphism Doesn '
T Take the Rectangle Class
'
S Draw Method
AS
a polymorphic form of the shape
'
. So, To avoid the name.
Note: you cannot Use the Two Version of a Method
in
The Same
Class
ONE WITH
New
Modifier and other with
Override
oral
Virtual
AS
in
The Above Example, I Cannot ADD ANOTHOD NAMED DRAW
in
The Rectangle
Class
Which
IS
a
Virtual
oral
Override
Method. Also,
in
The Square
Class
, I can
'
T Override The Virtual Draw Method of The Shape Class.
Calling
Base
Class
MEMBERS IF THE CHILD
Class
Has the data members with same name
AS
That of
Base
Class
, To avoid naming conflicts,
Base
Class
Data MEMBERS AND FUNCTIONS ARE Accessed
Using
A Keyword
Base
See. See.
in
The Examples How The of THE
Base
Class
Constructors Are Called and how the data members are.
public
CHILD
int
VAL):
Base
(VAL)
{Myvar = 5; base.myvar;
Oral
public
CHILD
int
VAL)
{Base (val); myvar = 5; base.myvar;}
FUTURE Additions: this Article
IS
Just A Quick Overwiew of the C # language so that you can Just Become Familiar with the langauge features. Althiuary i Have Tried to Discuss Almost All The Major Concepts
in
C #
in
A Brief and Comprehensive Way with Code Examples, I Think There
IS
lot much to be added and discussed. In the future, I would like to add more commands and concepts not yet discussed including events and so forth. I would also like to write about Windows programmingusing
C #
for
Beginners Our Most Commonly Known Msdn Inside C # by Tom Archer a Programmer
'
S Introduction to C # by Eric Gunnerson
Beginning C # by Karli Watson Programming C # (O O
'
REILLY)
About The Author Aisha
IS
a master of science
in
Computer science from quaid
-
i
-
Azam universty. She has worked
in
VC
6
, MFC, ATL, COM
/
DCOM, ActiveX, C
, SQL, AND SO FORTH. THESE DAYS SHE
IS
Working on .NET Framework and C #. INSPIRED with Nature, She Loves to Seek Knowledge. SHE
IS
Also fond of travelling. Sheeps a free source code and articles Web site at http:
//
Aishai.netFirms.com.