Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 C# / VB.NET Language Primer Chris J.T. Auld Microsoft MVP, Mobile Devices Managing Director Kognition Consulting Limited."— Presentation transcript:

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

2 2 Objectives Review/introduce important syntax elements of C# and VB.NET Discuss language elements commonly used with ASP.NET

3 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 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()

4 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 Sub End Class Defining a Class The “class” keyword defines a new class –The “public” keyword exposes it for external use

5 5 Protection Keywords Classes and members can be hidden from clients

6 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 Sub End Class

7 7 Constructor Invocation Constructor automatically invoked when object created Patient p = new Patient("fred", 60); Dim p As Patient = New Patient("fred", 60)

8 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 Sub End Class

9 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 Class End Namespace Imports DM Imports System DM.Foo.Func() Foo.Func() Console.WriteLine("Foo!") Namespaces A namespace defines a scope for naming

10 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 String End Interface An interface defines a set of operations w/ no implementation –Used to define a “contract” between client and object

11 11 Implementing Interfaces public 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 Property End Class

12 12 Using interfaces Interfaces enable polymorphism 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); 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)

13 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 DogCat

14 14 Binding options Programmer chooses desired type of binding –when method called through base class reference Two options available –static –dynamic

15 15 Static binding Static binding uses type of reference to determine method –default behavior static binding calls Animal.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)

16 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 Sub End Class Public Class Dog Inherits Animal Protected Overrides Sub Talk() ' woof End Sub End Class

17 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)

18 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 Property End Class Imports System Dim p As Person = New Person p.Age = 33 Console.WriteLine(p.Age) Properties A property is a method that’s used like a field

19 19 [ ShowInToolbox(true) ] public class MyCtrl : WebControl { [Bindable(true), DefaultValue("")] [Category("Appearance")] public string Text { get { … } set { … } } 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 Property End Class Attributes An attribute provides extra info about a type or member –Used by clients interested in the extra info, e.g. an IDE

20 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 Try End 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

21 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 handler unwinds call sequence

22 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

23 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 Try End Sub

24 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 translates code into this… Your write this…

25 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

26 26 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

27 27 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 Delegates and Events in VB.NET (static binding syntax)

28 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 Try End 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

29 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


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

Similar presentations


Ads by Google