Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace HelloWorld {

class Program {

static int num = 7;

static void Main(string[] args) {

Console.WriteLine("num in Main() is {0}", num); //---7---

HelloWorld.Program.Method1();

Console.ReadLine();

return;

}

static private void Method1() {

Console.WriteLine("num in Method1() is {0}", num); //---7---

}

}

}

Because the numvariable is declared in the class, it is visible (that is, global) to all the methods declared within the class, and you see the following output:

num in Main() is 7

num in Method1() is 7

However, if you declare another variable with the same name (num) within Main()and Method1(), like this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace HelloWorld {

class Program {

static int num = 7;

static void Main(string[] args) {

int num = 5;

Console.WriteLine("num in Main() is {0}", num); //---5---

HelloWorld.Program.Method1();

Console.ReadLine();

return;

}

static private void Method1() {

int num = 10;

Console.WriteLine("num in Method1() is {0}", num); //---10---

}

}

}

You get a very different output:

num in Main() is 5

num in Method1() is 10

That's because the numvariables in Main()and Method1()have effectively hidden the num variable in the Programclass. In this case, the numin the Programclass is known as the global variable while the numvariables in Mainand Method1are known as local variables. The num variable in Main()is only visible within Main(). Likewise, this also applies to the num variable in Method1().

What if you need to access the numdeclared in the Program class? In that case, you just need to specify its full name:

Console.WriteLine("num in Program is {0}", HelloWorld.Program.num); //---7---

While a local variable can hide the scope of a global variable, you cannot have two variables with the same scope and identical names. The following makes it clear:

static void Main(string[] args) {

int num = 5;

Console.WriteLine("num in Main() is {0}", num); //---5---

int num = 6; //---error: num is already declared---

return;

}

However, two identically named variables in different scope would be legal, as the following shows:

static void Main(string[] args) {

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

//--- i is visible within this loop only---

Console.WriteLine(i);

} //--- i goes out of scope here---

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

//--- i is visible within this loop only---

Console.WriteLine(i);

} //--- i goes out of scope here---

Console.ReadLine();

return;

}

Here, the variable iappears in two forloops (looping is covered later in this chapter). The scope for each iis restricted to within the loop, so there is no conflict in the scope and this is allowed.

Declaring another variable named ioutside the loop or inside it will cause a compilation error as the following example shows:

static void Main(string[] args) {

int i = 4; //---error---

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

int i = 6; //---error---

Console.WriteLine(i);

}

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

Console.WriteLine(i);

}

Console.ReadLine();

return;

}

This code results in an error: "A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'parent or current' scope to denote something else."

Constants

To declare a constant in C#, you use the constkeyword, like this:

//---declared the PI constant---

const float PI=3.14f;

You cannot change the value of a constant (during runtime) once it has been declared and assigned a value.

As a good programming practice, you should always use constants whenever you use values that do not change during runtime.

Comments

In C#, you can insert comments into your program using either //or a mirrored pair of /*and */. The following example shows how to insert comments into your program using //:

//---declare the variables---

int num1; //---num1 variable---

int num2 = 5; //---num2 variable---

float num3, num4; //---num3 and num4 variables---

And here's an example of how to insert a multi-line block of comments into your program:

/*

Declares the following variables: num1, num2, num3, num4

*/

int num1;

int num2 = 5;

float num3, num4;

In general, use the //for short, single-line comments and /* */for multi-line comments.

XML Documentation

One of the very cool features available in Visual Studio 2008 is the support for XML documentation. This feature enables you to insert comments into your code using XML elements and then generate a separate XML file containing all the documentation. You can then convert the XML file into professional- looking documentation for your code.

To insert an XML comment into your code, position the cursor before a class or method name and type three / characters (left window in Figure 3-6). The XML template is automatically inserted for you (see the right window in Figure 3-6).

Figure 36 The following code shows the XML documentation template created for - фото 87

Figure 3-6

The following code shows the XML documentation template created for the Programclass, the Main()method, and the AddNumbers()method (you need to fill in the description for each element):

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace HelloWorld {

///



/// This is my first C# program.

///

class Program {

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x