Blue Border - www.chilliPower.com
Download
Report
Transcript Blue Border - www.chilliPower.com
Introduction to the .NET Framework
and C#
NETbuilder - March 2009
Louis Botterill
Agenda
The .NET Framework and C# - an introduction
Origins and time-line
Versions and platform variants
.NET high level features
C# overview
C# examples and language features
Tools and GUI builder (quick demo)
Future
Resources and further reading
2
(Not covered in this presentation)
Other languages, VB etc
Server side programming ASP.NET
WCF, WPF
Silverlight, XAML and XBAP
LINQ, LINQ to SQL, LINQ to XML etc
Functional Programming
ClickOnce etc
* Can be covered in further presentations...
3
Origins
From Microsoft, described as a “Software Framework”
Microsoft started development on the .NET Framework in the late
1990s originally under the name of Next Generation Windows
Services (NGWS). By late 2000 the first beta versions of .NET 1.0
were released
The first release of the .NET Framework was on 13 February 2002
4
Versions
Version
Version
Version Number
Release Date Visual Studio
1.0
1.0.3705.0
2002-02-13
VS .NET
1.1
1.1.4322.573
2003-04-24
VS .NET 2003
2.0
2.0.50727.42
2005-11-07
VS 2005
3.0
3.0.4506.30
Server 2008
2006-11-06
3.5
3.5.21022.8
Windows 7
2007-11-19
Windows
Server 2003
Vista,
VS 2008
5
.NET Framework / CLR
.NET
CLR
1
1
1.1
1
2
2
3
2
3.5
2
4
4? TBA
6
Main variants
.NET CLR – Desktop applications
.NET CF – Mobile Applications
ASP.NET – Server (web) applications
7
Overview features
Virtual machine based
Multi-platform (various Microsoft platforms)
Multiple language support
VM Garbage collection
Byte-code is always compiled before
execution, either Just In Time (JIT) or in
advance of execution using the ngen.exe
utility.
8
Language Support (Official)
C#
VB (Visual Basic)
XAML
JScript
Powershell
9
Language support (Unofficial)
IronPython
Oxygene
IronRuby
Nemerle
Boo
Phalanger
IronLisp
F#
M
And others...
10
Some Basic terminology
ASP – Active Server Pages
CIL – Common Intermediate Language (formerly MSIL)
CLI – Common Language Infrastructure
CLR – common language runtime
LINQ – Language Integrated Query
WCF – Windows Communication Foundation
WF – Windows workflow Foundation
WPF – Windows Presentation Foundation
XAML - Extensible Application Markup Language
XBAP – XAML Browser APlication
11
Framework Stack
12
Some Key concepts
Assemblies – are packages of code
Managed code - is computer program code
that executes under the management of a
virtual machine, unlike unmanaged code,
which is executed directly by the computer's
CPU.
Debug and release builds
13
Assemblies
In the Microsoft .NET framework, an assembly is a partially compiled code library for
use in deployment, versioning and security.
In the Microsoft Windows implementation of .NET, an assembly is a PE (portable
executable) file for Windows GUI on Intel x86. There are two types:
process assemblies (EXE)
library assemblies (DLL)
A process assembly represents a process which will use classes defined in library
assemblies.
14
The Garbage Collector
The .NET Garbage Collector (GC) is a nondeterministic, compacting, mark-and-sweep
garbage collector.
The GC runs only when a certain amount of
memory has been used or there is enough
pressure for memory on the system.
15
Language - C#
C# (pronounced C Sharp) is a multi-paradigm programming
language that encompasses functional, imperative, generic, objectoriented (class-based), and component-oriented programming
disciplines.
It was developed by Microsoft as part of the .NET initiative and later
approved as a standard by ECMA (ECMA-334) and ISO (ISO/IEC
23270). C# is one of the programming languages supported by the
.NET Framework's Common Language Runtime.
Designed to be “Very Easy To Learn!”
16
Key Language Features
Object orientated & Component orientated
Imperative, Generic
Bounds checking
Run time type information
Pass by value and Pass by reference
Functions as first class objects
Pre-processor support
17
Key Language Features (2)
Strings are immutable
Single inheritance for classes
Multiple inheritance for interfaces
Namespaces – like Java Packages (but much
more flexible)
C# Requires “definite assignment”
18
Ubiquitous Hello World!
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine(“Hello
World!”);
}
}
Main - entry point, has two overloads Main() and Main(string[])
System namespace includes many common objects
Arrays indexed using []
19
Hello World! v2
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Hello ” + args[0]);
}
}
}
Console.ReadKey();
using – bring a namespace into scope
namespace – define a named scope for a block
20
The System namespace
System – contains .NET types, Garbarge collector,
Environment, Console
System.Collections & System.Collections.Generic collection classes
System.Linq – Language Integrated Query
System.Text – Encoders and decoders, .Regex, StringBuilder
etc
System.IO – File and Directory access, Readers and Writers
System.Net – HTTP, FTP, sockets etc
System.Threading – Thread related stuff
21
Numeric types
Type Size
Signed
byte
8
no
ushort
16
no
uint
32
no
ulong
64
no
sbyte 8
yes
short 16
yes
int
yes
32
long
64
float 32
yes
yes
double
64
yes
decimal
128
yes
22
Type aliases
Primitive types have keyword aliases, e.g.
string alias for System.String
int alias for System.Int32
And so on...
23
Foreach
using System;
class Foreach
{
static void Main(string[] args)
{
foreach (string arg in args)
{
Console.WriteLine(arg);
}
}
}
24
Properties
class MyClass
{
private int x;
public int X
{
get
{
return x;
}
set
{
if (x < 100)
{
x = value;
}
else
{
throw new ArgumentOutOfRange("x");
}
}
}
}
public int Y { get; set; };
25
Indexers (indexed properties)
public class MyList
{
private string[] items;
public string this[int index] {
set {
return items[index];
}
}
}
set {
items[index] = value;
}
26
Checked Integer arithmetic
using System;
class Overflow
{
static void Main()
{
try
{
int x = int.MaxValue + 1;
// wraps to int.MinValue
int y = checked(int.MaxValue + 1); // throws
}
}
}
catch (OverflowException caught)
{
Console.WriteLine(caught);
}
27
Value types
Primitive types, enums, structs
//enumeration types
enum Suit { Hearts, Clubs, Diamonds, Spades }
// structure types
struct Rectangle
{
int x1, y1, x2, y2;
}
struct – no inheritance!
struct members are private by default
struct can have constructors
struct can have static methods and fields
readonly and const keywords
28
Nullable types
Provides support for nullable value types
Example – Nullable<Int32>
The syntax T? is shorthand for System.Nullable<T>
.GetValueOrDefault(); returns value or default value for type
Use the .HasValue and .Value read-only properties to test for null
and retrieve the value
The Value property returns a value if one is assigned, otherwise a
System.InvalidOperationException is thrown
Use the ?? operator to assign a default value that will be applied
when a nullable type whose current value is null is assigned to a
non-nullable type, for example int? x = null; int y = x ?? -1;
29
Enumerations (Enums)
Value objects
Strongly typed
Can specific underlying types and values
enum DayOfWeek : int
{
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
Saturday = 32.
Sunday = 64
Weekend = Saturday | Sunday
}
30
Reference types
Class class
Interface interface
Arrays string[]
Delegates delegate
Foo: Bar, IFoo {...}
IFoo: IBar
{...}
strings = new string[10];
void SomeDelegate();
Can all be Null!
31
Case statements
No default fall-through
Fall through Only on empty cases
Can switch on non-numeric types i.e. string
Use of Goto (yes really!) can be used to mimic
case fall-through if necessary
32
Some (more unusual) Keywords
sealed – like Java final, a class cannot be
sub-classed
partial – a class is defined across multiple
files/blocks.
static – can have static classes
33
Inheritance – virtual, override and
new
In a superclass, if a method is not
polymorphic, then in its subclasses use the
keyword new to provide a new definition that
hides the original.
In a superclass, if a method is polymorphic,
use the keyword virtual. In its subclasses, use
the keyword override to provide a new
polymorphic overridden version.
* Virtual methods must be explicitly
overridden *
34
Example constructor syntax
public class MyClass
{
public MyClass()
{
....
}
public MyClass(int x) : this()
{
...
}
public MyClass(int x, int y) : this(x)
{
....
}
}
35
Example inheritance syntax
public class MyClass : MyBaseClass, IMyInterface, IMyOtherInterface
{
public MyClass(int someValue) : base(someValue)
{
...
}
}
36
Destructors
public class MyClass : MyOtherClass
{
~MyClass()
{
Do some cleanup...;
}
}
Destructor as per constructor but with ~ prefix, i.e. name same
as class with no return
Converted into protected Finalize override
User never calls Finalize
37
Delegates
namespace System
{
public delegate void EventHandler(object sender, EventArgs sent);
...
}
namespace System.Windows.Forms
{
public class Button
{ ...
public event EventHandler Click;
}
}
using System.Windows.Forms;
class MyForm : Form
{ ...
private void initializeComponent()
{ ...
okButton = new Button("OK");
okButton.Click += new EventHandler(this.okClick); // create + attach
}
private void okClick(object sender, EventArgs sent)
{ ...
}
...
private Button okButton;
}
38
Actions and Functions
Declaire a routine with no return
Action<int, string> myFunc = (int v1, string s) => {
// Do some stuff...
};
Declaire a function with a return
var createForm = new Func<Form>(() => {
MyLovelyForm myForm = new MyLovelyForm();
return myForm;
});
39
Attributes
Can be attached to types and members
Consumed at run-time using reflection
Based on a class that inherits from Attribute
public
abstract class ServiceResponseBase
{
[XmlElement(ElementName = "result", Namespace =
"http://www.netbuilder.com/webtrader/common")]
public abstract ServiceResponseElement Result { get; set; }
[XmlElement(ElementName = "tss", Namespace =
"http://www.netbuilder.com/webtrader/marketdata/tss")]
public abstract TssElement TssElement { get; set; }
}
40
Preprocessor directives
#define, #undef
#if, #elif
#else, #endif
#region some region name
… code ...
#endregion
41
Tools and plug-ins
Visual Studio (Pro) 2008
Visual Studio Express Edition 2008 SP1
Resharper (JetBrains) - http://www.jetbrains.com/resharper/
DevExpress – http://www.devexpress.com/
Powerful, but not that cheap. Trials available,
we don't currently have any licenses.
tools and component libraries, Refactor and
CodeRush etc
Whole list of plug-ins on Wikipedia
http://en.wikipedia.org/wiki/List_of_Microsoft_Visual_Studio_Add-ins
42
Tools and plug-ins (2)
TestDriven.net – Nunit integration
VisualSVN – Tortoise SVN integration
43
Demo: Time to make a quick GUI
Show the tools in action
GUI builder
Editing properties and events
Adding event handlers
Running and debugging
44
The future, .NET 4.0
Enhanced parallel computing - multi-core and distributed support
IronPython and IronRuby support
F# support
Microsoft announced the .NET Framework 4.0 on September 29, 2008. While full details
about its feature set have yet to be released, some general information regarding the
company's plans have been made public. Some focus of this release are:
* Improve support for parallel computing, which target multi-core or distributed systems. To
this end, they plan to include technologies like PLINQ (Parallel LINQ), a parallel
implementation of the LINQ engine, and Task Parallel Library, which exposes parallel
constructs via method calls.
* Full support for IronPython, IronRuby, and F#.
* Support for a subset of the .NET Framework and ASP.NET with the "Server Core" variant
of Windows Server 2008 R2
45
.NET 4.0
Expected in 2010 (with Visual studio 2010)
Enhanced COM interoperability
Improved support for dynamic languages
46
Recommended Books
Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition Andrew Troelsen
Programming C#: Building .NET Applications with C# - Jesse
Liberty
http://www.amazon.co.uk/Programming-C-Building-NETApplications/dp/0596006993/ref=sr_1_1?ie=UTF8&s=books&qid=123
8583167&sr=8-1
Professional C# 2008 (Wrox Professional Guides)
http://www.amazon.co.uk/Pro-2008-NET-PlatformFourth/dp/1590598849/ref=sr_1_1?ie=UTF8&s=books&qid=12385832
56&sr=1-1
http://www.amazon.co.uk/Professional-C-2008-WroxGuides/dp/0470191376/ref=sr_1_3?ie=UTF8&s=books&qid=1238583
47
256&sr=1-3
C# in Depth: What you need to master C# 2 and 3 - Jon Skeet
Resources and further reading
http://msdn.microsoft.com/net
Programmers overview http://www.jaggersoft.com/pubs/AProgrammersOverviewOfCSharp.htm
Comparison of C# to Java PDF https://fhict.fontys.nl/Deeltijd/1JarigeStudies/CSA/Lesmateriaal/Week%201/Achterg
rond/Java%20and%20CSharp.pdf
C# for C++ programmers - http://andymcm.com/csharpfaq.htm#5.3
48