Introduction to C - PowerPoint PPT Presentation

1 / 106
About This Presentation
Title:

Introduction to C

Description:

String literal Types. Two types (Regular and Verbatim) ... Type.GetType (string) E.g. Type t = typeof (int); //System.Int32 ... Performs like Java except for String ... – PowerPoint PPT presentation

Number of Views:68
Avg rating:3.0/5.0
Slides: 107
Provided by: nenggiiny
Category:

less

Transcript and Presenter's Notes

Title: Introduction to C


1
Introduction to C and Visual Studio 2005
  • Neng Giin (Microsoft Singapore)
  • Special thanks to From Java to C A
    Developers Guide (by Mok Heng Ngee), David Lo,
    Beatrice Luca

2
Contents (1)
  • Introduction to .NET and C
  • C and VS 2005 examples
  • Types, operators and flow controls
  • Intermediate topics
  • Arrays
  • Exception Handling
  • Delegates

3
Contents (2)
  • Intermediate topics cont
  • Events
  • File IO
  • Built in data structures
  • Class, Method and Other OO Stuffs
  • Cs C features Naming Conventions

4
Part I
  • Introduction to .Net and C

5
What exactly is .NET for developers?
  • New programming paradigm
  • Interoperability of multiple languages
  • New programming languages
  • VB.Net, C.NET, VC.NET, Jscript.NET and J.NET
  • New runtime environment
  • JIT compilation, memory management, type safety
    checking, garbage collection, etc
  • .NET Framework - Extensive selection of built-in
    class libraries (BCLs)
  • Win32 API, WPF, WCF, etc.
  • Other useful functionalities

6
.NET Framework in Context
7
Programming Paradigm
  • True language interoperability
  • Methods interoperability
  • Inheritance
  • True integrated development and debugging
    environment
  • How is the support of multiple languages achieved
    ?
  • MSIL - equivalent to java byte code in Java
  • CLR (Common Language Runtime) - similar to JVM
  • CLI (Common Language Infrastructure)

8
MSIL, CLR CLI
  • .NET compiles not to binary but to intermediate
    language (MSIL).
  • CLR provides JIT (Just In Time) compilation to
    binary (IL is not interpreted)
  • CLI standard for interoperability. Ensure
    conversion to universal MSIL.
  • CTS (common type)
  • CLS (common feature)

9
.NET Framework Built-in Class library
  • Windows specific
  • Covers almost every aspect of development
  • GUI, controls frames
  • Networking
  • Web browsing web forms
  • File system access
  • Windows registry access
  • Database access, etc

10
C, What is it - (C) ?
  • C specification
  • Modern, general purpose, OO
  • Support SE principles
  • Strong type checking
  • Array bounds checking
  • Automatic garbage collection
  • Support development of software components in
    distributed environments
  • Internationalization
  • Support various types of systems

11
(No Transcript)
12
C Extras C Java
  • Combination of features of Java and C
  • Similar syntax with Java with a number of minor
    exceptions
  • Retains some C legacies
  • Some extra features
  • Indexes
  • Delegates
  • Etc

13
C Familiar Java-like features
  • Class structure
  • Single inheritance
  • Interfaces
  • Garbage collection
  • Code safety
  • Stricter typing
  • Etc.

14
C Features in C
  • Pointer operations (unsafe code)
  • Operator overloading
  • Preprocessor directives
  • Struct
  • Enum
  • Etc.

15
Other C Features
  • Encapsulated method signatures called delegates,
    which enable type-safe event notifications.
  • Properties, which serve as accessors for private
    member variables.
  • Attributes, which provide declarative metadata
    about types at run time.
  • Inline XML documentation comments.
  • Language-Integrated Query (LINQ) which provides
    built-in query capabilities across a variety of
    data sources.

16
C Vs. Java
  • Feature richness Vs. Ease of use and learning
  • Different purpose
  • Multiple programming languages BUT single
    platform
  • Single language BUT multiple platforms

17
Summary Part I
  • What is .Net to developers ?
  • What is .Net new programming paradigm how it is
    accomplished ?
  • What is C in relation to C Java ?
  • - elegance simplicity of Java
  • - power convenience of C

18
Part II
  • C VS 2005 Examples

19
Simple C Program
  • using System
  • public class HelloWorld
  • public static void Main ()
  • Console.WriteLine(Hello World)

20
Insertion Sort in C
  • public void InsertionSort ( int array)
  • for (int j2jarrayj
  • int i j-1
  • while (i0 arrayi key) arrayi1
    arrayi
  • i i-1
  • arrayi1 key

21
(No Transcript)
22
Summary Part II
  • Some simple examples of C code
  • A snapshot of VS.Net environment

23
Part III
  • Types, operators, and flow controls

24
Section 3.1
  • Available Types, How to Use Them Related issues

25
Cs Types Its Categories
  • In C, every type, even primitive ones, can be
    treated as objects (true OO, unlike Java)
  • Types are categorized to
  • Pointer types used for pointer operation in
    unsafe codes
  • Reference types (similar with reference type in
    java) reference to an object on the heap
  • Value types (similar to simple types in java)
    int, float, short, byte

26
Value Types
  • bool
  • decimal
  • float
  • double
  • long
  • ulong
  • char
  • sbyte
  • byte
  • short
  • ushort
  • int
  • uint

27
Decimal Type
  • Unique to C
  • 128 bit data type
  • Range 1.010-28 till 7.91028
  • Precision 28-29 significant digits
  • Useful for financial or scientific calculations
    requiring precision
  • Cant be converted implicitly to double or float
    (decimal have smaller range).

28
String literal Types
  • Two types (Regular and Verbatim)
  • Regular string literal considers escape sequences
  • string dir C\ -- compile error
  • Verbatim string literal - add _at_ e.g. string dir
    _at_C\ -- ok
  • C\ is considered as it is

29
Boxing and unboxing
  • Process where CLR converts simple value type to
    object
  • Bridge gap between value and reference type (from
    stack to heap)
  • E.g. int i 99
  • object o (object) i //explicit
  • i.GetType() //implicit

30
Boxing and unboxing
  • Different from casting, in boxing a new object is
    created
  • Unboxing - Convert back to value type
  • E.g.
  • int i 99
  • object o (object) i
  • i (int) o //unboxing

31
Section 3.2
  • Available Operators, How to Use Them Related
    issues

32
Operators
33
typeof(type) operators
  • Gets a representative System.Type object of a
    type or an object
  • Can only be applied to type names
  • Similar function can be achieved by
  • Object.GetType()
  • Type.GetType (string)
  • E.g.
  • Type t typeof (int) //System.Int32
  • Type t mycarobject.GetType() // the object
    type
  • Type t Type.GetType (MyClass) //MyClass

34
checked unchecked keyword (1)
  • checked to detect for overflow of integral
    types
  • E.g.
  • int i 40000
  • checked
  • short s (short)i
  • //compiler doesnt detect overflow
  • //throw overflow exception during runtime

35
checked unchecked keyword (2)
  • unchecked' force compilation despite detection
    of overflow at compile time
  • E.g.
  • unchecked
  • short s1 (short) 40000
  • // compiler detects overflow
  • // unchecked keyword force no compile-time
    exception to be thrown.
  • // during runtime, garbage value will be assigned
    to s1

36
operator
  • Performs like Java except for String
  • Compare content of 2 strings rather than whether
    they are the same object
  • E.g.
  • string s1 new string (str1)
  • string s2 new string (str1)
  • s1s2 evaluates to false in Java, true in C

37
Section 3.3
  • Available Flow Controls, How to Use Them
    Related issues

38
Flow Controls
  • foreach
  • switch-case
  • goto
  • break
  • continue
  • while
  • dowhile
  • for

39
foreach flow control
  • Repeat bunch of statements or traverse every
    element of an array/collection
  • E.g.
  • int array 1,2,3,4,5
  • foreach (int i in array)

40
switch
  • Same as java except can use switch to compare
    strings
  • Compulsory break at the end of every case
  • fall through feature - use goto

41
switch
  • E.g.
  • switch (car) case Volvo // do something
  • goto default
  • break
  • case default
  • // do something
  • break

42
goto
  • Three different ways
  • goto case
  • goto
  • goto default
  • E.g.
  • goto case volvo
  • goto exit . exit ..

43
Summary Part III
  • Different types
  • Different value types (more detailed look at
    Decimal)
  • Boxing and unboxing
  • Typeof operators
  • Checked unchecked keyword
  • Flow controls (more detailed look at foreach,
    goto)

44
Part IV
  • Intermediate Topics

45
Contents
  • Arrays
  • Exception Handling
  • Delegates
  • File I/O
  • Collection Classes
  • Hashtable
  • ArrayList

46
Arrays (1)
  • Single Dimensional Same as Java
  • Multidimensional - two types
  • Rectangular array (2D array)
  • Jagged array (array of array)
  • E.g.
  • int MyArray1 new int 5 - single
    dimensional
  • int ,MyArray2 new int 2,5 - rectangular

47
Arrays (2)
  • E.g. (continued)
  • int MyJArray new int 2MyJArray 0
    new int 1,2,3MyJAarray 1 new int
    2,3,4,5
  • int, array 1,2,3,4,5,6- initializing
    a rectangular array in a single statement
  • int array new int new int
    1,2,3, new int 4,5,6,7- initializing a
    jagged array in a single statement

48
Arrays (3)
  • System.Array
  • All array implicitly object of this class
  • Contain static methods to manipulate array
  • public static void Reverse (Array array)
  • public static void Sort (Array array)
  • public static int IndexOf (Array array, Object
    value)

49
Exception Handling (1)
  • Four keyword only
  • try, catch, finally and throw
  • No throws keyword
  • All exception are unchecked exception
  • You can choose not to catch them
  • There wont be compile error
  • Syntax the same as Java

50
Exception Handling (2)
  • Syntax try-catch-finally
  • try
  • catch (Exception e)
  • finally

51
Exception Handling (3)
  • If not needed no need to declare exception object
    ee.g. catch (Exception)
  • To re-throw the exception use catch (Exception)
    throw finally
  • All exceptions are subclass of System.Exception

52
C Exception Handling(4)
53
Exception Handling (5)
  • ApplicationException
  • Thrown by user program for non-fatal error
  • Derive your exception from this class
  • Doesnt add new functionality
  • For differentiation purpose only
  • SystemException
  • Thrown by CLR
  • For differentiation purpose only

54
Exception Handling (6)
  • System. Exception Properties
  • StackTrace, InnerException, Message, HelpLink,
    Source, TargetSite
  • System.Exception constructors
  • public Exception ()
  • public Exception (string)
  • public Exception (string, Exception)

55
Delegates (1)
  • Class derived from System.Delegate
  • To encapsulate one or more methods
  • When invoked, all methods it encapsulates are
    also invoked
  • Behaved like a class as well a function
  • Can be declared and instantiated
  • Can be invoked

56
Delegates (2)
  • public delegate void AccDelegate (double
    increment)
  • public class Car
  • public void Accelerate (double increment)
  • public static void Main ()
  • Car c1 new Car ()
  • Car c2 new Car ()
  • AccDelegate a1 new AccDelegate
    (c1.Accelerate)
  • AccDelegate a2 new AccDelegate
    (c2.Accelerate)
  • AccDelegate commonAccelerator a1a2
    //compose
  • commonAccelerator (5.5)

57
Delegates (3)
  • Delegate declaration
  • accessibility_modif delegate return_type
    delegate_identifier (parameter list)
  • E.g. public delegate void AccDelegate(double
    increment)
  • - Declare a delegate that encapsulate methods
    returning void and receiving a parameter of type
    double

58
Delegates (4)
  • Delegate instantiation
  • AccDelegate acc new AccDelegate ( c1.Accelerate
    )
  • Constructor parameter (i.e. c1.Accelerate) should
    be a method with the same signature as the
    delegate
  • Delegate invocation
  • acc (50.0)
  • c1.Accelerate () and c2.Accelerate () will be
    invoked with parameter 50.0.

59
Delegates (5)
  • To combine delegates simply use
  • To remove simply use -
  • E.g.
  • MyDelegate a1 new MyDelegate (c1.Accelerate)
  • MyDelegate a2 new MyDelegate (c2.Accelerate)
  • MyDelegate commonAccelerator a1 a2
  • commonAccelerator - a1

60
File I/O (1)
  • Several useful classes from System.IO namespace
  • File
  • Directory
  • DirectoryInfo
  • FileInfo
  • StreamReader StreamWriter
  • FileStream

61
File I/O (2)
  • Copying a file
  • File.Copy (source, target)
  • File.Copy (source, target, overwrite)
  • Moving a file
  • File.Move (source, target)
  • Deleting a file
  • File.Delete (filepath)

62
File I/O (3)
  • Reading a text file
  • string pth _at_C\data\index.txt
  • string line
  • StreamReader sr new StreamReader (pth)
  • while ((line sr.ReadLine())! null)
  • .// do something to each line read
  • sr.Close ()

63
File I/O (4)
  • Writing to a text file
  • string pth _at_C\data\index.txt
  • string line
  • StreamWriter sw new StreamWriter (pth)
  • sw.WriteLine (Hello World)
  • sw.Write (Hello World\n)
  • sw.Close()

64
Collection Classes (1)
  • Built in data structures
  • Useful when simple array is insufficient
  • A number of them
  • ArrayList
  • Hashtable
  • BitArray,Queue,Stack,SortedList, etc
  • Must import/using System.Collections

65
Collection Classes (2)
  • ArrayList (much like Javas Vector)
  • Ordered list of objects
  • Useful functions Add, Count, ToArray,
    GetEnumerator
  • E.g. 1ArrayList al new ArrayList ()al.Add
    (peach)
  • // add new element
  • object myArray al.ToArray ()
  • // ToArray returns an object array

66
Collection Classes (3)
  • Hashtable
  • Similar to java.util.Hashtable
  • Encapsulate key/value pairs
  • Common functionalities
  • Add
  • Count
  • ContainsKey
  • Remove

67
Collection Classes (4)
  • Hashtable (cont)
  • E.g. 1
  • Hashtable ht new Hashtable ()
  • ht.Add (A, A)
  • ht.Add (B, A)
  • if (ht.ContainsKey (A))
  • ht.Remove (A) // removing A
  • // looping through values using public property
    Values
  • foreach (string val in ht.Values)
  • // do some work

68
Summary Part IV
  • Declaration of Jagged Rectangular Array
  • Exception Handling in C
  • Delegates - Encapsulates list of methods
  • File I/O
  • StreamReader
  • StreamWriter
  • Useful collection classes
  • Hashtable, Array List

69
Part V
  • Classes, methods and other OO stuffs

70
Section 5.1
  • Implementing Classes
  • Related Issues

71
Namespace
  • package - in Java
  • No correlation between namespace hierarchies and
    directory structure
  • Eg MyNameSpace1.MyClass
  • namespace MyNameSpace1 class MyClass
  • Q How many namespaces can we have in a single C
    file? Can we have nested namespaces?

72
Using
  • import in Java
  • Dont include class names in the using
  • statement.
  • Specify until package level only.
  • Eg. using System -- OKusing System.ClassName
    -- Compile error
  • using System.FakeNameSpace -- Compile error
  • Q Can we have using inside a namespace?

73
Using
  • Can create your own alias (namespace )Eg.
  • using C System.Console
  • class Test
  • public static void Main() C.WriteLine
    (Test)

74
Common Class Modifiers
  • abstract
  • sealed
  • public
  • internal
  • A class that is only accessible by code in the
    same project
  • Although not the same, it is similar to package
    keyword in java
  • private

75
Class Members
  • Data Members
  • Constant
  • Fields, etc.
  • Function Members
  • Constructor
  • Method, etc.
  • Some members are not available in Java.
  • operator overloading, delegates, read only
    variables, etc.

76
Class Inheritance
  • Class Inheritance class s
  • Eg.
  • public class Car
  • public class VolvoCar
  • Q Which class has no super class?

77
Implementing Interfaces
  • Syntax class ,rface_2,...
  • Eg.
  • interface IStore
  • class PetStoreIStore
  • // provide concrete implementations
    for all the
  • abstract methods

78
Implementing Interface
  • Difference from Java
  • No implements keyword
  • Functions declared in interface cant have any
    modifiers. Implicitly public and abstract.
  • Additional notes
  • Superclass listed first, followed by
    interfacesEg. public class ChildParent,I1,I2

79
Abstract Sealed Classes
  • Meaning are the same as their java equivalent
  • Sealed
  • Equivalent to java final class
  • Class that cant be inherited by other class
  • Abstract
  • Equivalent to java abstract class
  • Class that cant be instantiated

80
Section 5.2
  • Implementing Methods
  • Related Issues

81
Method Structure
  • assess_modifier other_modifiers return_type
    method_name (parameter(s))
  • // method code
  • E.g.
  • private void DoThis (int j, string s)

82
Method Modifiers
  • Public
  • Protected
  • Internal
  • Private
  • Sealed
  • Abstract
  • Static
  • New
  • Override
  • Virtual

83
ref out keyword
  • Pass value type by reference instead of by value
    (! java)
  • Insert ref/out in method invocation signature
    statements
  • out variable no need to be initialized
  • Example the ref keyword passes a reference to
    the actual double object over to the invoked
    method
  • MS public void Accelerate (ref double speed)
  • MI Accelerate (ref speed)

84
Static Constructor
  • Initialized static class member
  • Cannot have parameters/accessibility modifiers
  • Cannot be called explicitly
  • Automatically invoked before the first static
    class member is utilized
  • E.g.
  • class Test
  • static Test ()
  • //initialization of static vars

85
Destructor
  • Called during garbage collection
  • Release resources not managed by .Net runtime,
    i.e. file database connection
  • E.g.
  • Test()
  • ...//release unneeded resources

86
Constructor Initializers Chaining
  • Keyword this base
  • this allow the programmer to call an overloaded
    constructors in the same class
  • base to call superclasss constructor
  • E.g.
  • public class VolvoCar
  • public Volvo (string s)base (s).public
    Volvo (int i,string s)this(s).
  • Chaining If none of the superclass constructors
    is explicitly invoked using base() extension,
    then the constructor of a subclass invoke the
    default constructor of the immediate superclass

87
Passing Variable Number of Parameters
  • params keyword (not found in Java)
  • E.g. arbitrary number of int parameters
  • Method definition public static void MyMethod
    (params int list)
  • Method invocation MyMethod (9,24,98)
  • Method behaviour list initialized to an int
    array of size 3

88
Method Overloading Overriding (1)
  • Overloading multiple methods of the same name
    and return type in the same class
  • Same as in Java
  • Constructors can be similarly overloaded
  • Overriding
  • Use virtual and override
  • Only method declared with virtual can be
    overridden
  • E.g.
  • In Car (parent) public virtual void Accelerate
    ()
  • In Volvo (child) public override void
    Accelerate ()

89
Method Overloading Overriding (2)
  • Overriding (cont)
  • If no virtual and override is used, will simply
    be method hiding, not method overriding
  • Although a virtual method can be overridden, it
    doesnt have to be.e.g. Virtual method is
    inherited by the subclass and can be invoked
    normally like other inherited non-virtual methods
  • Car c1 new Car () c1.Accelerate
    ()

90
Method hiding
  • new keyword
  • Common Use Create a new instance of class or
    struct
  • As a modifier Create a new class member which
    hides an inherited member from a superclass
  • E.g. public new InheritedMethod ()
  • Class member cant be declared by both new and
    override

91
Overriding Vs. Method hiding
  • Overriding
  • public class Car
  • public virtual Accelerate ()
  • public class VolvoCar
  • public override Accelerate ()
  • public static void Main()
  • Volvo v new Volvo ()
  • v.Accelerate() Which of the methods is called?
  • Car c (Car) Volvo
  • c.Accelerate() Which of the methods is called?

92
Overriding Vs. Method hiding
  • Method hiding
  • public class Car
  • public void Accelerate ()
  • public class VolvoCar
  • public new Accelerate ()
  • public static void Main()
  • Volvo v new Volvo ()
  • v.Accelerate() Which of the methods is called?
  • Car c (Car) Volvo
  • c.Accelerate() Which of the methods is called?

93
Constant Vs. ReadOnly
  • Constant
  • e.g. const char finalVar
  • Read only
  • e.g. readonly char finalVar
  • Difference ?
  • const can only be initialized on the declaration.
    Implicitly static.
  • readonly can be initialized at the declaration
    and constructor. Not implicitly static.

94
Summary Part V
  • Import package in C
  • Class structure modifiers (abstract, sealed,
    etc)
  • Inheritance interface
  • Method structure modifiers
  • Constructors, destructors some special keywords
  • Method overriding and hiding

95
Part VI
  • Some C Features Naming Conventions

96
Operator Overloading
  • 1.09.9 - OK
  • public class Fraction () Fraction f1 new
    Fraction ()Fraction f2 new Fraction
    ()f1f2 - how to do this ?
  • How to extend the behaviour of operator to
    object of class Fraction?
  • Use operator overloading

97
Operator Overloading
  • Not v. important, can be accomplished by a method
    e.g.
  • f1.Add (f2) - normal public method
  • Fraction.Add (f1,f2) - static method
  • Intuitive appeal
  • public static operator overload ()
  • e.g. class Fraction
  • public static Fraction operator (Fraction
    o1, Int32 o2)
  • //. Other class members

98
Operator Overloading
  • Operators that can be overloaded includes
  • ,-,!,,,--,true,false (unary)
  • - / and (binary)
  • ! (comparison)
  • First param type must be of the same type as the
    defining class

99
Struct
  • Similar to class in syntax
  • Except
  • Cant be inherited
  • Value type (while a class is a reference type,
    ie. stores the address of an operator)
  • Can only be accessed after initialization,
    otherwise compile error
  • Default constructor cant be overridden
    implicit
  • No field initialization of struct data members
    i.e.struct public string Title Merchant
    // error
  • No destructors

100
Struct
  • E.g.
  • struct Name
  • private string FirstName
  • public string SetFirstName (string prenom)
  • public static void Main()
  • Name nm new Name()
  • nm.SetFirstName(John)

101
Naming Conventions
  • Local Variables Method Parameters
  • Camel Casing e.g. firstName, lastName, etc
  • All other identifiers
  • Pascal Casing e.g. MyClass, Volvo, PlainText
  • Pascal Casing convention capitalizes the first
    character of each word (including acronyms over
    two letters in length) as in the following
    examples.
  • PropertyDescriptor
  • HtmlTag
  • Camel Casing convention capitalizes the first
    character of each word except the first word, as
    in the following examples.
  • propertyDescriptor
  • ioStream
  • htmlTag

102
Naming Conventions
  • Exceptions
  • Suffix with Exception
  • Events
  • Suffix with Events
  • Event Args
  • Suffix with EventArgs
  • Event Handler Delegate
  • Suffix with EventHandler
  • Interfaces
  • Prefix with I

103
Naming Convention
  • Enum
  • Pascal Casing for both enum identifiers and value
    names
  • Namespaces
  • .
  • Plural nouns when appropriate
  • No class have the same name as namespace
  • Dont put class in BCL namespace
  • Avoid words like Collections, Forms, and UI

104
Summary Part VI
  • Operator overloading
  • How to declare them ?
  • Struct
  • Similar to class with some limitations
    constraints
  • Naming conventions
  • Camel and Pascal Casing

105
Total Summary
  • Introduction .Net C
  • Simple example in C
  • Class Methods in C
  • Type, operator flow control available in C
  • Some core topics (array, exception handling, etc)
  • Cs C Features Cs coding convention

106
  • Thank you for your attention
Write a Comment
User Comments (0)
About PowerShow.com