C - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

C

Description:

checked and unchecked statements. int i = int.MaxValue; checked i = i 1; // throws exception. unchecked i = i 1; // i = int.MinValue. Statements and Expressions ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 44
Provided by: stevea81
Category:
Tags: bloat | unchecked

less

Transcript and Presenter's Notes

Title: C


1
C Overview
  • Steve Anonsen
  • Software Architect

2
Overview
  • Simple, modern, type safe language derived from
    C/C
  • Innovative balance of productivity and power
  • Seeking the ease of use of VB w/ power and
    expressiveness of C
  • Squarely targeted at the Web app space
  • Complete synergy with .NET Framework

3
A First C Program
  • using Systemclass Hello public static void
    Main() Console.WriteLine("Hello world")

4
C Design Goals
  • Simple
  • regular and simplified syntax
  • unified type system
  • no redundancies
  • no pointers (except in unsafe code)
  • Modern
  • Garbage collected
  • Structured exception handling
  • Extensible and typed metadata
  • Add any custom attributes and access them in
    code, providing a great framework building tool

5
C Design Goals
  • Financial and temporal types
  • decimal up to 28 digits
  • datetime
  • Both are compatible with SQL Server
  • OO
  • Rich encapsulation
  • Simplified operator overloading
  • Interfaces
  • Delegates
  • Essentially type safe function pointers
  • Introduced in Visual J 6.0

6
C Design Goals
  • Type-safe
  • No uninitialized variables
  • No unsafe casts
  • Range and overflow checking
  • ref and out params
  • Goodbye GP faults

7
What's not in C
  • include
  • Macros -- makes it tough for conditional
    compilation
  • Templates
  • Multiple inheritance (MI)
  • Virtual base classes
  • Forward declarations (not needed)
  • Member pointers
  • Global operators

8
Type System - Basics
  • Everything is an object - at no additional cost
    to the performance of primitive types
  • Value types
  • Primitives
  • enum
  • struct
  • User defined primitive type
  • Java only has primitives

9
Type System - Basics
  • Reference types
  • Classes
  • Interfaces
  • Different semantics than Java
  • Represents a list of slots, not a list of names
  • Arrays
  • Semantically richer than Java
  • Delegates
  • Introduced in VJ 6.0
  • Not in Java
  • Removes the need for anonymous classes

10
Built-in Types
  • Object Object and String
  • Integral byte, char, short, int, long
  • Integral sbyte, uint, ulong, ushort
  • Not part of the Common Language Specification
  • Floating float, double, decimal
  • Logical bool
  • Compatibility variant

11
Type System Classes
  • Single inheritance
  • Multiple inheritance (MI) of interfaces
  • Class members
  • Consts, fields, methods, properties, indexers,
    operators, constructors, destructors
  • Nested types
  • Member access
  • C's and internal
  • private, public, protected
  • internal is like Javas package protected

12
Type System Classes
  • Example
  • public class Base private int priv
    protected abstract int Prot() public int
    Publ() Prot() public class Derived Base
    protected override int Prot() priv 2
    Derived d new Derived()Base b
    db.Publ() // priv 2b.Prot() // error
    can't accessb.priv 1 // error can't access

13
Type System Structs
  • Sealed - convert to object through boxing
  • Sealed means it can't be subclassed like "final"
    in Java
  • Multiple interface implementation
  • No referential identity (instances are stored
    in-line)
  • Ideal for lightweight objects

14
Type System Interfaces
  • MI
  • No default implementation
  • Can contain methods and properties
  • Private interface implementations

15
Type System Delegates Events
  • Delegate is a type safe function pointer
  • Derives from Delegate base class
  • Especially useful for event handling
  • Delegates have lower overhead than Java anonymous
    classes for event handlers
  • Method rather than interface based
  • Can reuse event handlers
  • No hidden overhead
  • Parent access from anonymous classes is expensive

16
Type System Delegates Events
  • Example event publisher
  • public delegate void EventHandler(object sender,
  • Event e)
  • public class Button Control
  • public event EventHandler Click
  • protected void OnClick(Event e)
  • if (Click ! null) Click(this, e)
  • public void Reset() Click null

17
Type System Delegates Events
  • Example event consumer
  • public class MyDialog
  • Button OK
  • public MyDialog () // constructor
  • OK new Button(...)
  • OK.Click new EventHandler(OkButtonClick)
  • void OkButtonClick(object sender, Event e)
  • // can access local variables here

18
Type System Unification
  • Boxing and unboxing int i 123 object o i
    // box int j (int)o // unbox
  • Benefits
  • Anything can be an object
  • Eliminates wrapper e.g. in Java int i
    123 Integer o i // hard coded object
    type int j o.intValue()
  • Collections work for all types

19
Type System - Unification
  • Example
  • class string Format(string, object,
    object) ...
  • long totaldatetime datestring s
    string.Format("total 0 on 1",
  • total, date)
  • Thus, primitive types are automatically converted
    to object

20
Namespaces
  • C namespace syntax
  • Simpler semantics
  • C namespaces are transitive, Cs are not
  • In C if A imports B and I import A, then I also
    see B
  • Directly map to CLR namespace
  • Can contain
  • Nested namespaces
  • Type declarations
  • Open ended
  • i.e. can add new definitions to a namespace

21
Namespaces
  • Using directives
  • Import namespaces and types
  • Supports aliasing
  • Example
  • namespace Microsoft.XML using xxx
    using ReallyReallyLongName Name public
    class ... namespace events ...

22
Properties and indexers
  • Properties are smart fields
  • Associates code with get and set methods
  • Indexers are smart arrays
  • Permit overloading on index types
  • C has 1st class support
  • Not just a naming pattern
  • Access control allowed
  • Can't have different access for get and set
  • Can be abstract and overridden

23
Example of a Property
  • public class Button Control private string
    caption public string Caption get
    return caption set caption
    value Repaint() Button b new
    Button()b.Caption "OK"string s b.Caption

24
Example of an Indexer
  • public class ListBox Control private
    string items public string thisint index
    get return itemsindex set
    itemsindex value Repaint()
    ListBox listBox ...listBox0
    "OK"Console.WriteLine(listBox0)

25
Statements and Expressions
  • High C fidelity
  • if, while, do require bool condition
  • goto can't jump into blocks
  • switch statement
  • no fall-through
  • must use goto case or goto default
  • checked and unchecked statements
  • int i int.MaxValuechecked i i 1 //
    throws exceptionunchecked i i 1 // i
    int.MinValue

26
Statements and Expressions
  • Expression statements must do work void Foo()
    i 1 // error
  • foreach statement
  • Allows iterating collections in a type safe
    fashion foreach (string s in args) Console.Writ
    eLine(s)
  • A type simply implements GetEnumerator
  • The return type of GetEnumerator implements
    GetNext and GetObject

27
Statements and Expressions
  • foreach semanticsforeach (T x in c)// expands
    to E e c.GetEnumerator()while (e.GetNext())
    T x (T)e.GetObject()
  • Easier than VB, which needs IEnumVariant
  • Cant directly implement IEnumVariant in VB!

28
Versioning
  • Overloaded in most languages
  • C and Java have fragile base classes
  • Not enough language support to signal versioning
    intent
  • C allows intent to be expressed
  • Methods not virtual by default
  • This also helps to avoid v-table bloat
  • C keywords "virtual", "override" and "new"
    provide context
  • C cannot guarantee versioning
  • Can enable (e.g. explicit override)
  • Can encourage (e.g. explicit virtual)

29
Versioning
  • For example, consider the following case of a
    class in its first version class B // V1,
    provided by a 3rd party class D B //
    V1 void foo()
  • Now V2 comes along class B // V2 adds a new
    method void foo()
  • What happens to D? It overrides foo.
    Intentionally? No way foo wasn't there before!

30
Versioning
  • C does things like so
  • class B virtual void bar() //
    overridable virtual void foo() virtual void
    quux() void zed() // not overridableclas
    s D B override void bar()// explicitly
    override new void foo() // explicitly
    hide void quux() // warning new or
    override? void zed() // hides Bzed()

31
Versioning
  • Examples
  • D d new D()B b d // d is-a
    bd.bar() // calls d.barb.bar() // calls
    d.bar (polymorphic)d.foo() // calls
    d.foob.foo() // calls b.foo (ds is
    new)d.zed() // calls d.zedb.zed() // calls
    b.zed

32
Extensible Metadata
  • Attributes on types and members
  • Queried at runtime via reflection
  • Examples
  • Help contexts
  • Design-time info for UI components
  • Marshalling info for P/Invoke
  • Code access security
  • Extensible and type-safe
  • Attributes are declared as classes
  • Users can define new ones

33
Extensible Metadata
  • User-defined Example
  • attribute(ValidOn AttributeTargets.Class)pub
    lic class Category Category(int i) Value
    i public int ValueCategory(1) public
    class A Type type typeof(A)Category attr
    (Category)type.GetCustomAttribute(
  • typeof(Category))if (attr.Value 1) ...

34
Conditional compilation
  • define, undef
  • if, elif, else,endif
  • Simple boolean logic
  • Conditional methods// examplepublic class Debug
    conditional("Debug") public static void
    Assert(bool cond, String s) if (!cond)
    throw new AssertionException(s)

35
Scalable compilation model
  • Language design facilitates incremental
    compilation
  • No header files and macros
  • No declaration order dependence
  • Fast, smart incremental builds
  • Always build the minimal set of files
  • Never compiles the same file more than once
  • Organization
  • Source files can be arbitrarily moved, renamed,
    merged, and split (no file name dependency)

36
Unsafe Code
  • P/Invoke covers most cases (calling COM, DLLs)
  • Unsafe code is allowed
  • Low-level code without leaving the box
  • Enables unsafe casts, pointer arithmetic
  • The only place raw pointers can be used
  • Is applied to a method

37
Unsafe Code
  • Declarative pinning
  • fixed statement prevents movement of memory by
    the garbage collector so variables can be passed
    to unmanaged code
  • Must be used in an unsafe methodunsafe Frob()
    Foo foo fixed(foo) char p
    foo.c

38
Unsafe Code
  • Basically "inline C"unsafe void Foo() char
    buf256 // raw memory char p // still a
    unicode char for (p buf p lt buf 256 p)
    p 0 ...
  • Class must be fully trusted if unsafe appears

39
Gaining C Acceptance
  • C and much of the Common Language Runtime have
    been standardized by ECMA
  • Will soon have a reference implementation of CLR
  • The spec was published with no strings attached
  • Technical excellence is not enough they must
    also get confidence, market acceptance, academic
    excitement
  • Most of the .NET Framework class library is
    written in C they have millions of lines

40
C vs C
  • Changes from C (many are also in Java)
  • Changes due to .NET Framework
  • Garbage collected
  • Single inheritance only
  • Built-in array and string types
  • Bounds-checking
  • Ability to define primitive (value) types
  • Built-in threading
  • Simpler grammar
  • No templates
  • No const methods
  • No macros
  • No pointers to member function

41
But isnt C Standard?
  • Well, kind of
  • VC .NET introduces these keywords for the .NET
    Framework
  • __managed/__unmanaged
  • __interface
  • __valuetype
  • __byref
  • __sealed/abstract
  • __property
  • __delegate
  • __event

42
C vs Java
  • Enumerations and operator overloading
  • Cs operator has been generalized into
    indexers
  • Properties are a first class language feature
  • decimal and datetime types are built-in
  • Attribute classes for extensible metadata
  • Delegates provide type safe function pointers
  • No anonymous classes
  • Namespaces are used instead of packages there is
    also no dependence upon the file system structure

43
C vs Java
  • Better abstract data types support
  • Value types with operator overloading
  • Methods are non-virtual by default
  • Versioning requires explicit override or hide
  • Interface semantics are different
  • Private definitions
  • Explicit implementation of members
  • An interface is slots, not names
  • Other details noted through the presentation
  • We picked C on the technical merits long before
    we were acquired
Write a Comment
User Comments (0)
About PowerShow.com