Top Banner
Programming Language
48
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: c# at f#

Programming Language

Page 2: c# at f#

• It was developed by Microsoft within its .NET initiative

and later approved as a standard by Ecma (ECMA-334)

and ISO (ISO/IEC 23270).

• C# is one of the programming languages designed for

the Common Language Infrastructure.

• "C sharp" was inspired by musical notation where a

sharp indicates that the written note should be made a

semitone higher in pitch.

• C#'s principal designer and lead architect at Microsoft is

Anders Hejlsberg, who was previously involved with the

design of Turbo Pascal, Embarcadero Delphi.

Page 3: c# at f#

• C# language is intended to be a simple, modern, general-

purpose, object-oriented programming language.

• The language, and implementations thereof, should

provide support for software engineering principles such

as strong type checking, array bounds checking,

detection of attempts to use uninitialized variables, and

automatic garbage collection.

• The language is intended for use in developing software

components suitable for deployment in distributed

environments.

• Source code portability is very important, as is

programmer portability, especially for those programmers

already familiar with C and C++.

Page 4: c# at f#

• Support for internationalization is very important.

• C# is intended to be suitable for writing applications for

both hosted and embedded systems, ranging from the

very large that use sophisticated operating systems,

down to the very small having dedicated functions.

• Although C# applications are intended to be economical

with regard to memory and processing power

requirements, the language was not intended to compete

directly on performance and size with C or assembly

language.

Page 5: c# at f#

VersionLanguage specification

Date .NET Framework Visual StudioECMA ISO/IEC Microsoft

C# 1.0

December 2002 April 2003

January 2002 January 2002.NET Framework

1.0

Visual Studio

.NET 2002

C# 1.2 October 2003 April 2003.NET Framework

1.1

Visual Studio

.NET 2003

C# 2.0 June 2006September

2006

September

2005November 2005

.NET Framework

2.0

Visual Studio

2005

C# 3.0

None

August 2007 November 2007

.NET Framework

2.0 (Except

LINQ/Query

Extensions)

.NET Framework

3.0 (Except

LINQ/Query

Extensions)

.NET Framework

3.5

Visual Studio

2008

C# 4.0 April 2010 April 2010 .NET Framework 4Visual Studio

2010

Page 6: c# at f#

• It has no global variables or functions. All methods and

members must be declared within classes. Static

members of public classes can substitute for global

variables and functions.

• Local variables cannot shadow variables of the enclosing

block, unlike C and C++. Variable shadowing is often

considered confusing by C++ texts.

• C# supports a strict Boolean data type.

• In C#, memory address pointers can only be used within

blocks specifically marked as unsafe, and programs with

unsafe code need appropriate permissions to run.

• Managed memory cannot be explicitly freed.

Page 7: c# at f#

• Multiple inheritance is not supported, although a class

can implement any number of interfaces.

• C# is more type safe than C++.

• C# currently (as of version 4.0) has 77 reserved words.

Page 8: c# at f#

• Value typesValue types are plain aggregations of data. Instances

of value types do not have referential identity nor a

referential comparison semantics - equality and

inequality comparisons for value types compare the

actual data values within the instances, unless the

corresponding operators are overloaded.

Examples of value types are all primitive types, such

as int (a signed 32-bit integer), float (a 32-bit IEEE

floating-point number), char (a 16-bit Unicode code

unit), and System.DateTime (identifies a specific point

in time with nanosecond precision).

Page 9: c# at f#

• Reference typesreference types have the notion of referential identity -

each instance of a reference type is inherently distinct

from every other instance, even if the data within both

instances is the same.

Examples of reference types are object (the ultimate

base class for all other C# classes), System.String (a

string of Unicode characters), and System.Array (a

base class for all C# arrays).

Page 10: c# at f#

• C# utilizes a double forward slash (//) to indicate the rest of the line is a comment. This is inherited from C++.

public class Foo

{

// a comment

public static void Bar(int firstParam) {} // also a comment

}

Multi-line comments can be indicated by a starting forward slash/asterisk (/*) and ending asterisk/forward slash (*/). This is inherited from standard C.

public class Foo

{

/* A Multi-Line

comment */

public static void Bar(int firstParam) {}

}

Page 11: c# at f#

• C# features "preprocessor directives" (though it does not have an actual preprocessor) based on the C preprocessor that allow programmers to define symbols but not macros. Conditionals such as #if, #endif, and #else are also provided. Directives such as #region give hints to editors for code folding.

public class Foo

{

#region Procedures

public void IntBar(int firstParam) {}

public void StrBar(string firstParam) {}

public void BoolBar(bool firstParam) {}

#endregion

#region Constructors

public Foo() {}

public Foo(int firstParam) {}

#endregion

}

Page 12: c# at f#

using System;

class Program

{

static void Main()

{

Console.WriteLine("Hello world!");

}

}

Page 13: c# at f#

using System;

The using statement allows the programmer to state all candidate prefixes to use during compilation instead of always using full type names.

class Program

Above is a class definition. Everything between the following pair of braces describes Program.

static void Main()

This declares the class member method where the program begins execution. The void keyword declares that Main has no return value.

Console.WriteLine("Hello world!");

The program calls the Console method WriteLine, which displays on the console a line with the argument, the string "Hello world!".

Page 14: c# at f#

• Both languages are considered "curly brace" languages

in the C/C++ family. Overall the syntaxes of the

languages are very similar.

• The syntax at the statement and expression level is

almost identical with obvious inspiration from the C/C++

tradition.

• Java is explicit about extending classes and

implementing interfaces, while C# infers this from the

kind of types a new class/interface derives from.

• C# supports more features than Java which to some

extent is also evident in the syntax which specifies more

keywords and more grammar rules than Java.

Page 15: c# at f#

Type Name BCL Equivalent Value Range Size Default Value

sbyte System.SByte integer −128 through +127 8-bit (1-byte) 0

short System.Int16 integer−32,768 through

+32,76716-bit (2-byte) 0

int System.Int32 integer−2,147,483,648 through

+2,147,483,64732-bit (4-byte) 0

long System.Int64 integer

−9,223,372,036,854,775

,808 through

+9,223,372,036,854,775

,807

64-bit (8-byte) 0

byte System.Byte unsigned integer 0 through 255 8-bit (1-byte) 0

ushort System.UInt16 unsigned integer 0 through 65,535 16-bit (2-byte) 0

uint System.UInt32 unsigned integer 0 through 4,294,967,295 32-bit (4-byte) 0

ulong System.UInt64 unsigned integer

0 through

18,446,744,073,709,551,

615

64-bit (8-byte) 0

decimal System.Decimal signed decimal number

−7.92281625142643375

93543950335 through

+7.92281625142643375

93543950335

128-bit (16-byte) 0.0

float System.Single floating point number±1.401298E−45 through

±3.402823E+3832-bit (4-byte) 0.0

double System.Double floating point number

±4.94065645841246E−3

24 through

±1.79769313486232E+3

08

64-bit (8-byte) 0.0

bool System.Boolean Boolean true or false 8-bit (1-byte) false

char System.Char single Unicode character '\u0000' through '\uFFFF' 16-bit (2-byte) '\u0000'

Page 16: c# at f#

Java C#

BigInteger bigNumber =

new

BigInteger("123456789012345678901

234567890");

BigInteger answer =

bigNumber.multiply(new

BigInteger("42"));

BigInteger square =

bigNumber.multiply(bigNumber);

BigInteger sum =

bigNumber.add(bigNumber);

BigInteger bigNumber =

BigInteger.Parse("12345678901234567

8901234567890");

var answer = bigNumber * 42;

var square = bigNumber * bigNumber;

var sum = bigNumber + bigNumber;

Page 17: c# at f#

Java C#

Integer a = 42;

Integer b = null;

// This will generate a

runtime

NullPointerException

,

// because it attempts

to unbox the null

value.

int? a = 42;

int? b = null;

// c will receive the null

value

// because * is lifted

and one of the

operands are null

int? c = a * b;

Page 18: c# at f#

keyword feature, example usage

checked, uncheckedIn C#, checked statement blocks or expressions can enable

run-time checking for arithmetic overflow.

get, set

C# implements properties as part of the language syntax with

their optional corresponding get and set accessors, as an

alternative for the accessor methods used in Java, which is

not a language feature but a coding-pattern based on method

name conventions.

goto

C# supports the goto keyword. This can occasionally be

useful, for example for implementing finite state machines or

for generated code, but the use of a more structured method

of control flow is usually recommended (see criticism of the

goto statement). Java does not support the goto statement

(but goto is a reserved word). However, Java does support

labeled break and continue statements, which in certain

situations can be used when a goto statement might otherwise

be used.

switch(color)

{

case Color.Blue:

Console.WriteLine("Color is blue"); break;

case Color.DarkBlue:

Console.WriteLine("Color is dark");

goto case Color.Blue;

// ...

}

lockIn C#, the lock keyword is a shorthand for synchronizing

access to a block of code across threads (using a Monitor),

wrapped in a try ... finally block.

Page 19: c# at f#

out, refC# has support for output and reference parameters.

These allow returning multiple output values from a

method, or passing values by reference.

strictfpJava uses strictfp to guarantee the results of floating point

operations remain the same across platforms.

switch

In C#, the switch statement also operates on strings and longs

but only allows fallthrough for empty statements. Java's switch

statement does not operate on strings nor long primitive type

but falls through for all statements (excluding those with

'break').

throws

Java requires every method to declare the checked exceptions

or superclasses of the checked exceptions that it can throw.

Any method can also optionally declare the unchecked

exception that it throws. C# has no such syntax.

public int readItem() throws java.io.IOException

{

// ...

}

using

In C#, using causes the Dispose method (implemented via the

IDisposable interface) of the object declared to be executed

after the code block has run or when an exception is thrown

within the code block.

// Create a small file "test.txt", write a string,

// ... and close it (even if an exception occurs)

using (StreamWriter file = new StreamWriter("test.txt"))

{

file.Write("test");

}

Page 20: c# at f#

• An identifier can:

start with a "_".

contain both upper case and lower case Unicode letters. Case is

significant.

• An identifier cannot:

start with a numeral.

start with a symbol, unless it is a keyword (check Keywords).

have more than 511 chars.

Page 21: c# at f#

abstract as base bool

break by 2 byte case

catch char checked class

constcontinu

edecimal default

delegate do double descending 2

explicit event extern else

enum false finally fixed

float for foreach from 2

goto group 2 if implicit

in int interface internal

into 2 is lock long

new nullnamespa

ceobject

operator out override orderby 2

params private protectedpublic

readonly ref return switch

struct sbyte sealed short

sizeofstackall

ocstatic string

select 2 this throw true

try typeof uint ulong

unchecked unsafe ushort using

var 2 virtual volatile void

while where 2 yield 1

Page 22: c# at f#

Integers

hexadecimal 0xF5, 0x[0..9, A..F, a..f]+

decimal 245, [0..9]+

Floating-point values

float 23.5F, 23.5f; 1.72E3F, 1.72E3f, 1.72e3F, 1.72e3f

double 23.5, 23.5D, 23.5d; 1.72E3, 1.72E3D, ...

Dates

date not possible

Characters

char 'a', 'Z', '\u0231'

Strings

String"Hello, world"

"C:\\Windows\\", @"C:\Windows\"

Page 24: c# at f#

• Variables are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.

• Declare

int MyInt; // Declaring an uninitialized variable called 'MyInt', of type 'int'

• Initialize

int MyInt; // Declaring an uninitialized variable

MyInt = 35; // Initializing the variable

• Declare & initialize

int MyInt = 35; // Declaring and initializing the variable at the same time

Page 25: c# at f#

Operator category Operators

Arithmetic + - * / %

Logical (boolean and bitwise) & | ^ ! ~ && ||

String concatenation +

Increment, decrement ++ --

Shift << >>

Relational == != < > <= >=

Assignment = += -= *= /= %= &= |= ^= <<= >>=

Member access .

Indexing [ ]

Cast ( )

Conditional ? :

Delegate concatenation and

removal+ -

Object creation new

Type information as is sizeof typeof

Overflow exception control checked unchecked

Indirection and Address * -> [] &

Page 26: c# at f#

• if statementThe if statement is entered when the given condition is true.

Single-line case statements do not require block braces although it is mostly preferred by convention.

Simple one-line statement:

if (i == 3) ... ;

Multi-line with else-block (without any braces):

if (i == 2)

...

else

...

Page 27: c# at f#

• switch statementThe switch construct serves as a filter for different values.

switch (ch)

{

case 'A':

...

break;

case 'B':

case 'C':

...

break;

default:

...

break;

}

Page 28: c# at f#

• The goto statement can be used in switch statements to jump from one case to another or to fall through from one case to the next.

switch(n)

{

case 1:

Console.WriteLine("Case 1");

break;

case 2:

Console.WriteLine("Case 2");

goto case 1;

case 3:

Console.WriteLine("Case 3");

case 4: // Compilation will fail here as cases cannot fall through in C#.

Console.WriteLine("Case 4");

goto default; // This is the correct way to fall through to the next case.

default:

Console.WriteLine("Default");

}

Page 29: c# at f#

• while loop

while (i == true)

{

...

}

• do ... while loop

do

{

...

}

while (i == true);

• for loopThe for loop consists of three parts: declaration, condition and increment. Any

of them can be left out as they are optional.

for (int i = 0; i < 10; i++)

{

...

}

Page 30: c# at f#

• The break statement breaks out of the closest loop or switch statement. Execution continues in the statement after the terminated statement, if any.

int e = 10;

for (int i=0; i < e; i++)

{

while (true)

{

break;

}

// Will break to this point.

}

Page 31: c# at f#

• The continue statement discontinues the current iteration of the current control statement and begins the next iteration.

int ch;

while ((ch = GetChar()) >= 0)

{

if (ch == ' ')

continue; // Skips the rest of the while-loop

// Rest of the while-loop

...

}

Page 32: c# at f#

• Modifiers are keywords used to modify declarations of types and type members. Most notably there is a sub-group containing the access modifiers.abstract - Specifies that a class only serves as a base class. It must be

implemented in an inheriting class.

const - Specifies that a variable is a constant value that has to be initialized when it gets declared.

event - Declare an event.

extern - Specify that a method signature without a body uses a DLL-import.

override - Specify that a method or property declaration is an override of a virtual member or an implementation of a member of an abstract class.

readonly - Declare a field that can only be assigned values as part of the declaration or in a constructor in the same class.

sealed - Specifies that a class cannot be inherited.

static - Specifies that a member belongs to the class and not to a specific instance. (see section static)

unsafe - Specifies an unsafe context, which allows the use of pointers.

virtual - Specifies that a method or property declaration can be overridden by a derived class.

volatile - Specifies a field which may be modified by an external process and prevents an optimizing compiler from modifying the use of the field.

Page 33: c# at f#

• F# is a multi-paradigm programming language, targeting

the .NET Framework, that encompasses functional

programming as well as imperative and object-oriented

programming disciplines.

• It is a variant of ML and is largely compatible with the

OCaml implementation.

• F# was initially developed by Don Syme at Microsoft

Research but is now being developed at Microsoft

Developer Division and is being distributed as a fully

supported language in the .NET Framework and Visual

Studio as part of Visual Studio 2010.

• F# is a strongly typed language that uses type inference.

Page 34: c# at f#

• F# uses pattern matching to resolve names into values. It

is also used when accessing discriminated unions.

• F# comes with a Microsoft Visual Studio language

service that integrates it with the IDE.

• All functions in F# are instances of the function type, and

are immutable as well.

• The F# extended type system is implemented as generic

.NET types.

Page 35: c# at f#

• A few small samples follow:

(* This is a comment *)

(* Sample hello world program *)

printfn "Hello World!"

Page 36: c# at f#

indentationblock (grouping statements, especially when

statements are not expressions)

nothing neededbreaking lines (useful when end-of-line and/or indentation

has a special meaning)

(* ... *) commenting (nestable)

// commenting (until end of line)

< > <= >= comparison

min / max comparison (min / max (binary or more))

comparecomparison (returns 3 values (i.e. inferior, equal or

superior))

(** ... *) documentation comment (non nestable)

/// documentation comment (until end of line)

= <> equality / inequality (deep)

== != equality / inequality (shallow)

System.GC.Collect() force garbage collection

( ... ) grouping expressions

Page 37: c# at f#

begin ... end grouping expressions

__LINE__ __SOURCE_FILE__ information about the current line and file

case-sensitivetokens (case-sensitivity (keywords, variable

identifiers...))

[_a-zA-Z][_a-zA-Z0-9']* tokens (variable identifier regexp)

CamelCase for methods, types and

modules, underscore for functions

tokens (what is the standard way for

scrunching together multiple words)

<-variable assignment or declaration

(assignment)

let v = e invariable assignment or declaration

(declaration)

let v = e(1)variable assignment or declaration

(declaration)

Page 38: c# at f#

(>) a

partial application (in the examples

below, a normal call is "f(a,b)") (give the

first argument to operator ">")

f a

partial application (in the examples below, a

normal call is "f(a,b)") (give the first

argument)

fun a b -> ... anonymous function

f a b ... function call

f() function call (with no parameter)

<< function composition

>> function composition

let f para1 para2 = ... function definition

no syntax needed(2)function return value (function body is the

result)

Page 39: c# at f#

try a with exn -> ... exception (catching)

finallyexception (cleanup: code executed before

leaving)

raise exception (throwing)

if c then ... if_then

if c then b1 else b2 if_then_else

for i = 10 downto 1 do ... doneloop (for each value in a numeric range, 1

decrement)

for i in 10 .. -1 .. 1 do ... doneloop (for each value in a numeric range, 1

decrement)

for i = 1 to 10 do ... done

loop (for each value in a numeric range, 1

increment (see also the entries about

ranges))

Page 40: c# at f#

for i in 1 .. 10 do ... done

loop (for each value in a numeric range,

1 increment (see also the entries about

ranges))

for i in 1 .. 2 .. 10 do ... doneloop (for each value in a numeric range,

free increment)

while c do ... done loop (while condition do something)

while c do

...loop (while condition do something)

match val with

| v1 -> ...

| v2 | v3 -> ...

| _ -> ...

multiple selection (switch)

; sequence

end-of-line sequence

Page 41: c# at f#

: annotation (or variable declaration)

t ecast (computed conversion (calls an internal

or a user-defined function))

e :?> t cast (downcast (need runtime checking))

downcast e(3) cast (downcast (need runtime checking))

e : t cast (upcast)

upcast e cast (upcast)

type n = t declaration

constness is the defaultmutability, constness (type of a constant

value)

T refmutability, constness (type of a mutable

value)

Page 42: c# at f#

s.[n] accessing n-th character

chr ascii to character

'z' character "z"

ord character to ascii

char character type name

ToString convert something to a string (see also string interpolation)

s.[n..m] extract a substring

sub extract a substring

IndexOf locate a substring

LastIndexOf locate a substring (starting at the end)

all strings allow multi-line

stringsmulti-line

BinaryFormatter.Serialize serialize (marshalling)

Page 43: c# at f#

print_any simple print (on any objects)

WriteLine simple print (on any objects)

print_string simple print (on strings)

printf simple print (printf-like)

sprintf sprintf-like

Format sprintf-like

+ string concatenation

^ string concatenation

= <> string equality & inequality

Page 44: c# at f#

length string size

Length string size

"..." strings (with no interpolation of variables)

stringBinaryFormatter.

Deserialize type name

unserialize (un-marshalling)

uppercase / lowercase upper / lower case character

ToUpper / ToLower upper / lower case character

uppercase/lowercase uppercase / lowercase / capitalized string

ToUpper / ToLower uppercase / lowercase / capitalized string

Page 45: c# at f#

false false value

not logical not

|| / &&logical or / and (short

circuit)

true true value

bool type name

Page 46: c# at f#

+ / - / * / / addition / subtraction / multiplication / division

&&& / ||| / ^^^ bitwise operators (and / or / xor)

land / lor / lxor bitwise operators (and / or / xor)

~~~ bitwise operators (bitwise inversion)

lnot bitwise operators (bitwise inversion)

<<< / >>> bitwise operators (left shift / right shift / unsigned right shift)

lsl / lsr or asr bitwise operators (left shift / right shift / unsigned right shift)

** exponentiation (power)

log10 logarithm (base 10)

log logarithm (base e)

% modulo (modulo of -3 / 2 is -1)

mod modulo (modulo of -3 / 2 is -1)

- negation

1000., 1E3 numbers syntax (floating point)

0b1, 0o7, 0xf numbers syntax (integers in base 2, octal and hexadecimal)

1000 numbers syntax (integers)

Page 47: c# at f#

let r = System.Random()

r.Next()random (random number)

sqrt / exp / abssquare root / e-exponential / absolute

value

sin / cos / tan trigonometry (basic)

asin / acos / atan(7) trigonometry (inverse)

int / / floor / ceil truncate / round / floor / ceil

int_of_float / / floor / ceil truncate / round / floor / ceil

float, float32 type name (floating point)

int, int8, uint8, int16, uint16, int32, uint32,

int64, uint64, bigint, bignumtype name (integers)

Page 48: c# at f#

Presented by:

Harry Kim BaloisBSCS 41A