61
An Introduction An Introduction to .NET to .NET Keith Mulkey Keith Mulkey Senior Software Engineer Senior Software Engineer SFA, Inc. SFA, Inc.

An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Embed Size (px)

Citation preview

Page 1: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

An Introduction An Introduction to .NETto .NETKeith MulkeyKeith Mulkey

Senior Software EngineerSenior Software Engineer

SFA, Inc.SFA, Inc.

Page 2: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

AgendaAgendaWhat is .NET?What is .NET?

What is the Common Language Runtime (CLR)?What is the Common Language Runtime (CLR)?Introduction to Visual Studio 2005 and the IDEIntroduction to Visual Studio 2005 and the IDE

Introduction to C#Introduction to C#

Page 3: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

What is .NET?What is .NET?

According to Microsoft, .NET is According to Microsoft, .NET is ““the Microsoft Web services strategy to the Microsoft Web services strategy to

connect information, people, systems, and connect information, people, systems, and devices through software”devices through software”

What does this mean to the average What does this mean to the average developer?developer?ABSOLUTELY NOTHING!ABSOLUTELY NOTHING!

Page 4: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

What is .NET to the average What is .NET to the average developer?developer?

A Framework that provides:A Framework that provides:an easy to use development environmentan easy to use development environmenta multitude of libraries that make our job a multitude of libraries that make our job easier including distributed processingeasier including distributed processingcross-language interoperabilitycross-language interoperabilitya runtime environment that will manage a runtime environment that will manage resources with no assistance from usresources with no assistance from ustight integration with the operating systemtight integration with the operating systemeasy integration of third party librarieseasy integration of third party libraries

Page 5: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

.NET Framework Design Features.NET Framework Design Features

Component (Assembly) InfrastructureComponent (Assembly) Infrastructure

Language IntegrationLanguage Integration

Distributed ComputingDistributed Computing

Simplified DevelopmentSimplified Development

Simplified DeploymentSimplified Deployment

ReliabilityReliability

SecuritySecurity

Page 6: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Component InfrastructureComponent Infrastructure

.NET classes are ready to be used at the .NET classes are ready to be used at the binary levelbinary level

.NET assemblies do not have to be .NET assemblies do not have to be registered in the Windows registryregistered in the Windows registry

No special “plumbing” code is required No special “plumbing” code is required for component registration, class for component registration, class factories, component lifetime or dynamic factories, component lifetime or dynamic bindingbinding

Page 7: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Language IntegrationLanguage Integration

Language Independence vs. Language Language Independence vs. Language IntegrationIntegration

COM supported language independenceCOM supported language independenceComponent can be written in any languageComponent can be written in any languageComponent must meet COM specification rulesComponent must meet COM specification rulesSupports binary reuseSupports binary reuseDOES NOT allow COM component code reuseDOES NOT allow COM component code reuseDOES NOT support COM component class DOES NOT support COM component class extensionextensionDOES NOT allow catching exceptions thrown by DOES NOT allow catching exceptions thrown by COM componentCOM component

Page 8: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Language IntegrationLanguage Integration

Language Independence vs. Language Language Independence vs. Language IntegrationIntegration

COM supported language independenceCOM supported language independence.NET supports language integration.NET supports language integration

Components can be written in any supported Components can be written in any supported language (C#, VB, Managed C++, J#)language (C#, VB, Managed C++, J#)The adherence to a common specification is The adherence to a common specification is taken care of by .NETtaken care of by .NETDOES allow .NET component code reuseDOES allow .NET component code reuseDOES support .NET component class extensionDOES support .NET component class extensionDOES allow catching exceptions thrown by .NET DOES allow catching exceptions thrown by .NET componentscomponents

Page 9: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Language IntegrationLanguage Integration

Language Independence vs. Language Language Independence vs. Language IntegrationIntegration

COM supported language independenceCOM supported language independence.NET supports language integration.NET supports language integration

Made possible by the Common Type System Made possible by the Common Type System (CTS)(CTS)Everything in CTS derives from System.ObjectEverything in CTS derives from System.ObjectCTS supports concepts of classes, interfaces, CTS supports concepts of classes, interfaces, delegates, reference types, and value typesdelegates, reference types, and value typesCTS supports base system types such as CTS supports base system types such as integer, double, string, file manipulationinteger, double, string, file manipulation

Page 10: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Language IntegrationLanguage Integration

Language Independence vs. Language Language Independence vs. Language IntegrationIntegration

COM supported language independenceCOM supported language independence.NET supports language integration.NET supports language integration

Common Language Specification (CLS) Common Language Specification (CLS) provides minimum set of rulesprovides minimum set of rulesAll .NET language compilers must meet CLS All .NET language compilers must meet CLS and generate code that conforms to CTSand generate code that conforms to CTSThis allows different .NET languages to be used This allows different .NET languages to be used in the same applicatonin the same applicaton

Page 11: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Distributed ComputingDistributed Computing

COM supported distributed computing COM supported distributed computing using DCOMusing DCOM

Due to embedded IP address, DCOM Due to embedded IP address, DCOM would not work through firewalls and would not work through firewalls and NATNAT

.NET uses industry standard SOAP to .NET uses industry standard SOAP to interoperate on the Internetinteroperate on the Internet

.NET Remoting uses a CORBA-like .NET Remoting uses a CORBA-like approach for distributed computingapproach for distributed computing

Page 12: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Simplified DevelopmentSimplified Development

Every .NET language uses the same Every .NET language uses the same library of .NET componentslibrary of .NET componentsThe API to the .NET library of The API to the .NET library of components is always the samecomponents is always the sameIntegrating with .NET components is Integrating with .NET components is always the samealways the sameThe same IDE is used for all languagesThe same IDE is used for all languagesIntellisenseIntellisense®® works the same for all works the same for all languageslanguagesThe build process is always the sameThe build process is always the same

Page 13: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Simplified DeploymentSimplified Deployment

No more “DLL Hell”No more “DLL Hell”Shared DLLs are registered with the Global Shared DLLs are registered with the Global Assembly Cache (GAC)Assembly Cache (GAC)

Multiple versions of the same DLL can co-Multiple versions of the same DLL can co-existexist

Applications are tightly bound to a particular Applications are tightly bound to a particular DLL versionDLL version

Page 14: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Simplified DeploymentSimplified Deployment

No more “DLL Hell”No more “DLL Hell”

DLL Registry entries eliminatedDLL Registry entries eliminatedReferences and dependencies stored in References and dependencies stored in DLL manifestDLL manifest

Private DLLs are found using logical paths Private DLLs are found using logical paths or XML based configuration filesor XML based configuration files

Shared (public) DLLs are found using the Shared (public) DLLs are found using the GACGAC

Both are found at runtimeBoth are found at runtime

Page 15: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Simplified DeploymentSimplified Deployment

No more “DLL Hell”No more “DLL Hell”

DLL Registry entries eliminatedDLL Registry entries eliminated

““Zero-Impact” installation and removalZero-Impact” installation and removal.NET DLLs are not entered into registry .NET DLLs are not entered into registry upon installationupon installation

Hence no need to remove from registry Hence no need to remove from registry upon uninstallupon uninstall

Installation and removal can be Installation and removal can be accomplished with copy and delete accomplished with copy and delete

Page 16: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Simplified DeploymentSimplified Deployment

No more “DLL Hell”No more “DLL Hell”

DLL Registry entries eliminatedDLL Registry entries eliminated

““Zero-Impact” installation and removalZero-Impact” installation and removal

Web, network, and CD deployment all Web, network, and CD deployment all supported within Visual Studio 2005supported within Visual Studio 2005

Page 17: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

ReliabilityReliability

Type safetyType safetyCLR must recognize and verify types CLR must recognize and verify types before they are loaded and executedbefore they are loaded and executed

Helps prevent buffer overruns which can be Helps prevent buffer overruns which can be a source of program errors and security a source of program errors and security weaknessesweaknesses

Page 18: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

ReliabilityReliability

Type safetyType safety

Common error handlingCommon error handling

Automatic memory managementAutomatic memory management

Page 19: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

SecuritySecurity

.NET can protect access to specific parts .NET can protect access to specific parts of executable codeof executable code.NET supports strong naming of .NET supports strong naming of assemblies to help prevent pirating and assemblies to help prevent pirating and tamperingtampering.NET has extensive support for all of the .NET has extensive support for all of the major security algorithms and practices major security algorithms and practices in use todayin use today.NET can be tightly integrated with the .NET can be tightly integrated with the Windows Active DirectoryWindows Active Directory

Page 20: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

.NET Framework Architecture.NET Framework Architecture

Common Language Runtime(debug, exception, type checking, garbage collection, JIT compilation, etc.)

Framework Base Classes(IO, string, net, security, threading, text, reflection, collections, etc.)

Data and XML Classes(ADO.NET, SQL, XSLT, Xpath, XML, etc)

Web Services Web Forms Windows Forms

Windows Platform

.NET Framework

VEGAApplication

Page 21: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

What is the CLR?What is the CLR?

The CLR is the heart and soul of The CLR is the heart and soul of the .NET architecturethe .NET architecture

Analogous to Java’s JVMAnalogous to Java’s JVM

The CLR activates objects and:The CLR activates objects and:performs security checks on themperforms security checks on them

lays them out in memorylays them out in memory

executes themexecutes them

garbage collects themgarbage collects them

Page 22: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

The CLR vs. the JVMThe CLR vs. the JVM

Both are runtime infrastructures that Both are runtime infrastructures that abstract the underlying platformabstract the underlying platform

JVM supports any language that can be JVM supports any language that can be represented in its bytecoderepresented in its bytecode

JavaJava

Page 23: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

The CLR vs. the JVMThe CLR vs. the JVM

Both are runtime infrastructures that Both are runtime infrastructures that abstract the underlying platformabstract the underlying platform

JVM supports any language that can be JVM supports any language that can be represented in its bytecoderepresented in its bytecode

CLR supports any language that can be CLR supports any language that can be represented in its Common Intermediate represented in its Common Intermediate Language (CIL)Language (CIL)

C#, VB.NET, Managed C++, J#C#, VB.NET, Managed C++, J#

Page 24: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Which is better, CLR or JVM?Which is better, CLR or JVM?

Depends on who you askDepends on who you ask

The CLR is not and never has been an The CLR is not and never has been an interpreterinterpreter

In April 2003, a subset of the CLR known In April 2003, a subset of the CLR known as the Common Language Interface as the Common Language Interface (CLI) became an international standard(CLI) became an international standard

Projects are underway to develop CLRs Projects are underway to develop CLRs for Linux and Unix and possibly even for Linux and Unix and possibly even Mac OS XMac OS X

Page 25: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Back to the CLRBack to the CLR

The CLR manages the execution of code The CLR manages the execution of code in the .NET environmentin the .NET environmentThe CLR:The CLR:

loads required classesloads required classesperforms Just-In-Time (JIT) compilationperforms Just-In-Time (JIT) compilationenforces securityenforces securityand much more…and much more…

Units of deployment are Portable Units of deployment are Portable Executables (PEs) aka assembliesExecutables (PEs) aka assembliesPEs can be DLLs or EXEsPEs can be DLLs or EXEs

Page 26: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

What is a .NET Assembly?What is a .NET Assembly?

Assemblies consist of code and Assemblies consist of code and metadatametadata

Code in an assembly is in the form of the Code in an assembly is in the form of the Common Intermediate Language (CIL)Common Intermediate Language (CIL)

Metadata makes it all work togetherMetadata makes it all work together

Page 27: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

.NET Assembly.NET Assembly

Cobol .NETSource Code

Perl .NETSource Code

Managed C++Source Code

J#Source Code

VB .NETSource Code

Cobol .NETCompiler

Perl .NETCompiler

Managed C++Compiler

J#Compiler

VB .NETCompiler

C#Compiler

C#Source Code

.NETAssembly

(DLL or EXE)

CILand

Metadata

Compilation

Page 28: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

.NET Metadata.NET Metadata

In .NET, metadata includes:In .NET, metadata includes:type definitionstype definitions

version informationversion information

external assembly referencesexternal assembly references

other standardized informationother standardized information

Page 29: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

.NET Metadata.NET Metadata

In .NET, metadata includes:In .NET, metadata includes:

.NET uses metadata to describe an .NET uses metadata to describe an assembly in detail, including:assembly in detail, including:

identity descriptionidentity description

types that it referencestypes that it references

types that it exportstypes that it exports

security requirements for executionsecurity requirements for execution

Page 30: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

.NET Metadata.NET Metadata

In .NET, metadata includes:In .NET, metadata includes:

.NET uses metadata to describe an .NET uses metadata to describe an assembly in detail, including:assembly in detail, including:

Metadata provides enough information Metadata provides enough information for any runtime tool or program to find for any runtime tool or program to find out everything that is needed for out everything that is needed for component integrationcomponent integration

Page 31: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

.NET Consumers of Metadata.NET Consumers of Metadata

CLR relies on metadata to support CLR relies on metadata to support runtime featuresruntime features

verificationverification

security enforcementsecurity enforcement

cross-context marshallingcross-context marshalling

memory layoutmemory layout

executionexecution

Page 32: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

.NET Consumers of Metadata.NET Consumers of Metadata

CLR relies on metadata to support CLR relies on metadata to support runtime featuresruntime features

Class Loader of CLR uses metadata to Class Loader of CLR uses metadata to find and load .NET classesfind and load .NET classes

JIT compiler uses metadata to compile JIT compiler uses metadata to compile CIL codeCIL code

Various tools use metadata to support Various tools use metadata to support integration (e.g., Intellisenseintegration (e.g., Intellisense®®))

Page 33: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Type Libraries on SteroidsType Libraries on Steroids

Any application, tool, or utility that can Any application, tool, or utility that can read metadata from a .NET assembly read metadata from a .NET assembly can make use of that assembly.can make use of that assembly.

Metadata ensures language Metadata ensures language interoperabilityinteroperability

Page 34: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Single-File & Multi-File AssembliesSingle-File & Multi-File Assemblies

Assemblies composed of a single *.dll or *.exe Assemblies composed of a single *.dll or *.exe are single-file assembliesare single-file assemblies

Multi-file assemblies are composed of Multi-file assemblies are composed of numerous .NET *.dlls or *.exes termed numerous .NET *.dlls or *.exes termed modulesmodules

Primary module contains the assembly Primary module contains the assembly manifestmanifest

Other modules contain module-level manifestOther modules contain module-level manifest

Primary module documents the set of Primary module documents the set of “secondary” modules within the assembly“secondary” modules within the assembly

Page 35: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

The .NET Runtime EnvironmentThe .NET Runtime Environment

The term runtime can be understood as The term runtime can be understood as a collection of external services that are a collection of external services that are required to execute a given compiled required to execute a given compiled unit of code.unit of code.

MFC requires mfc42.dllMFC requires mfc42.dll

VB6 requires msvbvm60.dllVB6 requires msvbvm60.dll

Java requires the JVMJava requires the JVM

.NET requires the CLR.NET requires the CLR

Page 36: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

The .NET CLRThe .NET CLR

Crux of the CLR is the Common Object Crux of the CLR is the Common Object Runtime Execution Engine (mscoree.dll)Runtime Execution Engine (mscoree.dll)

f

Cobol .NETSource Code

Perl .NETSource Code

Managed C++Source Code

J#Source Code

VB .NETSource Code

Cobol .NETCompiler

Perl .NETCompiler

Managed C++Compiler

J#Compiler

VB .NETCompiler

C#Compiler

C#Source Code

.NETAssembly

(DLL or EXE)

CILand

Metadata

CLR

ClassLoader

JITCompiler

PlatformDependentExecutableInstructions

Compilation Runtime – mscoree.dll

Page 37: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

CLR ExecutionCLR ExecutionVEGA

Class Loader(Locates class & entry point, caches type information,

allocates memory, initializes statics, instantiates object)

CLR’s Common Object Runtime Execution Engine

Verifier(Verifies that metadata is well formed, CIL code is type safe, caches verified status)

JIT Compilation

Me

tho

dIn

vo

ca

tio

n

JIT Compiler(Occurs on a method by method basis, is optimized for host platform,

occurs on first method invocation only)

Execution Support and Management(Garbage Collector, Security Engine, Code Manager

Exception Manager, Thread Support, etc)

Page 38: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Visual Studio 2005 & Visual Studio 2005 & the IDEthe IDE

Page 39: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Visual Studio 2005 & the IDEVisual Studio 2005 & the IDE

Solution ExplorerSolution Explorer

Class ViewClass View

Object BrowserObject Browser

Code Definition WindowCode Definition Window

Code RefactoringCode Refactoring

IntellisenseIntellisense®®

ToolbarsToolbars

DebuggingDebugging

Page 40: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

What is C#What is C#

New programming language developed New programming language developed by Microsoft for .NETby Microsoft for .NET

Syntax is very similar to JavaSyntax is very similar to Java

Just as Java is in many ways a cleaned-Just as Java is in many ways a cleaned-up version of C++, C# can be viewed as up version of C++, C# can be viewed as a cleaned-up version of Java a cleaned-up version of Java

C# is managed codeC# is managed code

Page 41: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Anatomy of a C# ProgramAnatomy of a C# Program

A C# application must have one PE that A C# application must have one PE that is an .exe; it can have any number of is an .exe; it can have any number of PEs that are .dllsPEs that are .dlls

By convention, C# source code files By convention, C# source code files have a .cs extensionhave a .cs extension

All program logic must be contained All program logic must be contained within a type definitionwithin a type definition

Page 42: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Anatomy of a C# ProgramAnatomy of a C# Program

Every C# application must contain a Every C# application must contain a class defining a Main() methodclass defining a Main() method

Main() must be public and staticMain() must be public and static

Main() typically does very little other than Main() typically does very little other than start things upstart things up

Page 43: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Rules of the RoadRules of the Road

Everything must exist within a Everything must exist within a namespacenamespace

“ “enum”s and “struct”s can be defined enum”s and “struct”s can be defined outside of a class but must be scoped within outside of a class but must be scoped within a namespacea namespace

Object visibility should always be Object visibility should always be specified. If one is not provided the specified. If one is not provided the compiler will assign a defaultcompiler will assign a default

Page 44: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Data in C#Data in C#

There are NO POINTERs in C# (per se)There are NO POINTERs in C# (per se)ALL reference type objects must be “new”ed ALL reference type objects must be “new”ed and are allocated on the managed heapand are allocated on the managed heap

Objects are NEVER “delete”ed; the garbage Objects are NEVER “delete”ed; the garbage collector will take care of thatcollector will take care of that

Scope resolution operator is always a Scope resolution operator is always a period (“.”) irrespective of the object’s period (“.”) irrespective of the object’s location (stack or heap)location (stack or heap)

Pointers can be used in “unsafe” code Pointers can be used in “unsafe” code sections -- but let’s not go there!sections -- but let’s not go there!

Page 45: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Data in C#Data in C#

Class attributes are always initialized to Class attributes are always initialized to a safe default valuea safe default value

Local variables within a member scope Local variables within a member scope are not initializedare not initialized

the compiler will force assignment before the compiler will force assignment before they can be usedthey can be used

there is one exception to thisthere is one exception to this

Page 46: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

The Mother of All ObjectsThe Mother of All Objects

When you create a class that does not When you create a class that does not explicitly specify a base class, you explicitly specify a base class, you implicitly derive from System.Objectimplicitly derive from System.ObjectSystem.Object provides some basic System.Object provides some basic functionality for all C# classesfunctionality for all C# classes

Example: ToString() returns a string Example: ToString() returns a string representation of the given objectrepresentation of the given object

Some functionality can be overridden: Some functionality can be overridden: Equals, GetHashCode, ToString, and Equals, GetHashCode, ToString, and FinalizeFinalize

Page 47: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Class Objects in C#Class Objects in C#

Class objects are either “public” or Class objects are either “public” or “internal”“internal”

Every C# class gets a “free” default Every C# class gets a “free” default constructorconstructor

ensures that all member data is set to an ensures that all member data is set to an appropriate default valueappropriate default value

value-type data are initialized with a default, value-type data are initialized with a default, safe value (e.g., int and doubles are safe value (e.g., int and doubles are initialized to 0)initialized to 0)

reference-type data are initialized to nullreference-type data are initialized to null

Page 48: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Class Objects in C#Class Objects in C#

As soon as you define a custom constructor, As soon as you define a custom constructor, the default constructor is removedthe default constructor is removed

class loader however still initializes attributes to class loader however still initializes attributes to default valuesdefault values

if a default constructor is still needed, you will have if a default constructor is still needed, you will have to provide it.to provide it.

There are no “friend” classes. Visibility There are no “friend” classes. Visibility modifier “internal” is similar but not the samemodifier “internal” is similar but not the same

Class attributes can be initialized by Class attributes can be initialized by assignment when declaredassignment when declared

Page 49: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Class Objects in C#Class Objects in C#

A class can be declared as “static”A class can be declared as “static”In fact the class that contains Main() must In fact the class that contains Main() must be declared staticbe declared static

Typically one .cs file contains the Typically one .cs file contains the declaration of one C# classdeclaration of one C# class

C# classes can span multiple files using C# classes can span multiple files using the “partial” modifierthe “partial” modifier

Page 50: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Inheritance in C#Inheritance in C#

Much the same as in C++Much the same as in C++

Multiple inheritance is not supportedMultiple inheritance is not supported

You can however implement as many You can however implement as many interfaces as you likeinterfaces as you like

Abstract methods and classes must be Abstract methods and classes must be marked as such using the keyword marked as such using the keyword “abstract”“abstract”

Page 51: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Loops and Branching in C#Loops and Branching in C#

““for”, “while”, “do … while”, “if … else” all for”, “while”, “do … while”, “if … else” all work as in C/C++work as in C/C++

““foreach” is new to C#foreach” is new to C#Allows interation over items in a collection Allows interation over items in a collection or arrayor array

No need to test for upper and lower limitsNo need to test for upper and lower limits

Example:Example:string[] colorSchemes = { “Day”, “Dusk”, “Night” };foreach (string s in colorSchemes { … }

Page 52: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Loops and Branching in C#Loops and Branching in C#

““switch” works as in C/C++ with a couple switch” works as in C/C++ with a couple of exceptions…of exceptions…

each “case” must have a terminating “break” each “case” must have a terminating “break” unless there is no code between “case”sunless there is no code between “case”s

the “switch” statement can evaluate stringsthe “switch” statement can evaluate strings

Page 53: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Accessors and MutatorsAccessors and Mutators

Object oriented encapsulation Object oriented encapsulation Attributes should not be directly accessibleAttributes should not be directly accessible

Accessors should be provided to retrieve Accessors should be provided to retrieve statestate

Mutators should be provided to set stateMutators should be provided to set state

Traditional approach:Traditional approach:GetXXX() or get_XXX()GetXXX() or get_XXX()

SetXXX() or set_XXX()SetXXX() or set_XXX()

C# uses propertiesC# uses properties

Page 54: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

C# PropertiesC# Properties

Example:Example:

““value” is value” is notnot a keyword but rather a a keyword but rather a contentual keywordcontentual keyword

Properties feel more “natural”Properties feel more “natural”Instead of: Instead of:

We use: We use:

private double lat;public double Lat {get{return lat;} set{lat=value;}}

double myLat = gsoPoint.get_Lat();

double myLat = gsoPoint.Lat;

Page 55: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

C# PropertiesC# Properties

Accessors and mutators can have Accessors and mutators can have different visibility:different visibility:

How would you make a property read or How would you make a property read or write only?write only?

Properties can be “static”Properties can be “static”

private double lat;public double Lat {get{return lat;} protected set{lat=value;}}

Page 56: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

C# Casting RulesC# Casting Rules

Any data type can be stored in an Any data type can be stored in an “object” variable:“object” variable:

Any subclass object can be stored in a Any subclass object can be stored in a superclass object variable:superclass object variable:

object shape = new GSOLine();

GSOShape shape = new GSOLine();

Page 57: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

C# Casting RulesC# Casting Rules

How do we get it back?How do we get it back?

What if “shape” is not a “GSOLine”?What if “shape” is not a “GSOLine”?InvalidCastException is thrown at runtimeInvalidCastException is thrown at runtime

GSOLine line = (GSOLine)shape;

Page 58: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

C# Casting RulesC# Casting Rules

Is there another way?Is there another way?

What if “shape” is not a “GSOLine”?What if “shape” is not a “GSOLine”?The “as” operation will return nullThe “as” operation will return null

GSOLine line = shape as GSOLine;

Page 59: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

C# Casting RulesC# Casting Rules

Which is better?Which is better?Exceptions are expensiveExceptions are expensive

Can we tell before we cast?Can we tell before we cast?if (shape is GSOLine)

Page 60: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Anatomy of a C# Anatomy of a C# Source Code FileSource Code File

Page 61: An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc

Building a Simple GUI Building a Simple GUI in Visual Studio 2005in Visual Studio 2005