C - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

C

Description:

Provide unified and extensible type system. Support component-oriented programming ... Reduced code bloat (typed collections) C# generics vs. C templates ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 35
Provided by: ander169
Category:

less

Transcript and Presenter's Notes

Title: C


1
C
  • Donal Lafferty
  • Research Student
  • Trinity College Dublin
  • (Adaptation of Anders Hejlsbergs
  • OOPSLA 2002 presentation)

2
C
  • Design goals
  • Unified type system
  • Component-oriented features
  • Productivity features
  • C futures
  • Standardization

3
C design goals
  • Dramatically increase productivity
  • Provide unified and extensible type system
  • Support component-oriented programming
  • Enable robust and durable applications
  • Build foundation for future innovation

4
Unified type system
  • Traditional views of primitive types
  • C, Java Theyre magic
  • Smalltalk, Lisp Theyre full-blown objects
  • C unifies with no performance cost
  • Value types, boxing and unboxing
  • Deep simplicity throughout system
  • Improved extensibility and reusability
  • New primitive types Decimal, SQL
  • User-defined primitive types.

5
Value and 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"
6
Value and reference types
  • Value types
  • Primitives int i double x
  • Enums enum State Off, On
  • Structs struct Point int x, y
  • Reference types
  • Classes class Foo Bar, IFoo ...
  • Interfaces interface IFoo IBar ...
  • Arrays Foo a new Foo10
  • Delegates delegate void Empty()

7
Classes
  • Inheritance
  • Single base class
  • Multiple interface implementations
  • Class members
  • Abstract, static and const
  • Nested types
  • Member access
  • Public, private, protected, internal

class Derived BaseClass, IInterfaceA,
IInterfaceB public Derived( ) base( )
// default ctor int IInterfaceA.GetValue( )
return 0 int IInterfaceB.GetValue( )
return -1
Derived derivedRef new Derived(
) derivedRef.GetValue( ) // NO!! ((IInterfaceA
)derivedRef).GetValue( ) // 0 ((IInterfaceB)d
erivedRef).GetValue( ) // -1
8
Structs
  • Syntactically like classes, but more efficient
  • Stored in-line, not heap allocated
  • Assignment copies data, not reference
  • Always inherit directly from System.Object
  • Ideal for light weight objects
  • Complex, Point, Rectangle, Color
  • int, float, double, etc., are all structs
  • No heap allocation, less GC pressure

9
Classes and structs
class CPoint int x, y ... struct SPoint
int x, y ... CPoint cp new CPoint(10,
20) SPoint sp new SPoint(10, 20)
10
sp
20
cp
CPoint
10
20
10
Unified type system
  • All types ultimately inherit from object
  • An implicit conversion exists from any type to
    type object

object
Stream
Hashtable
double
int
MemoryStream
FileStream
11
Unified type system
  • Boxing
  • Allocates 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
System.Int32
o
123
123
j
12
Component-oriented features
  • What defines a component?
  • Methods, events, properties, attributes
  • C has first class support
  • Not naming patterns, adapters, etc.
  • Not external files
  • Components are easy to build and consume

13
Properties
  • First class language construct

public class Button Control private string
text public string Text get
return text set text
value Repaint()
Button b new Button() b.Text "OK" string s
b.Text
14
Events
  • First class language construct

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)
void Initialize() Button b new
Button(...) b.Click new EventHandler(Button
Click) void ButtonClick(object sender,
EventArgs e) MessageBox.Show("You pressed
the button")
15
Attributes
  • How do you associate information with types and
    members?
  • Select a class as serializable
  • Identify a method as deprecated
  • Select methods as web services
  • Traditional solutions
  • Add keywords or pragmas to language
  • Use external files (e.g., .IDL, .DEF)
  • C solution Attributes

16
Attributes
public class Button Control
Category("Appearance") Description("Color
of text in button") Browsable(true)
public Color TextColor ... protected
override void Paint(Graphics g)
TextOut(g.GetHdc(), 10, 10, "Hello")
DllImport("gdi32", CharSet CharSet.Auto)
static extern bool TextOut(int hDC, int x,
int y, string text)
AttributeUsage(System.AttributeTargets.Property)
public class Category System.Attribute
public readonly string Value public
Category(string s)Value s
Type type typeof(Button) PropertyInfo pi
type.GetProperty("TextColor") foreach
(Attribute a in pi.GetCustomAttributes(false))
Category ca a as Category if (ca ! null)
Console.WriteLine(ca.Value)
17
Attributes
  • Completely extensible
  • Inherit from System.Attribute, apply
    AttributeUsage attribute
  • Type-safe
  • Arguments checked at compile-time
  • Examined using reflection at run-time
  • Extensive use in .NET frameworks
  • XML, Web Services, security, serialization,
    component model, COM and P/Invoke interop, code
    configuration

18
Productivity features
  • parameter arrays
  • ref and out parameters
  • overflow checking
  • foreach statement
  • lock statement
  • switch on string

19
Parameter arrays
  • Can write printf style methods
  • Type-safe, unlike C

static void printf(string fmt, params object
args) foreach (object x in args)
...
printf("s i", s, i)
object args new object2 args0
s args1 i printf("s i", args)
20
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)
21
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 i checked(x y)
checked int i x y
22
foreach statement
  • Iteration of arrays
  • Iteration of IEnumerable collections

public static void Main(string args)
foreach (string s in args) Console.WriteLine(s)
ArrayList accounts Bank.GetAccounts(...) foreac
h (Account a in accounts) if (a.Balance lt 0)
Console.WriteLine(a.CustName)
23
lock statement
  • Defines a synchronized region
  • Maps to implementation of Hoares Monitors

lock( x ) // Synchronized Region
System.Threading.Monitor.Enter(x) // lock
monitor try ... finally
System.Threading.Monitor.Exit(x) // release
24
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()
25
Polymorphism in Java
public class Fruit public String Colour()
return "You tell me" public String Shape()
return "Not sure"
public class Orange extends Fruit public
String Colour() return "Orange" public
String Shape() return "Round"
Fruit someFruit new Fruit() string a
someFruit.Shape() // "Not sure" string b
someFruit.Colour() // "You tell
me" someFruit new Orange() string c
someFruit.Shape() // "Round string d
someFruit.Colour() // "Orange"
26
Polymorphism in C
public class Fruit public virtual string
Shape() return "Not sure" public string
Colour() return "You tell me"
public class Orange Fruit public new string
Colour() return "Orange" public override
string Shape() return "Round"
Fruit someFruit new Orange() string a
someFruit.Shape() // "Round" string b
someFruit.Colour() // "You tell me" Orange
anOrange (Orange)someFruit string c
anOrange.Shape() // "Round" string d
anOrange.Colour() // "Orange"
27
Fragile Base Class
  • Base class dependent on derived class

Method B
Method C
Base Class
Method A
Method C '
Derived Class
28
Java Vulnerability
public class Fruit public int size public
Fruit(int size) this.size size public
void Resize(int size) this.ChangeSize(size)
public void ChangeSize(int size) this.size
size
public class Banana extends Fruit public
Banana(int size) super(size) public void
Bite() this.Resize(-1) public void
ChangeSize(int size) this.size size
Banana lunch new Banana( 10 )
System.out.println("Size" (lunch.size)) //
Size 10 lunch.Bite() System.out.println("Size"
(lunch.size)) // Size -1
29
C Solution
public class Fruit public int size public
Fruit(int size) this.size size public
virtual void Resize(int size)
this.ChangeSize(size) public virtual void
ChangeSize(int size) this.sizesize
public class Banana Fruit public Banana(int
size) base(size) public virtual void
Bite() this.Resize(-1) public virtual void
ChangeSize(int size) this.size size
Banana lunch new Banana( 10 )
Console.WriteLine( "Size0",lunch.size) //
Size10 lunch.Bite() Console.WriteLine(
"Size0",lunch.size) // Size9
30
The Future Generics
public class List private object
elements private int count public void
Add(object element) if (count
elements.Length) Resize(count 2)
elementscount element public
object thisint index get return
elementsindex set elementsindex
value public int Count get
return count
public class ListltItemTypegt private
ItemType elements private int count
public void Add(ItemType element) if
(count elements.Length) Resize(count 2)
elementscount element public
ItemType thisint index get return
elementsindex set elementsindex
value public int Count get
return count
List intList new List() intList.Add(1) intLis
t.Add(2) intList.Add("Three") int i
(int)intList0
List intList new List() intList.Add(1)
// Argument is boxed intList.Add(2)
// Argument is boxed intList.Add("Three")
// Should be an error int i (int)intList0
// Cast required
Listltintgt intList new Listltintgt() intList.Add(
1) // No boxing intList.Add(2)
// No boxing intList.Add("Three") //
Compile-time error int i intList0 //
No cast required
31
Generics
  • Why generics?
  • Compile-time type checking
  • Performance (no boxing, no downcasts)
  • Reduced code bloat (typed collections)
  • C generics vs. C templates
  • C generics are checked at declaration
  • C generics are instantiated at run-time
  • C generics vs. proposed Java generics
  • C generics work over entire type system
  • C generics preserve types at run-time

32
C and CLI standardization
  • Work begun in September 2000
  • Intel, HP, IBM, Fujitsu, Plum Hall, and others
  • Standards
  • ECMA 334 and 335 (December 2001)
  • ISO/IEC 232702003 (April 2003)
  • Several CLI and C implementations
  • .NET Framework and Visual Studio .NET
  • SSCLI Shared source on XP, FreeBSD, OS X
  • Mono Open source on Linux

33
Q A
  • .NET Framework SDK (includes C compiler)
  • http//msdn.microsoft.com/netframework
  • Microsoft Visual C .NET
  • http//msdn.microsoft.com/vcsharp
  • Standards
  • http//www.ecma.ch-international.org/
    publications/standards/ECMA-334.htm
  • Microsoft Research Generics prototype
  • http//research.microsoft.com/projects/clrgen
  • Community
  • http//www.gotdotnet.com/team/csharp
  • http//discuss.develop.com

34
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com