290 likes | 406 Views
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.
E N D
C# / VB.NETLanguage 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 • 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 Dog Dog fido = new Dog(); // use the new object fido.Bark(); ' make a new object of class Dog Dim fido As Dog = New Dog ' use the new object fido.Bark()
Defining a Class • The “class” keyword defines a new class • The “public” keyword exposes it for external use publicclass Dog { int hairs = 17; publicvoid Bark() { System.Console.Write("Woof."); System.Console.WriteLine("I have " + hairs + " hairs"); } } PublicClass Dog Dim hairs AsInteger = 17 PublicSub Bark() System.Console.Write("Woof.") System.Console.WriteLine("I have " & hairs & " hairs") EndSub EndClass
Protection Keywords • Classes and members can be hidden from clients
Constructors • Classes can have constructors • Constructors execute upon instantiation • Constructors can accept parameters • Constructors can be overloaded based on parameter lists publicclass Patient { privatestring _name; private int _age; public Patient(string name, int age) { _name = name; _age = age; } } PublicClass Patient Private _name As String Private _age As Integer PublicSubNew(name As String, age As Integer) _name = name _age = age EndSub EndClass
Constructor Invocation • Constructor automatically invoked when object created Patient p = new Patient("fred", 60); Dim p As Patient = New Patient("fred", 60)
Multiple constructors • Class can supply multiple overloaded constructors publicclass Patient { /* ... */ public Patient(string name, int age) { _name = name; _age = age; } public Patient(int age) : Patient("anonymous", age) {} public Patient() : Patient("anonymous", -1) {} } PublicClass Patient '... PublicSubNew(name As String, _ age As Integer) _name = name _age = age EndSub Public Sub New(name As String) Me.New("anonymous", age) End Sub Public Sub New() Me.New("anonymous", -1) End Sub EndClass
Namespaces • A namespace defines a scope for naming namespace DM { publicclass Foo { publicstaticvoid Func() {} } } Namespace DM PublicClass Foo PublicSharedSub Func() EndSub EndClass EndNamespace using DM; using System; DM.Foo.Func(); Foo.Func(); Console.WriteLine("Foo!"); Imports DM Imports System DM.Foo.Func() Foo.Func() Console.WriteLine("Foo!")
Interfaces • An interface defines a set of operations w/ no implementation • Used to define a “contract” between client and object publicinterface IDog { void Bark(int volume); bool Sit(); string Name { get; } } PublicInterface IDog Sub Bark(volume As Integer) Function Sit() As Boolean ReadOnlyProperty Name As String EndInterface
Implementing Interfaces publicclass Poodle : IDog { publicvoid Bark(int volume) { ... } public bool Sit() { ... } public string Name { get { ... } } } PublicClass Mutt Implements IDog Sub Bark(volume As Integer) _ Implements IDog.Bark ... EndSub Function Sit() As Boolean _ Implements IDog.Sit ... End Function ReadOnly Property Name As String _ Implements IDog.Name Get ... End Get End Property EndClass
Using interfaces void PlayWithDog(IDog d) { d.Bark(100); if (d.Sit()) Console.Write("good dog, {0}!", d.Name); } // elsewhere IDog rex = new Mutt(); IDog twiggie = new Poodle(); PlayWithDog(rex); PlayWithDog(twiggie); • Interfaces enable polymorphism Sub PlayWithDot(d As IDog) d.Bark(100) If d.Sit() Then Console.Write("good dog, {0}!", d.Name) End Sub ' elsewhere Dim rex As IDog= New Mutt() Dim twiggie As IDog= New Poodle() PlayWithDog(rex) PlayWithDog(twiggie)
Binding • Can call method through base class reference • must decide whether to call base or derived version • decision often called binding Sub Speak(a As Animal) a.Talk() EndSub void Speak(Animal a) { a.Talk(); } which version? Dim d As Dog = New Dog() Dim c As Cat = New Cat() Speak(d) Speak(c) Dog d = new Dog(); Cat c = new Cat(); Speak(d); Speak(c); Animal Dog Cat
Binding options • Programmer chooses desired type of binding • when method called through base class reference • Two options available • static • dynamic
Static binding • Static binding uses type of reference to determine method • default behavior Sub Speak(a As Animal) a.Talk() EndSub void Speak(Animal a) { a.Talk(); } static binding calls Animal.Talk Dim d As Dog = New Dog() Dim c As Cat = New Cat() Speak(d) Speak(c) Dog d = new Dog(); Cat c = new Cat(); Speak(d); Speak(c);
Overridable / virtual methods • To make a method dynamically bound • mark as overridable/virtual in base class • use Overrides/override keyword in derived implementation PublicClass Animal ProtectedOverridableSub Talk() ' generic EndSub EndClass PublicClass Dog Inherits Animal ProtectedOverridesSub Talk() ' woof EndSub EndClass publicclass Animal { protectedvirtualvoid Talk() { /* generic */ } } publicclass Cat : Animal { protectedoverridevoid Talk() { /* meow */ } }
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() EndSub void Speak(Animal a) { a.Talk(); } Dim d As Dog = New Dog() Dim c As Cat = New Cat() Speak(d) Speak(c) Dog d = new Dog(); Cat c = new Cat(); Speak(d); Speak(c);
Properties • A property is a method that’s used like a field PublicClass Person Dim _Age AsInteger Property Age() AsInteger Get Age = _Age EndGet Set(ByVal Value AsInteger) _Age = Value EndSet EndProperty EndClass publicclass Person { int _Age; publicint Age { get { return _Age; } set { _Age = value; } } } Imports System Dim p As Person = New Person p.Age = 33 Console.WriteLine(p.Age) Person p = new Person(); p.Age = 33; Console.WriteLine(p.Age);
Attributes • An attribute provides extra info about a type or member • Used by clients interested in the extra info, e.g. an IDE [ ShowInToolbox(true) ] publicclass MyCtrl : WebControl { [Bindable(true), DefaultValue("")] [Category("Appearance")] publicstring Text { get { … } set { … } } } <ShowInToolbox(True)> PublicClass MyCtrl Inherits WebControl <Bindable(True), DefaultValue(""), _ Category("Appearance")> _ Property Text() AsString Get ... EndGet Set (ByVal Value asString) ... EndSet EndProperty EndClass
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 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() EndTry EndSub
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 call sequence Main() One() Two() Three() Divide() problem occurs in Divide, search for error handler unwinds call sequence
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
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() EndTry EndSub
C# using construct Your write this… void DoDbWork(string dsn) { using( SqlConnection conn = new SqlConnection(dsn) ) { // do db work } // IDisposable.Dispose called here automatically } void DoDbWork(string dsn) { SqlConnection conn = new SqlConnection(dsn); try { // do db work } finally { if( conn != null ) ((IDisposable)conn).Dispose(); } } } Compiler translates code into this…
Delegates and Events in C# • An event notifies clients of interesting things in the object • A delegate provides the signature of the event 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 VB.NET (Dynamic binding syntax) Public Delegate Sub ClickDelegate Public Class Button Public Event Click As ClickDelegate Sub Push RaiseEvent Click End Sub End Class Public Class Class1 Public Sub OnClick() Console.WriteLine("Button clicked!") End Sub Public Shared Sub Main() Dim b As Button = New Button() AddHandler b.Click, _ New ClickDelegate(AddressOf OnClick) '... b.Push() End Sub End Class
Delegates and Events in VB.NET(static binding syntax) Public Delegate Sub ClickDelegate Public Class Button Public Event Click As ClickDelegate Sub Push RaiseEvent Click End Sub End 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
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 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 Try End Sub
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