An Introduction to.NET Keith Mulkey Senior Software Engineer SFA, Inc.
Agenda What is.NET? What is the Common Language Runtime (CLR)? Introduction to Visual Studio 2005 and the IDE Introduction to C#
What is.NET? According to Microsoft,.NET is “the Microsoft Web services strategy to connect information, people, systems, and devices through software” What does this mean to the average developer? ABSOLUTELY NOTHING!
What is.NET to the average developer? A Framework that provides: an easy to use development environment a multitude of libraries that make our job easier including distributed processing cross-language interoperability a runtime environment that will manage resources with no assistance from us tight integration with the operating system easy integration of third party libraries
.NET Framework Design Features Component (Assembly) Infrastructure Language Integration Distributed Computing Simplified Development Simplified Deployment ReliabilitySecurity
Component Infrastructure.NET classes are ready to be used at the binary level.NET assemblies do not have to be registered in the Windows registry No special “plumbing” code is required for component registration, class factories, component lifetime or dynamic binding
Language Integration Language Independence vs. Language Integration COM supported language independence Component can be written in any language Component must meet COM specification rules Supports binary reuse DOES NOT allow COM component code reuse DOES NOT support COM component class extension DOES NOT allow catching exceptions thrown by COM component
Language Integration Language Independence vs. Language Integration COM supported language independence.NET supports language integration Components can be written in any supported language (C#, VB, Managed C++, J#) The adherence to a common specification is taken care of by.NET DOES allow.NET component code reuse DOES support.NET component class extension DOES allow catching exceptions thrown by.NET components
Language Integration Language Independence vs. Language Integration COM supported language independence.NET supports language integration Made possible by the Common Type System (CTS) Everything in CTS derives from System.Object CTS supports concepts of classes, interfaces, delegates, reference types, and value types CTS supports base system types such as integer, double, string, file manipulation
Language Integration Language Independence vs. Language Integration COM supported language independence.NET supports language integration Common Language Specification (CLS) provides minimum set of rules All.NET language compilers must meet CLS and generate code that conforms to CTS This allows different.NET languages to be used in the same applicaton
Distributed Computing COM supported distributed computing using DCOM Due to embedded IP address, DCOM would not work through firewalls and NAT.NET uses industry standard SOAP to interoperate on the Internet.NET Remoting uses a CORBA-like approach for distributed computing
Simplified Development Every.NET language uses the same library of.NET components The API to the.NET library of components is always the same Integrating with.NET components is always the same The same IDE is used for all languages Intellisense ® works the same for all languages The build process is always the same
Simplified Deployment No more “DLL Hell” Shared DLLs are registered with the Global Assembly Cache (GAC) Multiple versions of the same DLL can co- exist Applications are tightly bound to a particular DLL version
Simplified Deployment No more “DLL Hell” DLL Registry entries eliminated References and dependencies stored in DLL manifest Private DLLs are found using logical paths or XML based configuration files Shared (public) DLLs are found using the GAC Both are found at runtime
Simplified Deployment No more “DLL Hell” DLL Registry entries eliminated “Zero-Impact” installation and removal.NET DLLs are not entered into registry upon installation Hence no need to remove from registry upon uninstall Installation and removal can be accomplished with copy and delete
Simplified Deployment No more “DLL Hell” DLL Registry entries eliminated “Zero-Impact” installation and removal Web, network, and CD deployment all supported within Visual Studio 2005
Reliability Type safety CLR must recognize and verify types before they are loaded and executed Helps prevent buffer overruns which can be a source of program errors and security weaknesses
Reliability Type safety Common error handling Automatic memory management
Security.NET can protect access to specific parts of executable code.NET supports strong naming of assemblies to help prevent pirating and tampering.NET has extensive support for all of the major security algorithms and practices in use today.NET can be tightly integrated with the Windows Active Directory
.NET Framework Architecture Application
What is the CLR? The CLR is the heart and soul of the.NET architecture Analogous to Java’s JVM The CLR activates objects and: performs security checks on them lays them out in memory executes them garbage collects them
The CLR vs. the JVM Both are runtime infrastructures that abstract the underlying platform JVM supports any language that can be represented in its bytecode Java
The CLR vs. the JVM Both are runtime infrastructures that abstract the underlying platform JVM supports any language that can be represented in its bytecode CLR supports any language that can be represented in its Common Intermediate Language (CIL) C#, VB.NET, Managed C++, J#
Which is better, CLR or JVM? Depends on who you ask The CLR is not and never has been an interpreter In April 2003, a subset of the CLR known as the Common Language Interface (CLI) became an international standard Projects are underway to develop CLRs for Linux and Unix and possibly even Mac OS X
Back to the CLR The CLR manages the execution of code in the.NET environment The CLR: loads required classes performs Just-In-Time (JIT) compilation enforces security and much more… Units of deployment are Portable Executables (PEs) aka assemblies PEs can be DLLs or EXEs
What is a.NET Assembly? Assemblies consist of code and metadata Code in an assembly is in the form of the Common Intermediate Language (CIL) Metadata makes it all work together
.NET Assembly
.NET Metadata In.NET, metadata includes: type definitions version information external assembly references other standardized information
.NET Metadata In.NET, metadata includes:.NET uses metadata to describe an assembly in detail, including: identity description types that it references types that it exports security requirements for execution
.NET Metadata In.NET, metadata includes:.NET uses metadata to describe an assembly in detail, including: Metadata provides enough information for any runtime tool or program to find out everything that is needed for component integration
.NET Consumers of Metadata CLR relies on metadata to support runtime features verification security enforcement cross-context marshalling memory layout execution
.NET Consumers of Metadata CLR relies on metadata to support runtime features Class Loader of CLR uses metadata to find and load.NET classes JIT compiler uses metadata to compile CIL code Various tools use metadata to support integration (e.g., Intellisense ® )
Type Libraries on Steroids Any application, tool, or utility that can read metadata from a.NET assembly can make use of that assembly. Metadata ensures language interoperability
Single-File & Multi-File Assemblies Assemblies composed of a single *.dll or *.exe are single-file assemblies Multi-file assemblies are composed of numerous.NET *.dlls or *.exes termed modules Primary module contains the assembly manifest Other modules contain module-level manifest Primary module documents the set of “secondary” modules within the assembly
The.NET Runtime Environment The term runtime can be understood as a collection of external services that are required to execute a given compiled unit of code. MFC requires mfc42.dll VB6 requires msvbvm60.dll Java requires the JVM.NET requires the CLR
The.NET CLR Crux of the CLR is the Common Object Runtime Execution Engine (mscoree.dll)
CLR Execution
Visual Studio 2005 & the IDE
Solution Explorer Class View Object Browser Code Definition Window Code Refactoring Intellisense ® ToolbarsDebugging
What is C# New programming language developed by Microsoft for.NET Syntax is very similar to Java Just as Java is in many ways a cleaned- up version of C++, C# can be viewed as a cleaned-up version of Java C# is managed code
Anatomy of a C# Program A C# application must have one PE that is an.exe; it can have any number of PEs that are.dlls By convention, C# source code files have a.cs extension All program logic must be contained within a type definition
Anatomy of a C# Program Every C# application must contain a class defining a Main() method Main() must be public and static Main() typically does very little other than start things up
Rules of the Road Everything must exist within a namespace “enum”s and “struct”s can be defined outside of a class but must be scoped within a namespace “enum”s and “struct”s can be defined outside of a class but must be scoped within a namespace Object visibility should always be specified. If one is not provided the compiler will assign a default
Data in C# There are NO POINTERs in C# (per se) ALL reference type objects must be “new”ed and are allocated on the managed heap Objects are NEVER “delete”ed; the garbage collector will take care of that Scope resolution operator is always a period (“.”) irrespective of the object’s location (stack or heap) Pointers can be used in “unsafe” code sections -- but let’s not go there!
Data in C# Class attributes are always initialized to a safe default value Local variables within a member scope are not initialized the compiler will force assignment before they can be used there is one exception to this
The Mother of All Objects When you create a class that does not explicitly specify a base class, you implicitly derive from System.Object System.Object provides some basic functionality for all C# classes Example: ToString() returns a string representation of the given object Some functionality can be overridden: Equals, GetHashCode, ToString, and Finalize
Class Objects in C# Class objects are either “public” or “internal” Every C# class gets a “free” default constructor ensures that all member data is set to an appropriate default value value-type data are initialized with a default, safe value (e.g., int and doubles are initialized to 0) reference-type data are initialized to null
Class Objects in C# As soon as you define a custom constructor, the default constructor is removed class loader however still initializes attributes to default values if a default constructor is still needed, you will have to provide it. There are no “friend” classes. Visibility modifier “internal” is similar but not the same Class attributes can be initialized by assignment when declared
Class Objects in C# A class can be declared as “static” In fact the class that contains Main() must be declared static Typically one.cs file contains the declaration of one C# class C# classes can span multiple files using the “partial” modifier
Inheritance in C# Much the same as in C++ Multiple inheritance is not supported You can however implement as many interfaces as you like Abstract methods and classes must be marked as such using the keyword “abstract”
Loops and Branching in C# “for”, “while”, “do … while”, “if … else” all work as in C/C++ “foreach” is new to C# Allows interation over items in a collection or array No need to test for upper and lower limits Example: string[] colorSchemes = { “Day”, “Dusk”, “Night” }; foreach (string s in colorSchemes { … }
Loops and Branching in C# “switch” works as in C/C++ with a couple of exceptions… each “case” must have a terminating “break” unless there is no code between “case”s the “switch” statement can evaluate strings
Accessors and Mutators Object oriented encapsulation Attributes should not be directly accessible Accessors should be provided to retrieve state Mutators should be provided to set state Traditional approach: GetXXX() or get_XXX() SetXXX() or set_XXX() C# uses properties
C# Properties Example: “value” is not a keyword but rather a contentual keyword Properties feel more “natural” Instead of: We use: private double lat; public double Lat {get{return lat;} set{lat=value;}} double myLat = gsoPoint.get_Lat(); double myLat = gsoPoint.Lat;
C# Properties Accessors and mutators can have different visibility: How would you make a property read or write only? Properties can be “static” private double lat; public double Lat {get{return lat;} protected set{lat=value;}}
C# Casting Rules Any data type can be stored in an “object” variable: Any subclass object can be stored in a superclass object variable: object shape = new GSOLine(); GSOShape shape = new GSOLine();
C# Casting Rules How do we get it back? What if “shape” is not a “GSOLine”? InvalidCastException is thrown at runtime GSOLine line = (GSOLine)shape;
C# Casting Rules Is there another way? What if “shape” is not a “GSOLine”? The “as” operation will return null GSOLine line = shape as GSOLine;
C# Casting Rules Which is better? Exceptions are expensive Can we tell before we cast? if (shape is GSOLine)
Anatomy of a C# Source Code File
Building a Simple GUI in Visual Studio 2005