Session 4 : C - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

Session 4 : C

Description:

C# resembles Java a lot, but provides innovation in type safety, versioning, ... (x) x.y f(x) a[x] x x-- new typeof sizeof checked unchecked. Primary. Associativity ... – PowerPoint PPT presentation

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

less

Transcript and Presenter's Notes

Title: Session 4 : C


1
Session 4 C
  • Peter Villadsen

2
C
  • C is a language created by Anders Hejlsberg to
    provide a vehicle for writing enterprise
    applications in .NET.
  • C resembles Java a lot, but provides innovation
    in type safety, versioning, events and garbage
    collection.
  • C is an ECMA standard (as opposed to Java).
  • The smarts of .NET is not in a particular
    language, but in the libraries.
  • Remember The role of the compiler is to make
    life easy, not difficult.
  • There is a new standard emerging (C version 2.0)
    that is evident in the 2005 beta packages.

3
General structure
  • C programs consist of one or more files.
  • Each file can contain one or more namespaces.
  • A namespace can contain types such as classes,
    structs, interfaces, enumerations, and delegates,
    in addition to other namespaces.

// A skeleton of a C program using
System namespace MyNamespace1 class
MyClass1 struct MyStruct
interface IMyInterface
delegate int MyDelegate() enum MyEnum
namespace MyNamespace2 class
MyClass2 public static void
Main(string args)
4
Compiling C programs
  • There are several choices, depending on the
    environment you have chosen to work in.
  • Command line csc HelloWorld.cs
  • Use your favourite IDE...

5
Using VS.NET
  • Source texts are arranged in projects.
  • A solution may contain one or more projects.
  • There are several useful project types.
  • Productivity is increased by on order of
    magnitude.
  • Help is always near...

6
.NET Assemblies
  • The output of the compilation process is an
    assembly or an executable file.
  • An assembly can contain any number of classes
    from any number of namespaces.
  • Assemblies refer to other assemblies.
  • At runtime, all the assemblies are stored
    together and deployed.

7
.NET Types.
  • The .NET environment offers the boolean type and
    3 numeric types (integral types, floating point
    types and decimal type).
  • bool values may assume the values true and false.
  • Integral types

8
.NET Floating point types
  • Literals
  • Float 3.14159f
  • Double 3.14159265358979323d
  • Decimal 7.55m

9
Expression Operators
10
String Type
  • Strings (string, System.String) are sequences of
    unicode characters.
  • Strings are immutable.
  • Strings offer a rich set of operations.
  • String literals
  • string s "Hello World"
  • string s _at_"c\filename.txt"

11
The Bool type
  • Boolean types may have one of two values true
    and false.
  • Operators include , , !, , is
  • Evaluation is "Short Circuit"

// remove old accounts without balance if
(account.Balance 0m (DateTime.Now -
account.LastEntry) gt TimeSpan.FromDays(100))
accounts.Remove(account) if (account is
CorporateAccount) ...
12
Array types.
  • Array types in C resemble array types in Java,
    but not in C.
  • An array is an indexed collection of objects, all
    of the same type.
  • Remember, arrays are objects too.
  • Syntax is
  • MyType myArrayVar
  • The size is NOT given at declaration time.
  • Arrays may have any rank (i.e. Number of
    dimensions)

13
Variables
  • Variables are locations in storage that is of a
    given type.
  • Each variable lives in a given scope. Refering to
    a variable outside its scope causes a compilation
    error.

14
C statements
  • C supports all the statement types you are used
    to (and then a few new ones).
  • Statements end with
  • There are
  • Conditional branching statements.
  • Iteration statements.
  • Unconditional branching statements.
  • Assignment statements.

15
Conditional statements If
  • Optional else and else if parts.
  • The condition is a boolean expression.

if (i gt 10) i 0 else i 1
16
Conditional Statements Switch
switch (i 6) case 1 f(2)
break case 2 f(5)
break default break
  • Switch statements are an alternative to nested if
    statements.
  • Switch statements allow selecting from a number
    of different values.
  • Optional default part.
  • It is an error to fall through one case into the
    next.

17
Iteration Statements
  • while, do ... while, for, foreach, break,
    continue
  • while (bool-expression) statement.
  • do statement while (bool-expression)

int i bool found false while (i lt 10)
if (myObject.matches(i)) found
true break i 1
do i 1 while (i lt 10)
18
Iteration Statement for
  • The for loop allows several operations
    Initialization, test and incrementation.
  • Notice the fact that the initialization may be
    used to declare a variable in the scope of the
    statement.

for (int i 0 i lt 10 i) // Infinite
loop for() if (something) break
if (something_else) continue
19
Iteration Statement foreach
using System.Collections ArrayList ar new
ArrayList() ar.Add("Hello") ar.Add("World") fo
reach (string s in ar) System.Console.WriteL
ine(s) Hashtable ht new Hashtable() ht"one
" 1 ht"two" 2 foreach (string s in
ht.Keys) System.Console.WriteLine("0-gt1"
, s,hts)
  • The foreach statement is usable for all types
    that implement the IEnumerable interface.
  • Suffice it to say, that all array types and all
    collections in the System.Collections namespace
    support this.

20
Iteration Statements break continue
  • break
  • Causes execution to leave the innermost loop in
    which the statement is contained.
  • continue
  • Causes execution to be immediately transferred to
    the start of the loop body for execution.

21
Assignment statements
  • Assignments assign values to variables.
  • Syntax
  • myVar expression
  • Derived syntaxes exist for the cases where the
    variable is used in the expression
  • myVar 5
  • myBool true

22
Classes revisited
  • Classes are optionally inherited from other
    classes.
  • Everything is derived from Object.
  • Methods marked with virtual may be overriden in
    derived classes.
  • Classes may be abstract containing one or more
    abstract methods.
  • Classes may be sealed.
  • Classes may implement one or more interfaces.
  • Methods may be static or instance methods.
  • Methods may be overloaded.
  • Constructors.

23
Methods
  • Methods have a return type (void is a legal
    return type meaning no return value).
  • Methods have any number of parameters.
  • Methods may be called by supplying the object
    instance, the name of the method, and any number
    of parameters.
  • At runtime, the formal parameters take the value
    of the actual parameters.
  • Parameters may be specified as in (default), out
    or ref.
  • The params keyword may be used for an unspecified
    number of parameters.

24
Params
  • Params may be used to pass an unspecified number
    of parameters.

public static void UseParams(params int list)
for ( int i 0 i lt list.Length i )
Console.WriteLine(listi)
Console.WriteLine() public static void
UseParams2(params object list) for ( int
i 0 i lt list.Length i )
Console.WriteLine(listi) Console.WriteLine()
public static void Main() UseParams(1,
2, 3) UseParams2(1, 'a', "test") int
myarray new int3 10,11,12
UseParams(myarray)
25
Properties
  • Properties allow clients to access object state
    as if they were accessing member fields directly,
    while actually implementing access through
    methods.
  • Decouples the object state from the
    implementation, while providing natural syntax.
  • Example
  • myString.Length // only getter
  • Sb.Capacity 1000 // setter
  • Sb.Capacity // Getter

26
Indexers
  • Sometimes it is useful to access a class as if it
    were an array.
  • You can do this by creating indexers.
  • Useful for "lookup scenarios".
  • Indexers resemble properties, but introduce a
    type of the index (not necessarily int).

27
Indexers
public string thisstring index get
set
28
Exceptions
  • Exceptions are for abnormal situations and error
    conditions - ONLY.
  • Throw an instance of an object derived from
    System.Exception. This object can contain any
    relevant information subject to interpretation by
    the handler.
  • Exceptions work by unravelling the call stack
    searching for the first handler for the
    particular exception type.
  • If no handler is found, the program stops.

29
Throwing Exceptions
  • Throwing an exception is done with the throw
    statement
  • throw new System.Exception("Something bad
    happened")

30
Catching Exceptions
  • Exceptions are caught with catch statements that
    are given in conjunction with a try block.

try int hhh 7 / f() // Any number of
catch clauses... catch (DivideByZeroException
e) System.Console.WriteLine(e.Message)
throw
31
Catching Exceptions
  • Specify more specialized handlers before more
    generic exception types.

try int hhh 7 / f() // Any number of
catch clauses... catch (DivideByZeroException
e) System.Console.WriteLine(e.Message)
throw catch (ArithmeticError e) ... catch
(Exception e) // Matches any exception
32
Exceptions
  • Implement MyException.Message to provide a text
    representation of what went wrong.
  • Only catch exceptions you know what to do about.
  • If you throw exceptions from an exception
    handler, be sure to supply the inner exception,
    proving a chain back.
  • Don't use the catch all handler.

33
Exceptions, examples
try int hhh 7 / f() // Any number of
catch clauses... catch (DivideByZeroException
e) System.Console.WriteLine(e.Message)
throw finally
class SingularEquations System.Exception
public override string Message get
return "The equations have no
solution"
34
Attributes.
  • It is possible to assign metadata to programmatic
    entities in your program. This is done by
    specifying attributes.
  • We will see how this is used mainly when we
    discuss web services in more depth.
  • Inspect metadata in the pre generated
    AssemblyInfo.cs file in your project.
Write a Comment
User Comments (0)
About PowerShow.com