C # Quick C #)

Source: Internet
Author: User
Tags uppercase letter

Title: C # Quick C #)
Original Author: Aisha Ikram
Translation: bigqiang
Website: http://www.fazhuan.com/
Mailbox: bigqiang@sina.com
--------------------------------------------------------------------------------

Environment:. net, C #, Win XP, Win 2000

Introduction

C # is such a language with C ++ features, the same programming style as Java, and the same rapid development model as basic. If you already know C ++, this article will give you a quick grasp of C # syntax in less than an hour. It is better to be familiar with Java, because the Java program structure, packages, and garbage collection concepts help you get to know C # Faster #. Therefore, when discussing the construction of C #, I will assume that you understand C ++.

This article will discuss the structure and features of the C # language, and use some code examples in a concise and understandable way, we will try to help you understand these concepts by looking at the code.

Note: This article is not written by C # guru (C # gurus). It is for C # learning or beginners.

The following is the directory of the C # question to be discussed:

Program Structure
Namespace
Data Type
Variable
Operators and expressions
Enumeration
Statement (statements)
Class and Structure)
Modifiers)
Properties)
Interface (interfaces)
Function Parameters)
Array (arrays)
Indexers)
Packing and unpacking
Delegate)
Inheritance and Polymorphism

The following content will not be discussed:

C ++ and C # Who is more common
Concepts such as garbage collection, threads, and file processing
Data Type Conversion
Exception Handling
. Net Library

-------------------
Program Structure
-------------------
This is similar to C ++. C # is a language that is sensitive to uppercase and lowercase letters. A semicolon (;) is a separator between statements. Different from C ++, the declaration code file (header file) and implementation code file (CPP file) in C # do not exist independently. All code (class declaration and class implementation) all are located in a file with the extension of CS.

Let's take a 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 encapsulated into a class, and the C # class is encapsulated into a namespace (like a file in a folder ). Similar to C ++, the main method is the entry point of your program. The main function call name of C ++ is "Main", while the main function of C # starts with the uppercase letter M and is "Main ".

There is no need to place the semicolon separator after the class statement block or Structure Definition Statement block. This is required in C ++, but not in C.

-------------------
Namespace
-------------------
Each class is packaged into a namespace. The concept of a namespace is exactly the same as that of C ++, but the frequency of using a namespace in C # is higher than that in C ++. You can use the dot qulifier to access a class. In the above Hello World Program, mynamespace is a namespace.

Now let's think about how to access the helloworld class from some namespaces of other classes.
Here is 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 the above anothernamespace as follows:

Using system;
Using anothernamespace; // you will add this using statement
Namespace mynamespace
{
Class helloworld
{
Static void main (string [] ARGs)
{
Anotherclass OBJ = new anotherclass ();
OBJ. func ();
}
}
}

In the. NET library, system is the top-level namespace, and Other Namespaces exist under this namespace. By default, a global namespace exists. Therefore, a class defined outside the namespace is directly under this global namespace. Therefore, you can access this class without any vertices or delimiters.

You can also define nested namespaces as follows.

Using
The "# include" indicator in C ++ is replaced by the "using" keyword of C #, followed by the namespace name. As shown in the preceding "using system ". "System" is the lowest-level namespace in all other encapsulated namespaces and classes. The base classes of all objects are derived from the object classes in the system namespace.

-------------------
Variable
-------------------
Except for the following, the variables in C # are almost the same as those in C ++:

Unlike C ++, C # variables must be initialized before being accessed; otherwise, an error will be reported during compilation. Therefore, it is impossible to access an uninitialized variable.
In C #, You won't access an uncertain pointer. (Note: strictly speaking, C # has made the pointer concept more restrictive. So C # removes the pointer concept in some documents)
An expression that exceeds the array boundary is not accessible.
C # does not have global variables or global functions. Global operations are implemented through static functions and static variables.

-------------------
Data Type
-------------------
All C # data types are derived from base class objects. There are two types of data:

Basic/internal user-defined

The following is a list of C # built-in types:

Description of Type bytes
Byte 1 unsigned byte type
Sbyte 1 signed byte type
Short 2 signed short byte type
Ushort 2 unsigned short byte type
Int 4 signed integer
Uint 4 unsigned integer
Long 8 signed long integer
Ulong 8 unsigned long integer
Float 4 floating point number
Double 8 Double Precision
Decimal 8 fixed precision
String Unicode string type
Char Unicode Character Type
Boolean true/false

Note: The type range in C # is different from that in C ++. For example, the long type in C ++ is 4 bytes, and the long type in C # is 8 bytes. Similarly, both bool and string types are different from C ++. The bool type only accepts true and false values. It does not accept any integer type.

User-Defined types include:

Class)
Structure Type (struct)
Interface)

The memory allocation modes of data types are divided into two types:

Value types)
Reference types)

Value Type:
Value Type data is allocated in the stack. They include: all basic or built-in types (excluding the string type), structure type, enumeration type (Enum type)

Reference Type:
The reference types are allocated in the heap. They are collected as garbage when they are no longer used. They are created using the new operator. For these types, the delete operator in C ++ does not exist, different from C ++, C ++ explicitly uses the delete operator to release the created type. In C #, these types are automatically collected and processed through the garbage collector.

The reference types include: class type, interface type, collection type such as array, string type, and enumeration type.

Enumeration types are similar to those in C ++. They are all defined by an Enum keyword.

Example:

Enum weekdays
{
Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
}

Comparison between class types and Structure Types
In addition to memory allocation, classes and structures have the same concept as C ++. Class objects are allocated to the stack and created through new. The structure is also created by new but allocated to the stack. In C #, the structure is suitable for fast access and data types with a small number of members. If there are more involved, you should create a class to implement it.
Note: This is related to the features of the heap and stack memory allocation structure. In short, stack is a memory allocated sequentially; heap is not necessarily a continuous memory space. For details, refer to relevant materials)

Example:

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)
{
}
...
}

-------------------
Attribute
-------------------
If you are familiar with the c ++ face object method, you must have an attribute concept. In the above example, from the perspective of C ++, the attributes of the Data class are day, month, and year. In C # mode, you can write them as get and set methods. C # provides a more convenient, simple, and direct way to access attributes.

Therefore, the above class can be written as follows:

Using system;
Class date
{
Public int day {
Get {
Return day;
}
Set {
Day = value;
}
}
Int Day;

Public int month {
Get {
Return month;
}
Set {
Month = value;
}
}
Int month;

Public 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 obtain and set these attributes here:

Class user
{
Public static void main ()
{
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, and protected modifiers that are often used in C ++. Here I will discuss some new modifiers introduced by C.

Readonly (read-only)
The readonly modifier is only used by data members of the class. As prompted by this name, readonly data members can only be read-only. They can only be assigned a value once in the constructor or in the direct initialization operation. Unlike the const data member, readonly requires that you initialize the data in the Declaration. This is done directly. See the following sample code:

Class myclass
{
Const int constint = 100; // initialize directly
Readonly int Myint = 5; // directly initialize
Readonly int myint2; // Translator's note: only declarations are made and Initialization is not made.

Public myclass ()
{
Myint2 = 8; // indirect
}
Public func ()
{
Myint = 7; // illegal operation (Note: no value is assigned twice)
Console. writeline (myint2.tostring ());
}

}

Sealed (sealed)
The sealed class does not allow any class inheritance. It does not have a derived class. Therefore, you can use the sealed keyword for the class you do not want to inherit.

Sealed class cannotbetheparent
{
Int A = 5;
}

Unsafe)
You can use the unsafe modifier to define an insecure context. In an insecure context, you can write Insecure code such as C ++ pointers. See the following sample code:

Public unsafe myfunction (int * pint, double * pdouble)
{
Int * panotherint = new int;
* Panotherint = 10;
Pint = panotherint;
...
* Pdouble = 8.9;
}

-------------------
Interface)
-------------------

If you have the concept of COM, you will understand what I want to talk about. An interface is an abstract base class. This base class only contains function descriptions, and the implementation of these functions is completed by sub-classes. In C #, you must use the interface keyword to define a class like an interface .. Net is based on this interface. C # does not support multi-class inheritance allowed by C ++ (Note: A derived class can be derived from two or more parent classes ). However, multiple inheritance methods can be obtained through interfaces. That is to say, one of your sub-classes can be derived from multiple interfaces for implementation.

Using system;
Interface mydrawing
{
Int originx
{
Get;
Set;
}
Int originy
{
Get;
Set;
}
Void draw (Object Shape );
}

Class shape: mydrawing
{
Int orix;
Int oriy;

Public int originx
{
Get {
Return orix;
}
Set {
Orix = value;
}
}
Public int originy
{
Get {
Return oriy;
}
Set {
Oriy = value;
}
}
Public void draw (Object Shape)
{
... // Do something
}

// Class's own Method
Public void moveshape (INT newx, int newy)
{
.....
}

}

-------------------
Arrays (array)
-------------------

Arrays in C # are better than those in C ++. The array is allocated in the heap, so it is a reference type. You cannot access elements that exceed an array boundary. Therefore, C # will prevent such bugs. Some auxiliary methods can access array elements cyclically and sequentially. foreach is such a statement. Compared with C ++, C # has the following array syntax features:

Square brackets are placed after the data type rather than after the variable name.
To create an array element, use the new operator.
C # supports one-dimensional, multi-dimensional, and staggered arrays (arrays in arrays ).

Example:

Int [] array = new int [10]; // One-dimensional integer Array
For (INT I = 0; I <array. length; I ++)
Array [I] = I;

Int [,] array2 = new int [5, 10]; // a two-dimensional integer Array
Array2 [1, 2] = 5;

Int [,] array3 = new int [, 5]; // a three-dimensional array of integer types.
Array3 [0, 2, 4] = 9;

Int [] [] arrayofarray = new int [2]; // an integer staggered array (array in the array)
Arrayofarray [0] = new int [4];
Arrayofarray [0] = new int [] {1, 2, 15 };

-------------------
Indexer
-------------------

The indexer is used to write a method to access the collection elements. The set uses a direct method like "[]", similar to an array. All you need to do is to list the indexes of access instances or elements. The attribute of the class carries the input parameter, while the indexer carries the index table of the element. In addition, they have the same syntax.

Example:

Note: collectionbase is a library class used to create a collection. List is a protected collectionbase member that stores the list of collections.
Class shapes: collectionbase
{
Public void add (shape SHP)
{
List. Add (SHP );
}

// Indexer
Public shape this [int Index]
{
Get {
Return (SHAPE) list [Index];
}
Set {
List [Index] = value;
}
}
}

-------------------
Boxing and unpacking (Boxing/unboxing)
-------------------

The C # Packing idea is brand new. All data types mentioned above, whether built-in or user-defined, are derived from a base class Object of the namespace system. Therefore, converting the basic or original type to the object type is called as packing. Otherwise, this type of inverse operation is called unpacking.

Example:

Class Test
{
Static void main ()
{
Int Myint = 12;
Object OBJ = Myint; // boxed
Int myint2 = (INT) OBJ; // unpack
}
}

The example shows the packing and unpacking operations. An integer value is converted to the object type, and then converted back to the integer type. When a variable of the value type needs to be converted to the reference type, the box of an object will be allocated space to hold the value, and the value will be copied into the box. In contrast, when data in an object box is converted to its original value type, this value is copied from the box to the appropriate storage location.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.