56
PART I THE C# LANGUAGE Chapters 1,2 Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

PART I THE C# LANGUAGE Chapters 1,2 Reference: Professional C# 2012 and.Net 4.5 by Bill Evjen, et al

Embed Size (px)

Citation preview

PART I THE C# LANGUAGEChapters 1,2

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Chapter 1- .NET Architecture• Compiling and running code that targets .NET• Advantages of Microsoft Intermediate Language (MSIL)• Value and reference types• Data typing• Understanding error handling and attributes• Assemblies, .NET base classes, and namespaces

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Relationship of C# to .NET• C# is a relatively new programming language and is significant in

two respects:• It is specifically designed and targeted for use with Microsoft’s .NET

Framework (a feature – rich platform for the development, deployment, and execution of distributed applications).

• It is a language based on the modern object- oriented design methodology

• C# is a language in its own right. Although it is designed to generate code that targets the .NET environment, it is not itself part of .NET

• Some features are supported by .NET but not by C# and vice versa (Eg: some instances of operator overloading are not supported by .NET but are by C#.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Common Language RuntimeCentral to the .NET Framework is its runtime execution environment, known as the Common Language Runtime (CLR) or the .NET runtime. Code running under the control of the CLR is often termed managed code.

Compilation occurs in two steps in .NET:• Compilation of source code to Microsoft Intermediate Language

(IL).• Compilation of IL to platform-specific code by the CLR.

Advantages• Platform Independence• Performance Improvement• Language Interoperability

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Key features of IL• Object orientation and the use of interfaces• Strong distinction between value and reference types

Value types are those for which a variable directly stores its data, whereas reference types are those for which a variable simply stores the address at which the corresponding data can be found.

• Strong data typingAll variables are clearly marked as being of a particular,

specific data type. In particular, IL does not normally permit any operations that result in ambiguous data types. Eg: variant• Error handling using exceptions• Use of attributes R

efer

ence

: Pro

fess

iona

l C#

201

2 an

d .N

et 4

.5 b

y B

ill E

vjen

, et a

l

Language interoperabilityLanguage interoperability is that classes written in one language should be able to talk directly to classes written in another language.• A class written in one language can inherit from a class written in

another language.• The class can contain an instance of another class, no matter

what the languages of the two classes are.• An object can directly call methods against another object

written in another language.• Objects (or references to objects) can be passed around between

methods.• When calling methods between languages, you can step between

the method calls in the debugger, even when this means stepping between source code written in different languages.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Strong Data TypingThe services provided by .NET that rely on type safety:• Language interoperability• Garbage collection• Security• Application domains

Common Type SystemThe CTS defines the predefined data types that are available in IL, so that all languages that target the .NET Framework will produce compiled code that is ultimately based on these types.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Common Language Specification• The Common Language Specification (CLS) works with the

CTS to ensure language interoperability. • The CLS is a set of minimum standards that all compilers

targeting .NET must support. • Because IL is a very rich language, writers of most

compilers will prefer to restrict the capabilities of a given compiler to support only a subset of the facilities offered by IL and the CTS.

• For example, IL is case-sensitive. CLS compliant code should not expose any two names that differ only in their case

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Garbage Collection• The garbage collector is .NET ’ s answer to memory

management and in particular to the question of what to do about reclaiming memory that running applications ask for.

• Garbage collection works in .NET because IL has been designed to facilitate the process.

• The principle requires that you cannot get references to existing objects other than by copying existing references and that IL be type safe.

• One important aspect of garbage collection is that it is not deterministic , i.e. the time its called is unpredictable.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Security• .NET can really excel in terms of complementing the

security mechanisms provided by Windows because it can offer code-based security, whereas Windows really offers only role-based security.

• Role-based security is based on the identity of the account under which the process is running (that is, who owns and is running the process).

• Code-based security, by contrast, is based on what the code actually does and on how much the code is trusted.

• The importance of code-based security is that it reduces the risks associated with running code of dubious origin

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Application Domains• Application domains are an important innovation in .NET

and are designed to ease the overhead involved when running applications that need to be isolated from each other but that also need to be able to communicate with each other.• Example: A web server application, which may be

simultaneously responding to a number of browser requests

• Application domains are designed as a way of separating components without resulting in the performance problems associated with passing data between processes

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Use of Exceptions and Attributes

Error Handling With Exceptions• The exception architecture ensures that when an error condition

occurs, execution can immediately jump to the exception handler routine that is most specifically geared to handle the exception condition in question.

Use Of Attributes• The initial idea of an attribute was that it provided extra

information concerning some item in the program that could be used by the compiler.

• Attributes can be defined in source code in one language and read by code that is written in another language.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Assemblies• An assembly is the logical unit that contains compiled code

targeted at the .NET Framework.• An assembly is completely self - describing and is a logical

rather than a physical unit, which means that it can be stored across more than one file.

• An important characteristic of assemblies is that they contain metadata that describes the types and methods defined in the corresponding code.

• An assembly, however, also contains assembly metadata that describes the assembly itself. This assembly metadata, contained in an area known as the manifest.

• Assemblies come in two types: private and shared assemblies.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Types of Assemblies• Private assemblies are the simplest type. They normally ship

with software and are intended to be used only with that software.

• Shared assemblies are intended to be common libraries that any other application can use.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

ReflectionReflection is the technique used by managed code to actually examine other managed code, and even examine itself, to determine information about that code.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Parallel and Asynchronous Programming• Parallel Programming allows work actions to run

across multiple processors• The new parallel programming APIs that are available now

make writing safe multi-threaded code simple

• Asynchronous Programming allows tasks to run independently, without blocking the main program (i.e. a UI thread processing an asynchronous task would not have to wait and become unresponsive)• Asynchronous methods have become much easier to invoke in

the latest release of .NET due to the Task Parallel Library (TPL)

.Net Framework Classes• The .NET base classes are a massive collection of managed code

classes.• These classes follow the same object model that IL uses, based on

single inheritance.• The great thing about the .NET base classes is that they have been

designed to be very intuitive and easy to use. For example, to start a thread, you call the Start( ) method of the Thread class.

• For calling an API function not available in the base classes, .NET offers a platform – invoke that ensures data types are correctly converted.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Namespaces• Namespaces are the way that .NET avoids name clashes between

classes.• A namespace is no more than a grouping of data types, but it has

the effect that the names of all data types within a namespace are automatically prefixed with the name of the namespace.

• It is also possible to nest namespaces within each other.• If a namespace is not explicitly supplied, the type will be added to

a nameless global namespace.• Microsoft recommends that for most purposes you supply at

least two nested namespace names; the first represents the name of your company and the second represents the name of the technology or software package • CompanyName.SalesServices.Customer

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Creating .NET Applications Using C#Console Applications• C# can be used to create console applications: text - only applications that run in

a DOS window.

ASP.NET Applications• The primary goal of ASP.NET is to build powerful, secure, dynamic applications

using the least possible amount of code.

Windows forms• Windows forms support fat-client or thick-client apps — applications that must

be installed on the end user’s machine where most of the processing takes place.

Windows Presentation Foundation (WPF)• WPF makes use of XAML, the XML declaration of an application, to create the

visual aspects and behaviors of an application through Declarative Programming• Declarative programming means that instead of creating objects through programming

in a compiled language such as C#, VB, or Java, everything is declared through XML-type programming.

Windows 8 Apps• Written with C# and XAML to create a touch-first application specific for

Windows 8 and newer operating systems.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Creating ASP.NET ApplicationsFeatures Of ASP.NET

• ASP.NET pages are structured.

• ASP.NET pages are easier to understand.

• A Visual Studio project, or solution, contains all the files associated with an application.

• ASP.NET is remarkable for its increased performance.

• Web Forms make web page construction even easier.

• Web Server Controls are used to populate a Web Form and are XML tags in the ASP.NET namespace that the web browser dynamically transforms into HTML and client-side script when a page is requested

• ASP.NET MVC supports the Model-View-Controller pattern for easily testable applications that can leverage HTML5 and JavaScript libraries

• ASP.NET Dynamic Data uses Entity Framework and scaffolding options to efficiently read and write data in a form

• ASP.NET Web API allows for a simple communication between the client and server using REST, making it easy to consume data in web clients using JavaScript as well as Windows 8 applications

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Creating Windows Applications

Windows Service • A program designed to run in the background. • Services are used when a program has to be running

continuously and ready to respond to events without having been explicitly started by the user.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

WCF and WF

Windows Communication foundation (WCF)• Single way to move data and services from one point to another.• Supports both REST and SOAP-based communication.• WCF provides an ability to build service one time and then

expose this service in a multitude of ways by just making changes within a configuration file.

Windows Workflow foundation (WF)• WF provides a model to define and execute processes using a set

of building blocks called activities.• A workflow is constructed from a number of activities, and these

activities are executed at runtime.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

SUMMARY

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Chapter 2- CORE C#• Variables• Predefined Data types• Flow Control• Enumerations• Namespaces• The Main() method• Compiling methods• Console I/O• Using Comments• Preprocessor directives• Guidelines and conventions for good programming in C#

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

First C# program using System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace Chapter2{ class Hello_World { static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.ReadLine(); return; }

}}//Code Snippet: Hello_World.cs

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

VariablesSyntax:datatype identifier;For example:int i;This statement declares an int named i.The compiler won’t actually let you use this variable in an expression until you have initialized it with a value. After it has been declared, you can assign a value to the variable using the assignment operator, =:i = 10;int i = 10;int x = 10, y =20; // x and y are both integersint x = 10, bool y = true; // This won't compile!

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Type Inference

Type inference makes use of the var keyword. The compiler “infers” what type the variable is by what the variable is initialized to.For example,int someNumber = 0;becomesvar someNumber = 0;Even though someNumber is never declared as being an int, the compiler figures this out and someNumber is an int for as long as it is in scope. Once compiled, the two preceding statements are equal.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

code snippet: Variables1.cs

namespace Variables1_ConsoleApp{ class Program { static void Main(string[] args) { var name = "Bugs Bunny"; var age = 25; var isRabbit = true; Type nameType = name.GetType(); Type ageType = age.GetType(); Type isRabbitType = isRabbit.GetType(); Console.WriteLine("name is type " + nameType.ToString()); Console.WriteLine("age is type " + ageType.ToString()); Console.WriteLine("isRabbit is type " + isRabbitType.ToString()); Console.ReadLine(); return; } }}

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Variable scopeThe scope of a variable is the region of code from which the variable can be accessed. In general, the scope is determined by the following rules:

• A field (also known as a member variable) of a class is in scope for as long as its containing class is in scope.

• A local variable is in scope until a closing brace indicates the end of the block statement or method in which it was declared.

• A local variable that is declared in a for, while, or similar statement is in scope in the body of that loop.

• A scope clash may occur with local variable declaration. Code Snippet: Scope_Clash.cs

• C# makes a fundamental distinction between variables that are declared at the type level (fields) and variables that are declared within methods (local variables) Code Snippet: Scope_Test.cs

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Constants• As the name implies, a constant is a variable whose value cannot be

changed throughout its lifetime.const int a = 100; // This value cannot be changed.• Constants make the programs easier to read, modify and help

prevent mistakes.class Scope_Test { const int a = 100; static int j = 20; public static void Main() { int j = 30; Console.WriteLine(j+a); return; } }OUTPUT: 130

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Predefined Data TypesValue Types And Reference Types• A value type stores its value directly, whereas a reference type

stores a reference to the value.• Value types are stored in an area known as the stack, and

reference types are stored in an area known as the managed heap.

• For example, int is a value type; Vector is a reference type.

• The Common Language Runtime (CLR) implements an elaborate algorithm to track which reference variables are still reachable and which have been orphaned.

• Periodically, the CLR will destroy orphaned objects and return the memory that they once occupied back to the operating system. This is done by the garbage collector.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Predefined Value TypesInteger Types

Floating-point Types

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Predefined Value Types Contd.• The Decimal Type

• The Boolean Type

• The Character Type

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Predefined Value Types Contd.

• Escape sequences

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Predefined Reference Types

The object Type• In C#, the object type is the ultimate parent type from which all

other intrinsic and user-defined types are derivedThe string Type• A string object is allocated on the heap, not the stack, and when

one string variable is assigned to another string, two references to the same string in memory is obtained.

string str1 = "Hello ";string str2 = "World";string str3 = str1 + str2; // string concatenation

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

code snippet : StringExample.cs

class StringExample { public static int Main() { string s1 = "a string"; string s2 = s1; Console.WriteLine("s1 is " + s1); Console.WriteLine("s2 is " + s2); s1 = "another string"; Console.WriteLine("s1 is now " + s1); Console.WriteLine("s2 is now " + s2); Console.ReadLine(); return 0; } }Output:s1 is now a strings2 is now a strings1 is now another strings2 is now another string

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Flow Control• The statements that allows to control the flow of the program

rather than executing every line of code in the order it appears in the program.

Conditional Statements• Conditional statements allow you to branch your code depending

on whether certain conditions are met or on the value of an expression.

• Two types: if statement and switch statement.• The if statement allows to test whether a specific condition is

met.if (condition)statement(s)elsestatement(s)

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

code snippet: ElseIf.cs

class Elseif { static void Main(string[] args) { Console.WriteLine("Type in a string"); string input; input = Console.ReadLine(); if (input == "") { Console.WriteLine("You typed in an empty string."); } else if (input.Length < 5) { Console.WriteLine("The string had less than 5 characters."); } else if (input.Length < 10) { Console.WriteLine("The string had at least 5 but less than 10Characters."); } Console.WriteLine("The string was " + input); } }

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

The switch statement• The switch statement, which allows to compare an expression with a

number of different values.• The end of the code for each case is marked using the break

statement.• The default case will execute if the expression evaluates to none of

the other cases.switch (integerA){case 1:Console.WriteLine("integerA =1");break;case 2:Console.WriteLine("integerA =2");break;case 3:Console.WriteLine("integerA =3");break;default:Console.WriteLine("integerA is not 1,2, or 3");break;}

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Loops• C# provides four different loops (for, while, do . . . while, and foreach)

that allow to execute a block of code repeatedly until a certain condition is met.

• The for loopfor (initializer; condition; iterator)statement(s)

code snippet NestedFor.cs• The while loop: while(condition)statement(s);

• The do . . . while loopdo{statement(s);} while(condition);

• The foreach loop allows to iterate through each item in a collection.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Jump StatementsC# provides a number of statements that allow to jump immediately to another line in the program. E.g. Break, goto, continue, return.The goto statement allows to jump directly to another specified line in the program, indicated by a label (this is just an identifier followed by a colon)It certainly doesn’t conform to good object-oriented programming practice.goto Label1;Console.WriteLine("This won't be executed");Label1:Console.WriteLine("Continuing execution from here");• The continue statement exits only from the current iteration of the

loop, meaning that execution will restart at the beginning of the next iteration of the loop.

• The return statement is used to exit a method of a class, returning control to the caller of the method.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Enumerations• An enumeration is a user-defined integer type.• The declaration of an enumeration must specify a set of

acceptable values that instances of that enumeration can contain.

public enum TimeOfDay{Morning = 0,Afternoon = 1,Evening = 2}

• System.Enum has several methods that help in the manipulation of instances of enum.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Namespaces• Namespaces provide a way of organizing related classes and other types.

• Unlike a file or a component, a namespace is a logical rather than physical grouping.

• Example:namespace Wrox{

namespace ProCSharp{

namespace Basics{

class NamespaceEx{// Code for the class here...}

}}

}

• Full name of NamespaceEx class is wrox.ProCSharp.Basics.NamespaceEx

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

The using directive

• The using statements occur at the top of C# files. It does no

physical linking between files.

• The class’s namespace is listed at the top of the file, prefixed with

the using keyword

• Namespace aliases: Another use of the using keyword is to assign

aliases to classes and namespaces.

using alias = NamespaceName;

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Main() method• C# programs start execution at a method named Main()• This must be a static method of a class (or struct), and must have a

return type of either int or void.• The method can be marked as private or public(more appropriate

as it has to be called from outside the program)

Multiple Main() Methods:• If there is more than one Main() method in an application, the

compiler will return an error message.• In this case the compiler has to be told which of these methods to

use as the entry point by using the /main switch, together with the full name of the class to which the Main() method belongs.

E.g. csc DoubleMain.cs /main:Wrox.MathExample

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

code snippet: DoubleMain.csclass Client { public static int Main() { MathExample.Main(); return 0; } } class MathExample { static int Add(int x, int y) { return x + y; } public static int Main() { int i = Add(5, 10); Console.WriteLine(i); return 0; } }//csc DoubleMain.cs /main:Wrox.MathExample to compile

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Compiling C# Files

• Example: To compile a C# file into a .NET DLL using the following command,

csc /t:library MathLibrary.cs

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Console I/OSome of the Console class’s static methods used for reading and writing data:• To read a line of text from the console window, you use the

Console.ReadLine() method.• Console.Write() — Writes the specified value to the console

window.• Console.WriteLine() — This does the same, but adds a newline

character at the end of the output.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Using CommentsInternal comments within the source files: C# uses the traditional C-type single-line (//...) and multiline (/* ... */) comments:// This is a singleline comment/* This commentspans multiple lines. */Xml documentation• C# has a very neat feature that has the ability to produce

documentation in XML format automatically from special comments.

• These comments are single-line comments but begin with three slashes (///)

• Within these comments, you can place XML tags containing documentation

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Xml Documentation

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

The C# Preprocessor Directives• Preprocessor directives are commands that never actually get translated

to any commands in the executable code, but instead they affect aspects of the compilation process.

• Preprocessor directives can be used to prevent the compiler from compiling certain portions of the code.

#define ENTERPRISE#if ENTERPRISE

// do something#elif PROFESSIONAL// do something else#else// code for the leaner version#endif

#define and #undef• #define tells the compiler that a symbol with the given name exists• #undef does the opposite, and removes the definition of a symbol#if, #elif, #else, and #endif• These directives inform the compiler whether to compile a block of code

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

#warning• If the compiler sees a #warning directive, it will display whatever

text appears after the #warning to the user, after which compilation continues.

#error • If it encounters a #error directive, it will display the subsequent

text to the user as if it were a compilation error message and then immediately abandon the compilation, so no IL code will be generated.

#region and #endregion• The #region and #endregion directives are used to indicate that a

certain block of code is to be treated as a single block with a given name.

#line• The #line directive can be used to alter the filename and line

number information that is output by the compiler in warnings and error messages.

#pragma• The #pragma directive can either suppress or restore specific

compiler warnings.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

C# Programming guidelinesIdentifiers are the names given to variables, to user-defined types such as classes and structs, and to members of these types.Rules For Identifiers• Identifiers are case-sensitive• They must begin with a letter or underscore, although they

can contain numeric characters.• C# keywords can not be used as identifiers.Usage Conventions• The convention by which variable names are prefixed with

letters that represent the data type is known as Hungarian notation. This is widely regarded as redundant with smart editors and IntelliSense.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Naming Conventions• The general philosophy in the .NET Framework is also that

the name of a variable should reflect the purpose of that variable instance and not the data type.

• Pascal casing is used for names of classes and public/protected members.• The first letter of each word in a name is capitalized.

• Camel casing is used for private members.• The first letter of the first word is not capitalized.

• Name styles should be consistent.• Namespace names are particularly important to design

carefully to avoid risk of ending up with the same name.• Namespace names are the only way that .NET distinguishes

names of objects in shared assemblies

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

Use of Properties and Methods

One area that can cause confusion in a class is whether a particular quantity should be represented by a property or a method• Use a property if something really should look and feel like

a variable.Use of fields• Fields should almost always be private, except that in some

cases it may be acceptable for constant or read-only fields to be public.

• The reason is that if a field is made public, it hinder the ability to extend or modify the class in the future.

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al

SUMMARY

Ref

eren

ce: P

rofe

ssio

nal C

# 2

012

and

.Net

4.5

by

Bill

Evj

en, e

t al