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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

return;

}

}

}

Next, you define the class name as Program:

class Program {

static void Main(string[] args) {

Console.WriteLine("Hello, world! This is my first C# program!");

Console.ReadLine();

return;

}

}

All C# code must be contained within a class. Because this class is within the HelloWorldnamespace, its fully qualified name is HelloWorld.Program.

Classes and objects are discussed in detail in Chapter 4.

Within the Programclass, you have the Main()method:

class Program {

static void Main(string[] args) {

Console.WriteLine("Hello, world! This is my first C# program!");

Console.ReadLine();

return;

}

}

Every C# program must have an entry point, which in this case is Main(). An entry point is the method that is first executed when an application starts up. The statickeyword indicates that this method can be called without creating an instance of the class.

Chapters 4 and 5 provide more information about object-oriented programming.

Unlike languages such as VB.NET in which a method can be either a function or a subroutine (a function returns a value; a subroutine does not), C# only supports functions. If a function does not return a result, you simply prefix the function name with the voidkeyword; otherwise, you indicate the return type by specifying its type.

You will find more about functions in Chapter 4.

Finally, you write the statements within the Main() method:

static void Main(string[] args) {

Console.WriteLine("Hello, world! This is my first C# program!");

Console.ReadLine();

return;

}

The WriteLine()method from the Consoleclass writes a string to the command prompt. Notice that in C# you end each statement with a semicolon ( ;), which indicates to the compiler the end of each statement. Hence, you can rewrite the WriteLine()statement like this:

Console.WriteLine(

"Hello, world! This is my first C# program!");

This is useful when you have a long statement and need to format it to fit into multiple lines for ease of reading.

The use of the ReadLine()statement is to accept inputs from the user. The statement is used here mainly to keep the command window visible. If you run this program in Visual Studio 2008 without using the ReadLine()method, the program will print the hello world statement and then close the window immediately.

Passing Arguments to Main()

If you run a program in the command prompt as described earlier in the chapter, you can pass in arguments to the application. For example, you might want the program to display your name. To do so, pass in the name like this:

C:\C#>HelloWorld Wei-Meng Lee

The argument passed into the program can be accessed by the args parameter (a string array) defined in the Main() method. Hence, you need to modify the program by displaying the values contained in the args string array, like this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace HelloWorld {

class Program {

static void Main(string[] args) {

Console.Write("Hello, ");

for (int i = 0; i < args.Length; i++)

Console.Write("{0} ", args[i]);

Console.Write("! This is my first C# program!");

Console.ReadLine();

return;

}

}

}

Chapter 8 covers string arrays in depth.

Language Syntax

C# is a case-sensitive language that is highly expressive yet simple to learn and use. The following sections describe the various syntax of the language.

Keywords

In any programming language, there is always a list of identifiers that have special meanings to the compiler. These identifiers are known as keywords, and you should not use them as identifiers in your program.

Here's the list of keywords in C# 2008:

abstract event new struct

as explicit null switch

base extern object this

bool false operator throw

break finally out true

byte fixed override try

case float params typeof

catch for private uint

char foreach protected ulong

checked goto public unchecked

class if readonly unsafe

const implicit ref ushort

continue in return using

decimal int sbyte virtual

default interface sealed volatile

delegate internal short void

do is sizeof while

double lock stackalloc

else long static

enum namespace string

Variables

In C#, you declare variables using the following format:

datatype identifier;

The following example declares and uses four variables:

class Program {

static void Main(string[] args) {

//---declare the variables---

int num1;

int num2 = 5;

float num3, num4;

//---assign values to the variables---

num1 = 4;

num3 = num4 = 6.2f;

//---print out the values of the variables---

Console.WriteLine("{0} {1} {2} {3}", num1, num2, num3, num4);

Console.ReadLine();

return;

}

}

Note the following:

num1is declared as an int(integer).

num2is declared as an intand assigned a value at the same time.

num3and num4are declared as float(floating point number)

□ You need to declare a variable before you can use it. If not, C3 compiler will flag that as an error.

□ You can assign multiple variables in the same statement, as is shown in the assignment of num3and num4.

This example will print out the following output:

4 5 6.2 6.2

The following declaration is also allowed:

//---declares both num5 and num6 to be float

// and assigns 3.4 to num5---

float num5 = 3.4f, num6;

But this one is not allowed:

//---cannot mix different types in a declaration statement---

int num7, float num8;

The name of the variable cannot be one of the C# keywords. If you absolutely must use one of the keywords as a variable name, you need to prefix it with the @ character, as the following example shows:

int @new = 4;

Console.WriteLine(@new);

Scope of Variables

The scope of a variable (that is, its visibility and accessibility) that you declare in C# is affected by the location in which the variable is declared. Consider the following example where a variable numis declared within the Programclass:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x