C # is a simple, modern, object oriented, and Type-safe programming language derived from C and C + +. C # (pronounced "C sharp") is firmly planted in the C and C + + family tree of languages, and would immediately be familiar to C and C + + programmers. C # aims to combine the productivity of Visual Basic and the raw power of C + +.
C # is provided as a of Microsoft Visual Studio 7.0. In addition to C #, visual Studio supports visual Basic, Visual C + +, and the scripting languages VBScript and JScript. All of this languages provide access to the Next Generation Windows Services (NWGS) platform, which includes a common EXE Cution engine and a rich class library. The. NET Software Development Kit defines a "Common Language subset" (CLS), a sort of lingua franca that ensures Interoperability between Cls-compliant languages and class libraries. For C # Developers, this means that even though C # is-a new language, it has complete access to the same rich class Librari Es that are used by seasoned tools such as visual Basic and Visual C + +. C # itself does not include a class library.
The rest of this chapter describes the essential features of the language. While later chapters describe the rules and exceptions in a detail-oriented and sometimes mathematical manner, this chapter St Rives for clarity and brevity at the expense of completeness. The intent is to provide the reader with a introduction to the language that would facilitate the writing of early program S and the reading of later chapters.
1.1 Hello, World
The canonical "Hello, World" program can is written in C # as follows:
Using System;
Class Hello
{
static void Main () {
Console.WriteLine ("Hello, World");
}
}
The default file extension for C # programs. CS, as in Hello.cs. Such A program can is compiled with the command line directive
csc Hello.cs
which produces a executable program named Hello.exe. The output of the program is:
Hello, World
Close examination the "This" is illuminating:
the using System; Directive references a namespace called System that's provided by the. NET Runtime. This is namespace contains the Console class referred to in the Main method. Namespaces provide a hierarchical means of organizing the elements of a class library. A "using" directive enables unqualified use to the members of a namespace. The "Hello, World" program uses Console.WriteLine as a shorthand for System.Console.WriteLine. What do these identifiers denote? System is a namespace, the Console is a class defined in that namespace, and WriteLine are a static method to defined on that Clas S.
the Main function is a static member of the class Hello. Functions and variables are not supported at the global level; Such elements are always contained within type declarations (e.g., class and struct).
the "Hello, World" output is produced through the use of a class library. C # does not itself provide a class library. Instead, C # uses a common class library is also used to other languages as visual Basic and Visual C + +.
For C and C + + developers, it is interesting to note a few things.
the program does not use either "::" or "->" operators. The ':: ' is ' is ' operator in C #, and the '-> ' operator is used into only a small fraction of C # programs. C # programs use '. ' As a separator in compound names such as Console.WriteLine.
the program does is not contain forward declarations. Forward declarations are never needed in C # programs, as declaration order are not significant.
the program does the not with #include to import program text. Dependencies between programs are handled symbolically rather with program text. This is the system eliminates barriers between programs written in different languages. For example, the Console class could is written in C # or in some other language.
1.2 Automatic Memory Management
Manual memory management requires developers to manage the allocation and de-allocation of blocks. Manual memory management is both time consuming and difficult. C # provides automatic memory management so, developers are from the this freed task. In the vast majority of cases, this automatic memory management increases code quality and enhances developer Without negatively impacting either expressiveness or performance.
The example
Using System;
public class Stack
{
Private Node-i = null;
public bool Empty {
get {
return (a = null);
}
}
public Object Pop () {
if (i = null)
throw new Exception ("Can" t Pop from a empty Stack. ");
else {
Object temp = i. Value;
A. Next;
return temp;
}
}
public void Push (object o) {
The new Node (O, a)
}
Class Node
{
Public Node Next;
public object Value;
Public Node (object value): This (value, null) {}
Public node (object value, Node next) {
Next = next;
Value = value;
}
}
}
Shows a Stack class implemented as a linked list of Node instances. Node instances are created in the Push method and are garbage collected when no longer needed. A Node instance becomes eligible for garbage collection as it is no longer possible for any code to access it. For instance, when a item is removed from the Stack, the associated Node instance becomes eligible for garbage .
The example
Class Test
{
static void Main () {
Stack s = new stack ();
for (int i = 0; i < i++)
S.push (i);
while (!s.empty)
Console.WriteLine (S.pop ());
}
}
Shows a test program that uses the Stack class. A Stack is created and initialized with elements, and then assigned the value NULL. Once the variable s is assigned null, the Stack and the associated Node instances become eligible for garbage N. The garbage collector is permitted to clean up immediately, and but is isn't required to does so.
For developers who are generally content with automatic memory management but sometimes need fine-grained control or Extra iota of performance, C # provides the ability to write "unsafe" code. Such code can deal directly with pointer types, and fix objects to temporarily prevent the garbage collector from moving t Hem. This ' unsafe ' code feature is in fact ' safe ' feature from the perspective of both and users. Unsafe code must is clearly marked in the code with the modifier Unsafe, so developers can ' t possibly use Unsafe Accidentally, and the C # compiler and the execution engine work together to ensure that unsafe code cannot masquerade as s AFE code.
The example
Using System;
Class Test
{
unsafe static void Writelocations (byte[] arr) {
Fixed (byte *p_arr = arr) {
byte *p_elem = P_arr;
for (int i = 0; i < arr. Length; i++) {
byte value = *p_elem;
string addr = Int. Format ((int) P_elem, "X");
Console.WriteLine ("Arr[{0}] at 0x{1} is {2}", I, addr, value);
p_elem++;
}
}
}
static void Main () {
byte[] arr = new byte[] {1, 2, 3, 4, 5};
Writelocations (arr);
}
}
Shows an unsafe method named Writelocations this fixes an array instance and uses pointer to manipulation over the Elements and write out the index, value, and location to each. One possible output of the program is:
Arr[0] at 0x8e0360 is 1
ARR[1] at 0x8e0361 is 2
ARR[2] at 0x8e0362 is 3
ARR[3] at 0x8e0363 is 4
ARR[4] at 0x8e0364 is 5
But of course the exact memory locations are to change.
1.3 Types
C # supports two major kinds of types:value types and reference. Value types include simple types (e.g., char, int, and float), enum types, and struct types. Reference types include class types, interface types, delegate types, and array types.
Value types differ from reference types in that variables of the value types directly contain their data, whereas variable s of the reference types store references to objects. With reference types, it's possible for two variables to reference the same object, and thus possible for operations on O NE variable to affect the object referenced by the other variable. With a value types, the variables each have their own copy of the data, and it's not possible for operations in one to Affe CT the other.
The example
Using System;
Class Class1
{
public int Value = 0;
}
Class Test
{
static void Main () {
int val1 = 0;
int val2 = VAL1;
Val2 = 123;
Class1 ref1 = new Class1 ();
Class1 ref2 = ref1;
Ref2. Value = 123;
Console.WriteLine ("Values: {0}, {1}", Val1, Val2);
Console.WriteLine ("Refs: {0}, {1}", Ref1.) Value, Ref2. Value);
}
}
Shows this difference. The output is
values:0, 123
Refs:123, 123
The assignment to the local variable val1 does not impact the local variable Val2-because both local variables are of a VA Lue type (int) and each local variable of the A value type has its own storage. In contrast, the assignment ref2. Value = 123; Affects the object that both REF1 and Ref2 reference.
Developers can define new value types through enum and struct declarations, and can define new reference via class, interface, and delegate declarations. The example
Using System;
public enum Color
{
Red, Blue, Green.
}
public struct Point
{
public int x, y;
}
public interface IBase
{
void F ();
}
public interface Iderived:ibase
{
void G ();
}
public class A
{
protected void H () {
Console.WriteLine ("A.H");
}
}
public class b:a, iderived
{
public void F () {
Console.WriteLine ("B.f, implementation of IDERIVED.F");
}
public void G () {
Console.WriteLine ("B.G, implementation of IDERIVED.G");
}
}
public delegate void Emptydelegate ();
Shows an example or two to each kind of type declaration. Later sections describe type declarations in greater detail.
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.