c# / vb.net language primer

29
1 C# / VB.NET Language Primer Chris J.T. Auld Microsoft MVP, Mobile Devices Managing Director Kognition Consulting Limited

Upload: sondra

Post on 10-Feb-2016

46 views

Category:

Documents


0 download

DESCRIPTION

C# / VB.NET Language Primer. Chris J.T. Auld Microsoft MVP, Mobile Devices Managing Director Kognition Consulting Limited. Objectives. Review/introduce important syntax elements of C# and VB.NET Discuss language elements commonly used with ASP.NET. Classes and Objects. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: C# / VB.NET Language Primer

1

C# / VB.NETLanguage Primer

Chris J.T. AuldMicrosoft MVP, Mobile DevicesManaging DirectorKognition Consulting Limited

Page 2: C# / VB.NET Language Primer

2

Objectives

• Review/introduce important syntax elements of C# and VB.NET

• Discuss language elements commonly used with ASP.NET

Page 3: C# / VB.NET Language Primer

3

Classes and Objects

• The CLR treats all types as classes no matter what language construct is used to produce them– The runtime knows how to load classes– The runtime knows how to instantiate objects– Every object is an instance of a class– Objects are typically created using the new operator

// make a new object of class DogDog fido = new Dog(); // use the new objectfido.Bark(); ' make a new object of class Dog

Dim fido As Dog = New Dog' use the new objectfido.Bark()

Page 4: C# / VB.NET Language Primer

4

public class Dog { int hairs = 17; public void Bark() { System.Console.Write("Woof."); System.Console.WriteLine("I have " + hairs + " hairs"); }}Public Class Dog Dim hairs As Integer = 17 Public Sub Bark() System.Console.Write("Woof.") System.Console.WriteLine("I have " & hairs & " hairs") End SubEnd Class

Defining a Class• The “class” keyword defines a new class

– The “public” keyword exposes it for external use

Page 5: C# / VB.NET Language Primer

5

public Public

C# VB.NET

internal Privatepublic Public*internal Friendprivate Private*

* VB.NET defaults to Public for methods and Private forfields declared using the Dim keyword

Type is visible everywhereType is only visible inside of assembly

Member is visible everywhereMember is only visible inside of assembly

Member is only visible inside of declaring type

Type

Member

Meaning

protected Protected Member is visible to type and deriving types only

Protection Keywords

• Classes and members can be hidden from clients

Page 6: C# / VB.NET Language Primer

6

Constructors• Classes can have constructors

– Constructors execute upon instantiation– Constructors can accept parameters– Constructors can be overloaded based on parameter lists

public class Patient { private string _name; private int _age; public Patient(string name, int age) { _name = name; _age = age; }}

Public Class Patient Private _name As String Private _age As Integer Public Sub New(name As String, age As Integer) _name = name _age = age End SubEnd Class

Page 7: C# / VB.NET Language Primer

7

Constructor Invocation

• Constructor automatically invoked when object created

Patient p = new Patient("fred", 60);

Dim p As Patient = New Patient("fred", 60)

Page 8: C# / VB.NET Language Primer

8

Multiple constructors

• Class can supply multiple overloaded constructors

public class Patient { /* ... */ public Patient(string name, int age) { _name = name; _age = age; }

public Patient(int age) : Patient("anonymous", age) {}

public Patient() : Patient("anonymous", -1) {}}

Public Class Patient '... Public Sub New(name As String, _ age As Integer) _name = name _age = age End Sub

Public Sub New(name As String) Me.New("anonymous", age) End Sub

Public Sub New() Me.New("anonymous", -1) End SubEnd Class

Page 9: C# / VB.NET Language Primer

9

namespace DM{ public class Foo { public static void Func() {} }}

using DM;using System;

DM.Foo.Func();Foo.Func();Console.WriteLine("Foo!");

Namespace DM Public Class Foo Public Shared Sub Func() End Sub End ClassEnd Namespace

Imports DMImports System

DM.Foo.Func()Foo.Func()Console.WriteLine("Foo!")

Namespaces

• A namespace defines a scope for naming

Page 10: C# / VB.NET Language Primer

10

public interface IDog { void Bark(int volume); bool Sit(); string Name { get; }}

Interfaces

Public Interface IDog Sub Bark(volume As Integer) Function Sit() As Boolean ReadOnly Property Name As StringEnd Interface

• An interface defines a set of operations w/ no implementation– Used to define a “contract” between client and object

Page 11: C# / VB.NET Language Primer

11

Implementing Interfacespublic class Poodle : IDog{ public void Bark(int volume) { ... } public bool Sit() { ... } public string Name { get { ... } }}

Public Class Mutt Implements IDog Sub Bark(volume As Integer) _ Implements IDog.Bark ... End Sub Function Sit() As Boolean _ Implements IDog.Sit ... End Function ReadOnly Property Name As String _ Implements IDog.Name Get ... End Get End PropertyEnd Class

Page 12: C# / VB.NET Language Primer

12

Using interfaces• Interfaces enable polymorphism

void PlayWithDog(IDog d){ d.Bark(100); if (d.Sit()) Console.Write("good dog, {0}!", d.Name);}// elsewhereIDog rex = new Mutt();IDog twiggie = new Poodle();PlayWithDog(rex);PlayWithDog(twiggie);

Sub PlayWithDot(d As IDog) d.Bark(100) If d.Sit() Then Console.Write("good dog, {0}!", d.Name)End Sub

' elsewhereDim rex As IDog = New Mutt()Dim twiggie As IDog = New Poodle()PlayWithDog(rex)PlayWithDog(twiggie)

Page 13: C# / VB.NET Language Primer

13

Sub Speak(a As Animal) a.Talk()End Sub

Binding

• Can call method through base class reference– must decide whether to call base or derived version– decision often called binding

which version?void Speak(Animal a) { a.Talk();}

Dog d = new Dog();Cat c = new Cat();

Speak(d);Speak(c);

Dim d As Dog = New Dog()Dim c As Cat = New Cat()

Speak(d)Speak(c)

Animal

Dog Cat

Page 14: C# / VB.NET Language Primer

14

Binding options

• Programmer chooses desired type of binding– when method called through base class reference

• Two options available– static– dynamic

Page 15: C# / VB.NET Language Primer

15

Static binding

• Static binding uses type of reference to determine method– default behavior

static binding callsAnimal.Talk

Sub Speak(a As Animal) a.Talk()End Sub

void Speak(Animal a) { a.Talk();}

Dog d = new Dog();Cat c = new Cat();

Speak(d);Speak(c);

Dim d As Dog = New Dog()Dim c As Cat = New Cat()

Speak(d)Speak(c)

Page 16: C# / VB.NET Language Primer

16

Overridable / virtual methods

• To make a method dynamically bound– mark as overridable/virtual in base class– use Overrides/override keyword in derived implementation

public class Animal { protected virtual void Talk() { /* generic */ }}public class Cat : Animal { protected override void Talk() { /* meow */ }}

Public Class Animal Protected Overridable Sub Talk() ' generic End SubEnd Class

Public Class Dog Inherits Animal Protected Overrides Sub Talk() ' woof End SubEnd Class

Page 17: C# / VB.NET Language Primer

17

Dynamic binding

• Dynamic binding uses type of object to determine method

dynamic binding calls

Dog.Talk or Cat.Talk

Sub Speak(a As Animal) a.Talk()End Sub

void Speak(Animal a) { a.Talk();}

Dog d = new Dog();Cat c = new Cat();

Speak(d);Speak(c);

Dim d As Dog = New Dog()Dim c As Cat = New Cat()

Speak(d)Speak(c)

Page 18: C# / VB.NET Language Primer

18

public class Person { int _Age; public int Age { get { return _Age; } set { _Age = value; } }}

Person p = new Person();p.Age = 33;Console.WriteLine(p.Age);

Public Class Person Dim _Age As Integer Property Age() As Integer Get Age = _Age End Get Set(ByVal Value As Integer) _Age = Value End Set End PropertyEnd Class

Imports SystemDim p As Person = New Personp.Age = 33Console.WriteLine(p.Age)

Properties

• A property is a method that’s used like a field

Page 19: C# / VB.NET Language Primer

19

[ ShowInToolbox(true) ]public class MyCtrl : WebControl { [Bindable(true), DefaultValue("")] [Category("Appearance")] public string Text { get { … } set { … } }}

<ShowInToolbox(True)> Public Class MyCtrl Inherits WebControl <Bindable(True), DefaultValue(""), _ Category("Appearance")> _ Property Text() As String Get ... End Get Set (ByVal Value as String) ... End Set End PropertyEnd Class

Attributes• An attribute provides extra info about a type or member

– Used by clients interested in the extra info, e.g. an IDE

Page 20: C# / VB.NET Language Primer

20

void Foo() { FileStream f; try { f = File.Open("s.bin"); f.Read(/*...*/); } catch (FileNotFoundException e) { Console.WriteLine(e.Message); } finally { f.Close(); }}

Sub Foo() Dim f As FileStream Try f = New File("s.bin") f.Read(...) Catch e As FileNotFoundException Console.WriteLine(e.Message) Finally f.Close() End TryEnd Sub

Exceptions• An exception is thrown when an error occurs

– A client can catch the exception– A client can let the exception through, but still do something

Page 21: C# / VB.NET Language Primer

21

Exception pattern

• Exceptions are a notification mechanism• Pattern:

– exception generated when condition detected– propagated back through the call chain– caught and handled at higher level

One() Two() Three() Divide()Main()

call sequence

problem occurs in Divide,search for error handlerunwinds call sequence

Page 22: C# / VB.NET Language Primer

22

Object disposal

• Many classes in the framework wrap unmanaged resources– Database connections– Transactions– Synchronization primitives– File handles– Etc.

• It is imperative that you release the resources wrapped by these classes as soon as possible– Do not wait for garbage collection

Page 23: C# / VB.NET Language Primer

23

IDisposable

• Classes indicate a desire for as-soon-as-possible-cleanup by implementing IDisposable– Has one method named Dispose

• Common pattern - call Dispose in finally block– Guarantees cleanup even with exception

void DoDbWork(string dsn) { SqlConnection conn; conn = new SqlConnection(dsn); try { conn.Open(); // db work here } finally { conn.Dispose(); }}

Sub DoDbWork(dsn As String) Dim conn As SqlConnection conn = New SqlConnection(dsn) Try ' db work here Finally f.Dispose() End TryEnd Sub

Page 24: C# / VB.NET Language Primer

24

void DoDbWork(string dsn) { using( SqlConnection conn = new SqlConnection(dsn) ) { // do db work } // IDisposable.Dispose called here automatically}

C# using construct

void DoDbWork(string dsn){ SqlConnection conn = new SqlConnection(dsn); try { // do db work } finally { if( conn != null ) ((IDisposable)conn).Dispose(); } }}

Compiler translatescode into this…

Your write this…

Page 25: C# / VB.NET Language Primer

25

public delegate void ClickDelegate();

public class Button { public event ClickDelegate Click; public void Push() { if (Click != null) Click(); }} public class App {

public static void OnClick() { Console.WriteLine("Button clicked!"); } public static void Main() { Button b = new Button(); b.Click += new ClickDelegate(OnClick); b.Push(); }}

Delegates and Events in C#

• An event notifies clients of interesting things in the object– A delegate provides the signature of the event

Page 26: C# / VB.NET Language Primer

26

Delegates and Events in VB.NET (Dynamic binding syntax)

Public Delegate Sub ClickDelegate

Public Class ButtonPublic Event Click As ClickDelegate

Sub PushRaiseEvent Click

End SubEnd Class Public Class Class1

Public Sub OnClick()Console.WriteLine("Button clicked!")

End SubPublic Shared Sub Main() Dim b As Button = New Button()

AddHandler b.Click, _ New ClickDelegate(AddressOf OnClick) '... b.Push()End Sub

End Class

Page 27: C# / VB.NET Language Primer

27

Public Delegate Sub ClickDelegate

Public Class ButtonPublic Event Click As ClickDelegate

Sub PushRaiseEvent Click

End SubEnd Class

Public Class Class1 Dim WithEvents b As Button = New Button() Public Sub OnClick() Handles b.Click Console.WriteLine("Button clicked!") End Sub '...End Class

Delegates and Events in VB.NET(static binding syntax)

Page 28: C# / VB.NET Language Primer

28

void Foo() { FileStream f; try { f = File.Open("s.bin"); f.Read(/*...*/); } catch (FileNotFound e) { Console.WriteLine(e.Message); } finally { f.Close(); }}

Sub Foo() Dim f As FileStrean Try f = new File("s.bin") f.Read(...) Catch e As FileNotFoundException Console.WriteLine(e.Message) Finally f.Close() End TryEnd Sub

Exceptions

• An exception is thrown when an error occurs– A client can catch the exception– A client can let the exception through, but still do something

Page 29: C# / VB.NET Language Primer

29

Summary

• C# and VB.NET are the flagship languages of .NET• Fundamental language constructs

– Classes– Constructors– Namespaces– Interfaces– Virtual methods– Properties– Attributes– IDisposable– Delegates and Events – Exceptions