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

Slides:



Advertisements
Similar presentations
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Advertisements

Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Writing Object Oriented Software with C#. C# and OOP C# is designed for the.NET Framework  The.NET Framework is Object Oriented In C#  Your access to.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Chapter 12: Advanced Topics: Exception Handling Visual Basic.NET Programming: From Problem Analysis to Program Design.
5. OOP. 2 Microsoft Objectives “Classes, objects and object-oriented programming (OOP) play a fundamental role in.NET. C# features full support for the.
Object-Oriented Programming in Visual Basic.NET. Overview Defining Classes Creating and Destroying Objects Inheritance Interfaces Working with Classes.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
OOP Languages: Java vs C++
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
To define a class in Visual Basic.NET, you can follow this general procedure: 1. Add a class to the project. 2. Provide an appropriate file name for.
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Module 7: Object-Oriented Programming in Visual Basic .NET
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
CIS 3301 C# Lesson 13 Interfaces. CIS 3302 Objectives Understand the Purpose of Interfaces. Define an Interface. Use an Interface. Implement Interface.
2009 first semister Instructor: Abdalrahman Obidat 1 Revision 3 Instructor: Abdalrahman Obidat.
Programming Languages and Paradigms Object-Oriented Programming.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Introduction to Exception Handling and Defensive Programming.
C# F 1 CSC 298 Object Oriented Programming (Part 1)
Effective C# 50 Specific Ways to Improve Your C# Item 14~ /08/14 1.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Applications Development
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Chapter 9 Questions 1. What are the difference between constructors and member functions? 2. Design and implement a simple class as you want, with constructors.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Introduction to Object-Oriented Programming Lesson 2.
CIS 200 Test 01 Review. Built-In Types Properties  Exposed “Variables” or accessible values of an object  Can have access controlled via scope modifiers.
INTRODUCTION CHAPTER #1 Visual Basic.NET. VB.Net General features It is an object oriented language  In the past VB had objects but focus was not placed.
Overview of Previous Lesson(s) Over View  ASP is a technology that enables scripts in web pages to be executed by an Internet server.  ASP.NET is a.
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2014
CIS 200 Test 01 Review.
Inheritance and Polymorphism
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Road Map Introduction to object oriented programming. Classes
Java Programming Language
Finalization 17: Finalization
Polymorphism Polymorphism
Object-Oriented Programming: Classes and Objects
Tonga Institute of Higher Education
CIS 199 Final Review.
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2018
Binding 10: Binding Programming C# © 2003 DevelopMentor, Inc.
Creating and Using Classes
5. OOP OOP © 2003 Microsoft.
Presentation transcript:

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

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

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 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 Protection Keywords Classes and members can be hidden from clients

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 Constructor Invocation Constructor automatically invoked when object created Patient p = new Patient("fred", 60); Dim p As Patient = New Patient("fred", 60)

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 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 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 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 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 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 Binding options Programmer chooses desired type of binding –when method called through base class reference Two options available –static –dynamic

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