Introduction to C # – Part 1 Stephen Turner Software Design Engineer Microsoft UK.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Advertisements

Introduction to C# Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation.
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Attributes Programming in C# Attributes CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
C# Structs, operator overloading & attributes. Structs ~ Structures Structs are similar to classes: they represent data structures with data and functions.
AP 08/01 Component Programming with C# and.NET 1st Class Component Support Robust and Versionable Creating and using attributes API integration –DLL import.
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++
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++
Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.
C#/.NET Jacob Lewallen. C# vs.NET.NET is a platform. Many languages compile to.NET: –VB.NET –Python.NET –Managed C++ –C#
C# Language Design Peter Hallam Software Design Engineer C# Compiler Microsoft Corporation.
Peter Juszczyk CS 492/493 - ISGS. // Is this C# or Java? class TestApp { static void Main() { int counter = 0; counter++; } } The answer is C# - In C#
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 20 Microsoft’s Approach 3 – C# Rob Pooley
Platforms and tools for Web Services and Mobile Applications Introduction to C# Bent Thomsen Aalborg University 3rd and 4th of June 2004.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Programming in C# Language Overview
OOP Languages: Java vs C++
Object Oriented Programming in C# Keith Pijanowski.Net Developer Evangelist Microsoft Corporation.
1.  C# is the first “component oriented” language in the C/C++ family  Everything is an object  Component concepts are first class:  Properties, methods,
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Java2C# Antonio Cisternino Part II. Outline Array types Enum types Value types  differences from classes  boxing and unboxing Delegate types  Base.
Distributed Systems (236351) Tutorial 1 - Getting Started with Visual Studio C#.NET.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
The Java Programming Language
Introduction to C# C# is - elegant, type-safe, object oriented language enabling to build applications that run on the.NET framework - types of applications.
C#C# Introduction CS3260 Dennis A. Fairclough Version 1.0 Introduction CS3260 Dennis A. Fairclough Version 1.0.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.
DEV300: Advanced C# Eric Gunnerson Program Manager Visual C# Microsoft Corporation.
Introduction to C#  Enterprise Application  Combines High productivity of RAD & raw power of C.
Introduction to C#. C# – The Big Ideas The first component oriented language in the C/C++ family Everything.
ILM Proprietary and Confidential -
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.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Introduction to C# Ali vatankhah. C# – The Big Ideas The first component oriented language in the C/C++ family The first component oriented language in.
Harsh Jegadeesan (CSD) Introduction to C#. Harsh Jegadeesan (CSD) C# – The Big Ideas The first component oriented language in the C/C++ family Everything.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
C Sharp Web & Internet Programming Group Diana, Aren, Jeff, & Adam, Farrin 5/5/20081CS 311.
Bill Campbell, UMB Microsoft's.NET C# and The Common Language Runtime.
1 9/6/05CS360 Windows Programming CS360 Windows Programming.
Managing C++ CHRIS DAHLBERG MID-TIER DEVELOPER SCOTTRADE.
Attributes C#.Net Software Development Version 1.0.
Introduction to C# Adapted from : Anders Hejlsberg, Microsoft CSCE 5013: Hot Topics in Mobile and Pervasive Computing Nilanjan Banerjee University of Arkansas.
Object Oriented Software Development 4. C# data types, objects and references.
Session 1 C# Basics.
Introduction to C# By: Abir Ghattas Michel Barakat.
Classes Single inheritance Single inheritance Multiple interface implementation Multiple interface implementation Class members Class members  Constants,
Introduction to C# Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation.
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Introduction to Web Application
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 –
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
C# – The Big Ideas The first component oriented language in the C/C++ family Everything really is an object Next generation robust and durable software.
Creating and Using Objects, Exceptions, Strings
The 100% Inspiration Tour.
Basic Introduction to C#
Module 5: Common Type System
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Structs.
CS360 Windows Programming
Introduction to C# AKEEL AHMED.
C# In many ways, C# looks similar to Java
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Java Programming Language
The essence of C# and. Net adopted from Anders Hejlsberg (
C# – The Big Ideas The first component oriented language in the C/C++ family The first component oriented language in the C/C++ family Everything really.
Presentation transcript:

Introduction to C # – Part 1 Stephen Turner Software Design Engineer Microsoft UK

Agenda Language comparisons – C# vs. Java, etc. Program structure – Hello, World Design goals – Part 1  Provide unified type system  Support component-oriented programming  Dramatically increase productivity Design goals – Part 2  Fully extensible type system  Enable robust and durable applications  Leverage existing software

Language Comparisons 60% Java, 10% C++, 10% VB, 20% new As in Java  Object-orientation (single inheritance)  Namespaces (like packages)  Interfaces  Strong typing  Exceptions  Threads  Garbage collection  Reflection  Dynamic loading of code As in C++  Operator overloading  Pointer arithmetic in unsafe code  Some syntactic details As in VB  Properties  Events  RAD development

Language Comparisons Advancements on Java Really new  Objects on the stack (structs)  Boxing / unboxing  Delegates  Attributes  Ref and out parameters  Rectangular arrays  Enumerations  Unified type system  goto  Versioning Productivity  Component-based programming  Properties  Events  Indexers  Operator overloading  foreach statements

Agenda Language comparisons – C# vs. Java, etc. Program structure – Hello, World Design goals – Part 1  Provide unified type system  Support component-oriented programming  Dramatically increase productivity Design goals – Part 2  Fully extensible type system  Enable robust and durable applications  Leverage existing software

Hello, World class Hello { static void Main() { System.Console.WriteLine("Hello, World"); }

Hello, World using System; class Hello { static void Main() { Console.WriteLine("Hello, World"); }

Hello, World using System; class Hello { private static int Main(string[] args) { Console.WriteLine("Hello, World"); return 0; }

Hello, World using System; namespace Test { class Hello { static void Main(string[] args) { if (args.Length > 0) { Person p = new Person(args[0]); Console.WriteLine("Hello, " + p.name); } class Person { public string name; public Person(string name) { this.name = name; }

C# Program Structure Namespaces  Contain types and other namespaces Type declarations  class, struct, interface, enum and delegate Members  constant, field, method, property, indexer, event, operator, constructor, destructor (finalizer) Organization  No header files, code written “in-line”  No declaration order dependence

Agenda Language comparisons – C# vs. Java, etc. Program structure – Hello, World Design goals – Part 1  Provide unified type system  Support component-oriented programming  Dramatically increase productivity

Unified Type System Traditional views  C++, Java – primitive types are “magic” and do not interoperate with objects  Smalltalk, Lisp – primitive types are objects, but at great performance cost C# unifies with little or no performance cost  Deep simplicity throughout system Improved extensibility and reusability  New primitive types: Decimal, SQL, …  Collections, etc., work for all types

Unified Type System All types ultimately inherit from object Any piece of data can be stored, transported, and manipulated with no extra work Stream MemoryStreamFileStream Hashtabledoubleint object

Value & Reference Types Value types  Variables directly contain data  Cannot be null Reference types  Variables contain references to objects  May be null int i = 123; string s = "Hello world"; 123 i s "Hello world"

Value & Reference Types Value types  Primitives int i; float f;  Enums enum State { Off, On }  Structs struct Point { int x, y; } Reference types  Classes class Foo: Bar, IFoo { … }  Interfaces interface IFoo: IBar { … }  Arrays string[] s = new string[10];  Delegates delegate void Empty();

Unified Type System Boxing  Allocates a box, copies value into it Unboxing  Checks type of box, copies value out int i = 123; object o = i; int j = (int) o; 123 i o 123 System.Int j

Unified Type System Benefits  Eliminates the need for wrapper classes  Collection classes work with all types  Replaces OLE Automation's Variant  Simple, consistent programming model string s1 = String.Format( "Your balance is {0} on {1}", 24.95, DateTime.Today); ArrayList al = new ArrayList(); al.Add(new Object()); al.Add(1); al.Add("Hello"); string s2 = ToString(); // no boxing occurs here

Predefined Types C# predefined types  Referenceobject, string  Signedsbyte, short, int, long  Unsignedbyte, ushort, uint, ulong  Characterchar  Floating-pointfloat, double, decimal  Logicalbool Predefined types are simply aliases for system-provided types  For example, int = System.Int32

Classes Inheritance  Single base class  Multiple interface implementation Class members  Constants, fields, methods, properties, indexers, events, operators, constructors, destructors  Static and instance members  Nested types Member access  Public, protected, internal, private

Interfaces Specify methods, properties, indexers & events Public or private implementations interface IDataBound { void Bind(IDataBinder binder); } class EditBox : Control, IDataBound { void IDataBound.Bind(IDataBinder binder) {... }

Structs Like classes, except  Stored on stack or in-line, not heap allocated  Assignment copies data, not reference  Derive from System.ValueType  Can not inherit or be inherited  Can implement multiple interfaces Ideal for light weight objects  Complex, point, rectangle, color  int, float, double, etc., are all structs Benefits  No heap allocation, so fast!  More efficient use of memory

Classes and Structs sp cp CPoint Class CPoint { int x, y;... } struct SPoint { int x, y;... } CPoint cp = new CPoint(10, 20); SPoint sp = new SPoint(10, 20);

Agenda Language comparisons – C# vs. Java, etc. Program structure – Hello, World Design goals – Part 1  Provide unified type system  Support component-oriented programming  Dramatically increase productivity

1 st Class Component Support C# is the first “component oriented” language in the C/C++ family What defines a component?  Properties & events  Design-time & runtime information  Integrated help & documentation C# has first class support  Not naming patterns, adapters, etc.  Not external header or IDL files Easy to build & consume

public class Person { private int age; public int Age { get { return age; } set { age = value; Party(); } // Unnatural Person p = new Person(); p.set_Age(27); p.set_Age(p.get_Age() + 1); // Natural Person p = new Person(); p.Age = 27; p.Age ++; Properties Properties are “smart fields”  Natural syntax, accessors, inlining

Indexers Indexers are “smart arrays”  Overloadable for different index signatures public class ListBox : Control { private string[] items; public string this[int index] { get { return items[index]; } set { items[index] = value; Repaint(); } ListBox lb = new ListBox(); lb[0] = "hello"; Console.WriteLine(lb[0]);

Delegates Object oriented function pointers  Actually a method type Multiple receivers  Each delegate has an invocation list (+= & -= ops) delegate double Func(double x); static void Main() { Func f = new Func(MySin); double x = f(1.0); } private static double MySin(double x) { return Math.Sin(x); }

Events A “protected delegate”  Owning class gets full access  Consumers can only hook or unhook handlers  Similar to a property – supported with metadata Used throughout the frameworks Very easy to extend

Event Sourcing Define the event signature Define the event and firing logic public delegate void EventHandler( object sender, EventArgs e); public class Button : Control { public event EventHandler Click; protected void OnClick(EventArgs e) { if (Click != null) { Click(this, e); }

Event Handling Define and register event handler public class MyForm : Form { Button okButton; public MyForm() { okButton = new Button(); okButton.Text = "OK"; okButton.Click += new EventHandler(OkButtonClick); } private void OkButtonClick(object sender, EventArgs e) { MessageBox.Show("You pressed the OK button"); }

Metadata Associate with types and members  Design time information  Transaction context for a method  XML persistence mapping Traditional solutions  Add keywords or pragmas to language  Use external files, e.g.,.IDL,.DEF Extend the language semantics  Expose methods to web services  Set transaction context for a method

Attributes Attributes can be  Attached to any type and its members  Examined at run-time using reflection Completely extensible  Simply a class that inherits from System.Attribute Type-safe  Arguments checked at compile-time Extensive use in.NET framework  Web Services, code security, serialization, XML persistence, component / control model, COM and P/Invoke interop, code configuration…

Attributes Appear in square brackets Attached to code elements  Types, members & parameters [WebService(Namespace=" class SomeClass { [WebMethod] void GetCustomers() { } string Test([SomeAttr] string param1) { }

Creating Attributes Attributes are simply classes  Derived from System.Attribute  Class functionality = attribute functionality public class HelpURLAttribute : System.Attribute { public HelpURLAttribute(string url) { … } public string URL { get { … } } public string Tag { get { … } set { … } } }

Using Attributes Just attach it to a class Use named parameters Use multiple attributes [HelpURL(“ Class MyClass { … } [HelpURL(“ Tag=“ctor”)] Class MyClass { … } [HelpURL(“ HelpURL(“ Tag=“ctor”)] Class MyClass { … }

Querying Attributes Use reflection to query attributes Type type = typeof(MyClass); // or myObj.GetType() foreach (Attribute attr in type.GetCustomAttributes()) { if (attr is HelpURLAttribute) { HelpURLAttribute ha = (HelpURLAttribute) attr; myBrowser.Navigate(ha.URL); }

1 st Class Component Support Create a component Add an event Add a property Document the interfaces

Agenda Language comparisons – C# vs. Java, etc. Program structure – Hello, World Design goals – Part 1  Provide unified type system  Support component-oriented programming  Dramatically increase productivity

Productivity Features Enums foreach statement Parameter arrays Ref and out parameters Overflow checking Using statement Switch on string Operator overloading XML comments Conditional compilation Unsafe code Platform Invoke COM interop

Enums Strongly typed  No implicit conversions to/from int  Operators: +, -, ++, --, &, |, ^, ~ Can specify underlying type  Byte, short, int, long Supported my metadata & reflection enum Color: byte { Red = 1, Green = 2, Blue = 4, Black = 0, White = Red | Green | Blue, }

foreach Statement Iteration of arrays Iteration of user-defined collections  Or any type that supports IEnumerable foreach (Customer c in customers.OrderBy("name")) { if (c.Orders.Count != 0) {... } public static void Main(string[] args) { foreach (string s in args) { Console.WriteLine(s); }

static void Main() { printf("%s %i %o", "Hello", 29, new Object()); object[] args = new object[3]; args[0] = "Hello"; args[1] = 29; args[2] = new Object(); printf("%s %i %o", args); } static void printf(string fmt, params object[] args) { foreach (object x in args) { } Parameter Arrays Can write “printf” style methods  Type-safe, unlike C++

ref and out Parameters Use “ref” for in/out parameter passing Use “out” to return multiple values Must repeat ref/out at call site static void Swap(ref int a, ref int b) {...} static void Divide(int dividend, int divisor, out int result, out int remainder) {...} static void Main() { int x = 1, y = 2; Swap(ref x, ref y); int r0, r1; Divide(3, 2, out r0, out r1); }

Overflow Checking Integer arithmetic operations  C, C++, Java silently overflow checked vs. unchecked contexts  Default is unchecked, except for constants  Change with “/checked” compiler switch int m0 = checked(x * y); checked { int m1 = x * y; }

using Statement Acquire, Execute, Release pattern Works with any IDisposable object  Data access classes, streams, text readers and writers, network classes, etc. Resource res = new Resource(...); try { res.DoWork(); } finally { if (res != null) { ((IDisposable)res).Dispose(); } using (Resource res = new Resource()) { res.DoWork(); }

Switch on String Color ColorFromFruit(string s) { switch(s.ToLower()) { case "apple": return Color.Red; case "banana": return Color.Yellow; case "carrot": return Color.Orange; default: throw new InvalidArgumentException(); }

Operator Overloading First class user-defined data types Used in base class library  Decimal, DateTime, TimeSpan Used in the Windows Forms library  Point, Size, Rectangle Used in the SQL libraries  SQLString, SQLInt16, SQLInt32, SQLInt64, SQLBool, SQLMoney, SQLNumeric, SQLFloat…

Operator Overloading public struct DBInt { public static readonly DBInt Null = new DBInt(); private int value; private bool defined; public bool IsNull { get { return !defined; } } public static DBInt operator +(DBInt x, DBInt y) {...} public static implicit operator DBInt(int x) {...} public static explicit operator int(DBInt x) {...} } DBInt x = 123; DBInt y = DBInt.Null; DBInt z = x + y;

XML Comments /// denotes an XML comment Compiler processing:  Verifies well-formed XML  Verifies parameter names  Generates globally unique names, so links can be resolved Any XML is okay, can use “standard” tags if you want to Enables post-processing to final form

XML Comments class XmlElement { /// /// Returns the attribute with the given name /// /// The name of the attribute /// /// The attribute value, or null /// public string GetAttribute(string name) {... }

Conditional Compilation #define, #undef #if, #elif, #else, #endif  Simple boolean logic Macros are not supported Conditional methods public class Debug { [Conditional("Debug")] public static void Assert(bool cond, String s) { if (!cond) { throw new AssertionException(s); }

Summary Language comparisons – C# vs. Java, etc. Program structure – Hello, World Design goals – Part 1  Provide unified type system  Support component-oriented programming  Dramatically increase productivity Design goals – Part 2  Fully extensible type system  Enable robust and durable applications  Leverage existing software

© 2003 Microsoft Ltd. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.