Sunteți pe pagina 1din 55

Sharpen Up On C#

The Productivity of VB, The Elegance of Java The Power of Visual C++

Burton Harvey, M.S., MCSD kbharvey@mindspring.com

The Sample Code: "Life" in C#


A fun and familiar way to demonstrate C#s power and elegance, and a reference to as many languages features as I could include This implementation leverages polymorphism so that the user interface can work with many kinds of cellular automata It worked on the PDC Tech Preview!

Outline
1. C# in the Context of MS.NET
MS.NET: Why, What, and How Other MS.NET languages (and Java) compared C# as the heart of MS.NET

2. Programming in C#
Data types and namespaces Loops and conditionals Object facilities
Access modifiers Interfaces and abstract classes Virtual and abstract methods Sealed classes Properties Indexers

Outline
2. Cont
User Interfaces enums Win forms Web forms Odds and Ends

3. The Future of C# / Questions and Answers

Well use the sample "Life" program for examples in Part II.

1. C# in the Context of MS.NET

Why MS.NET?

For vendors: Platform-independent products For developers: Language interoperability For managers: Faster and easier web application development For consumers: The Web becomes a globallydistributed application For techies everywhere: The End of DLL Hell

1. C# in the Context of MS.NET

What is "MS.NET"?

An IDE that can host many languages and apply the drag-and-drop metaphor to many tasks A class library of helpful functionality re-usable from any language Runtimes that run and "manage" code on any platform An XML-based standard for inter-object communication

1. C# in the Context of MS.NET

How Does MS.NET Work?

IL Intermediate Language.
The common bytecode to which all the languages compile The format in which the NGWS base classes are stored. A software abstraction layer Faster than interpreted code, but platform-independent One layer below source code, one layer above machine

JITs The interpreters of the IL. Assemblies "Molecules" of IL, packaged. A component with its metadata stored inside it instead of in the registry. XML Protocol for inter-object +communication.

1. C# in the Context of MS.NET

Wont MS.NET and C# Be Slow?

Fast processors make interpreted code more viable The NGWS base classes provide robust functionality "out-of-the-box" For situations in which speed is paramount, MS.NET provides options for translating the IL completely to native code before execution.

1. C# in the Context of MS.NET

IL Examined

Most IL instructions map almost directly to RISC op codes, but there are special instructions for handling objects. Think of IL as assembly code plus.

Speculation: Will there ever be a microprocessor whose native language is IL?

1. C# in the Context of MS.NET

JITs

MS.NET ships with several Just-In-Time compilers for interpreting IL.


The default JIT IL code is compiled to optimized code as needed (method-by-method) and cached. Econo-JIT IL code is quick compiled to less-thanoptimum code as needed (method-by-method) but not cached. Pre-JIT IL code is completely compiled and cached before execution begins. OptJIT A future enhancement. IL code is compiled in such a way as to target specific platforms.

1. C# in the Context of MS.NET

JITs

With JITMAN.EXE, you can set a servers JIT and configure that JITs settings:

1. C# in the Context of MS.NET

Understanding Assemblies

Assembly files end in ".dll" or ".exe" and contain IL Different versions of the same component can run side-by-side Assemblies describe their own interfaces

1. C# in the Context of MS.NET

Assemblies vs. COM Components

"COM saved space by allowing programs to share components. Today, space is cheap and time is at a premium. Its better to waste a little space by having redundant component copies on the hard drive than to waste hours (or even days) tracking down version conflicts."

1. C# in the Context of MS.NET

Inside an Assembly

ILDASM.EXE provides: A hierarchical view of the classes, methods, properties, events, and fields defined in the assembly A symbolic view of the assemblys IL

Note: ILDASM.EXEs sister program, ILASM.EXE, provides compiler vendors targeting MS.NET with a quick-and-dirty way of generating the manifest for IL code and packaging it with the IL in an assembly.

1. C# in the Context of MS.NET

C# and Managed Code

ALL C# code is managed code in that it is executed in the context of the runtime. The C# keyword, unsafe, flags blocks of code that, although managed, use C++ idioms (such as pointers) that might indicate malicious code. Some services provided by the runtime manager: Array bounds checking Garbage collection via the "count-and-sweep" algorithm

1. C# in the Context of MS.NET

C#: The Heart of MS.NET

When you use C#, you are using the language in which the NGWS base classes were coded before they were compiled to IL. When you use C#, youre using a modern language that includes the best features of earlier languages and eliminates their worst. When you use C#, youre not using a language that was adapted to the MS.NET platform, but one designed for it.
Microsoft has submitted a "C# Standard" for approval so that other vendors can implement versions of C# to target their platforms.

1. C# in the Context of MS.NET

C# Compared to C++

C# is designed to be simpler, safer, and more productive than C++ for enterprise development. Automatic garbage collection (goodbye, memory leaks!) No separate header files "one stop" coding No pointer manipulation The "->" operator has been subsumed within the "." operator. No preprocessor macros (#define functions), though conditional compilation is retained No fall-through case statements

1. C# in the Context of MS.NET

C# Compared to C++ (2)

Arrays are handled differently No complex plumbing code required for binary reusables Multiple interface inheritance permitted, single implementation inheritance permitted No generics (yet) Stronger type-checking (bool to int and byte to char conversions are not explicit) More object-oriented (thread of execution begins in a class, native support for properties) You can still use C++ features if you duck into unsafe blocks

1. C# in the Context of MS.NET

C# Compared to VB

C# has short-circuiting conditionals You cant use a string variable in a C# switchcase block the way that you can use a string in a VB selectcase block C# delimits lines with the semicolon (";") rather than a carriage return/line feed C# uses different characters for the assignment and equality operators
Developers moving from VB6 to VB7 face a steep learning curve. Because VB7 syntax is very similar to C# syntax, VB developers may want to go ahead and familiarize themselves with C#, too. Novice developers may want to start with C#.

1. C# in the Context of MS.NET

C# Compared to Java

C# code is similar to Java code. However, in addition to retaining several powerful C++ facilities with which Java dispenses, C# has at least one major development advantage: C# code can leverage, be leveraged by, and in general "play well" with code written in any other MS.NET language. You dont have to migrate your whole organization to C# in order to use it.

C# has type-safe enums C# has operator-overloading C# has native support for XML and distributed applications The C# bytecode interpreter works differently than the Java interpreter

2. Programming in C#

Some C# Coding Basics


Case-sensitive ";" terminates lines "{}" delimits code blocks "=" is the assignment operator; "==" is the equality operator Bool types are distinct from integer types; char types are distinct from bytes Programs begin from a class method, public static void Main(){}

2. Programming in C#

C# Data Types
Its rich (string, bool, decimal) Full palette of integer types Everythings an object (everything has methods) Value types and reference types differ in the way that assignments affect them. No pointers Boxing encloses a value type as a reference type on the heap to persist past function exit; unboxing casts a reference type to a value type on the stack. Conversion rules determine the legality of instance of these techniques. The System namespace defines the NGWS base types used by all the systems.

2. Programming in C#

The Integer Types


They are larger to accommodate Win64. Defined in System, they are also aliased there to provide C# programmers with familiar typenames.
System C# Typename Alias Byte SByte Int16 UInt15 Int32 UInt32 Int64 UInt64 byte sbyte short ushort int uint long ulong Bits 8 8 16 16 32 32 64 64 Min Value 0 -128 -32,768 0
-2,147,483,648

Max Value 255 127 32,767 65,535 2,147,483,647 4,294,967,295


9,223,372,036,854,775,807
18,446,744,073,709,551,615

0
-9,223,372,036,854,775,808

2. Programming in C#

Namespaces
Designed for enterprise development efforts, namespaces allow you to use different classes with the same name in the same program. Defining, using, and abbreviating namespaces in C# A single assembly can define several namespaces, and a single namespace can be defined across several assemblies. Just as assemblies are physical containers for classes, namespaces are conceptual ones.

2. Programming in C#

Useful Namespaces
System.Math provides useful mathematical functions. They are class methods. System.Random creates a sequence of pseudorandom numbers. To use this class, you create a Random object, set its seed property, and collect numbers from repeated calls to the objects Next() method.
The sample "Life" program leverages functionality from both of these namespaces.

2. Programming in C#

Useful Namespaces - Math Methods


Math Method Abs Round Floor Ceil Max Min Sin Cos Tan Asin Acos Atan Sqrt Pow Log Log10 Returns A numbers absolute value A number, rounded The largest integer less than a number The smallest integer greater than a number The largest sequence of numbers The smallest sequence of numbers The sine of a number (in radians) The cosine of a number (in radians) The tangent of a number (in radians) The arc-sine of a number (in radians) The arc-cosine of a number (in radians) The arc-tangent of a number (in radians) The square root of a number The value of a number taken to a power The natural logarithm of a number The base-10 Logarithm of a number

2. Programming in C#

The System.Exception Namespace


The namespace contains exception classes designed for the errors that will occur most commonly in C# programs. All of these inherit from the Exception base class.
NullReferenceException ComException ArgumentException, ArgumentNullException, ArgumentOutOfRangeException IndexOutOfRangeException InvalidOperationException SystemException InteropException SEHException

In your programs, you can use these classes as they are, or design your own exception classes that inherit from them. Often, an exception object is created and thrown away in the same line. (See next slide.)

2. Programming in C#

Loops
Pre-test loop: while Post-test loop: for and dowhile Variables declared inside loops are visible only within that loop

2. Programming in C#

Conditionals
Integer types do not implicitly convert to bool! Short-circuiting conditionals Case statements do not fall through

2. Programming in C#

The Rules of Life


Cellular automata "evolve" through generations "Dead" cells with exactly three neighbors come to life Live cells with less than 2 neighbors die of loneliness Live cells with more than 4 neighbors die of overcrowding Life is not the only kind of cellular automaton; a re-usable display for any kind of automaton would be nice

2. Programming in C#

Sample Program Class Diagram

2. Programming in C#

Summary of Class Diagram


To implement the design of our Automata class hierarchy, we need: A way to provide default functionality in a parent class so that child classes can use it A way to provide default functionality in a class so that child classes have to use it A way to force child classes to provide their own implementations for some functions (evolve()) A way to prevent the "Automaton" parent class from being instantiated A way to prevent the "LifeAutomaton" "proprietary" class from being specialized

2. Programming in C#

Classes and Access Modifiers


Private Visible only within class Protected Visible within class and inheriting classes Internal Visible to all classes within the component Public Visible within the class and without

2. Programming in C#

Abstract Classes and Interfaces


interfaces and abstract classes both define interfaces, but abstract classes can implement functions sealed classes cannot be subclassed Implications For "Life": A way to prevent the "Automaton" parent class from being instantiated A way to prevent the "LifeAutomaton" "proprietary" class from being specialized

2. Programming in C#

Virtual & Abstract Methods


virtual methods can be used or re-implemented by child classes abstract methods must be implemented by child classes Methods declared as neither virtual nor abstract cannot be overridden by child classes. For our Life implementation these facilities meet the following requirements: A way to provide default functionality in a parent class so that child classes can use it A way to provide default functionality in a class so that child classes have to use it A way to force child classes to provide their own implementations for some functions (evolve())

2. Programming in C#

Properties
Unlike C++, C# has special provisions for implementing object properties. A propertys read and write functions are together in the same code block. With access modifiers, you can discretely control property visibility.

2. Programming in C#

Arrays
C# allows both hard-coded and dynamic array sizes. Because C# lacks pointers, its array syntax is different than C++s.

2. Programming in C#

Indexers

Indexers make class interfaces more intuitive for clients. Indexers provide an opportunity to enforce rangechecking. Indexers provide an opportunity to protect the integrity of object state.

2. Programming in C#

Designing "Lifes" User Interface

2. Programming in C#

Enums
Enums make your source code more readable Enums enforce range-checking for integer values When exposed through a property, enums provide an centralized, understandable way of tracking state in a user interface.

2. Programming in C#

Scenario: User Clicks "Start"

2. Programming in C#

Scenario: User Clicks Stop

2. Programming in C#

Scenario: User Selects a New Automoton

2. Programming in C#

C# User Interfaces
WinForm interfaces run from an executable installed on client machines. WebForm interfaces are HTML sent from the web server to the clients browser and thus require no client installation. With WebForms, C# makes the web applications easier (and consequently, cheaper) to develop.

Now the process for creating thick clients and thin clients is the same:
1. 2. 3.

Drag controls from the toolbox and drop them onto a form. Set the properties of the controls. Write functions to handle events raised by the controls.

2. Programming in C#

How WebForms Work


You use web controls like ordinary Windows controls Web controls know how to render themselves in Javascript and HTML appropriate for different browsers Third-party vendors will supply web controls WebForms persist state like VB6 forms

2. Programming in C#

How WinForms Work


To create a new WinForm is to subclass a new WinForm class using the graphical form designer to generate the code. WinForm projects are similar to VB6 form projects, but are more object-oriented. WinForm event handling functions are looselybound to their associated controls. This gives flexibility.

2. Programming in C#

Events
Events provide a way for a server object to contact its client asynchronously. The server object "raises" the event, and the client object "handles" it in a function. Usually used to signal the failure or completion of a command, events are used in the Life program to signal a significant occurrence in the lifetime of the cell colony, such as a massive change in population size.

2. Programming in C#

Events (2)
To Use Events in C#: In the module containing the server class, forward-declare a delegate function with the extern keyword. In the server class itself, declare an instance of the delegate function modified with the event keyword. Well call this the "connection point." Also in the server class, put in the code that "raises" the event by calling the connection point at appropriate times.

2. Programming in C#

Events (3)
To Use Events in C#: In the client class, define event handler functions that match the signature of the delegate function declared in the server module. In the constructor function of the client class, cast references to your handler functions to the connection point type defined in the server module, and add those references to the server objects connection point.

2. Programming in C#

Calling the Win32/64 API


Wrapper the API call in a C# function, using the sysimport attribute to indicate the DLL in which the API function is defined. Remember that C# ints are 32 bits long. Remember that calling a Windows-specific function ties your code to that operating system.

2. Programming in C#

Calling Legacy COM Objects


Method 1: Use an MS.NET tool to generate an NGWS wrapper for the COM component so that you can call it as if it were an assembly. Method 2: In an unsafe block, query the DLLs IUnknown interface the way that you would in standard C++.

2. Programming in C#

Odds and Ends


C# supports operator overloading to further "objectify" your code. The IDE can generate XML documentation from the comments in your C# source code. C# does not require layers of boiler plate to expose your components classes as servers to other applications. Attributed programming allows you to associate properties with methods and classes in your code.

3. The Future of C# / Q & A

The Future of C#
"Generic code" that works with different data types. Unlike C++, C# will not use templates to implement generic code, but another mechanism that leverages the runtime to expose the generic code for use in any MS.NET language. OptJIT A new JIT for code with attributes providing compiler instructions, OptJIT would optimize code for specific platforms. Compact MS.NET A mysterious term tossed around at an interview. Your guess is as good as mine. An open C# standard for vendors who want to implement the language for their platform.

Resources
MSDN: http://msdn.microsoft.com/vstudio/nextgen/technol ogy/csharpintro.asp http://msdn.microsoft.com/msdnmag/issues/0900/c sharp/csharp.asp Other: http://www.csharptimes.com http://www.genamics.com/visualj++/csharp_compa rative.htm See accompanying paper for a more complete list

Questions and Answers

Burton Harvey, M.S., MCSD kbharvey@mindspring.com

S-ar putea să vă placă și