SlideShare a Scribd company logo
Introduction to C#
Game Design Experience
Professor Jim Whitehead
January 22, 2008
Creative Commons Attribution 3.0
(Except imported slides, as noted)
creativecommons.org/licenses/by/3.0
Goals of the C# language
• A simple, modern, general-purpose object-oriented
langauge
• Software robustness and programmer productivity
► Strong type checking, array bounds checking, detection of use of
uninitialized variables, source code portability, automatic garbage
collection
• Useable in creating software components
• Ease of learning by programmers familiar with C++ and
Java
• Usable for embedded and large
system programming
• Strong performance, but not
intended to compete with C
or assembly language
Type II safety cans for flammables
Brief history of C#
• Originated by Microsoft as a
response to Java
► Initial public release in 2000
• Language name inspired by musical note C#
► A “step above” C/C++ (and Java)
► Linux wags: Db (D-flat, same note, different name)
• Lead designers: Anders Hejlsberg, Scott
Wiltamuth
► Hejlsberg experience: Turbo Pascal, Borland Delphi, J+
+
• C# standardized via ECMA and ISO
► However, Microsoft retains architectural control
Key language features
• Unified object system
► Everything type is an object,
even primitives
• Single inheritance
• Interfaces
► Specify methods & interfaces,
but no implementation
• Structs
► A restricted, lightweight (efficient) type
• Delegates
► Expressive typesafe function pointer
► Useful for strategy and observer design patterns
• Preprocessor directives
cking, Flickr
www.flickr.com/photos/spotsgot/1414345/
Hello World example
class Hello
{
static void Main()
{
// Use the system console object
System.Console.WriteLine(“Hello, World!”);
}
}
Creates a new object type (class) called Hello.
It contains a single method, called Main.
Main contains one line, which writes
“Hello, World!” on the display.
The method that performs this action is called WriteLine.
The WriteLine method belongs to the System.Console object.
The keyword “static” means that the method Main can be called even if there is no current
instance of the class. It’s a class method, not an instance method.
The line beginning with // is a comment, and does not execute.
Demonstration of creating Hello World inside Visual C# Express
oskay, Flickr
www.flickr.com/photos/oskay/472097903/
Syntax
• Case-sensitive
• Whitespace has no meaning
► Sequences of space, tab, linefeed,
carriage return
• Semicolons are used to
terminate statements (;)
• Curly braces {} enclose
code blocks
• Comments:
► /* comment */
► // comment
► /// <comment_in_xml>
• Automatic XML commenting facility
Peter Hellberg, Flickr
www.flickr.com/photos/peterhellberg/1858249410
Classes and Objects
• A class combines together
► Data
• Class variables
► Behavior
• Methods
• A key feature of object-
oriented languages
► Procedural languages, such as C, did not require clustering of data
and behavior
• Class/instance distinction
► Class defines variables & methods
► Need to create instanced of the class, called objects, to use
variables & methods
► Exception: static methods and variables
► Analogy: a jelly bean mold (class) can be used to create a large
number of jelly beans (objects, instances of the class)
Jelly bean mold, photo by daxiang stef
www.flickr.com/photos/daxiang/96508482/
Defining a class
• Attributes: used to add metadata to a class
► Can safely be ignored
• Access modifiers: one of
► public, private, protected, internal, protected internal
• Base-class
► Indicates (optional) parent for inheritance
• Interfaces
► Indicates (optional) interfaces that supply method signatures that need to be implemented in the
class
• Class-body
► Code for the variables and methods of the class
[attributes] [access-modifiers] class identifier [:base-class [,interface(s)]]
{ class-body }
Simple example:
class A
{
int num = 0; // a simple variable
A (int initial_num) { num = initial_num; } // set initial value of num
}
cking, Flickr
www.flickr.com/photos/spotsgot/1559060/
Inheritance
• Operationally
► If class B inherits from base class A, it gains all of the
variables and methods of A
► Class B can optionally add more variables and methods
► Class B can optionally change the methods of A
• Uses
► Reuse of class by specializing it for a specific context
► Extending a general class for more specific uses
• Interfaces
► Allow reuse of method definitions of
interface
► Subclass must implement method
definitions cking, Flickr
www.flickr.com/photos/spotsgot/1500855/
Inheritance Example
class A
{
public void display_one()
{
System.Console.WriteLine("I come from A");
}
}
class B : A
{
public void display_two()
{
System.Console.WriteLine("I come from B, child of A");
}
}
class App
{
static void Main()
{
A a = new A(); // Create instance of A
B b = new B(); // Create instance of B
a.display_one(); // I come from A
b.display_one(); // I come from A
b.display_two(); // I come from B, child of A
}
}
In-class demo of this code in Visual C# Express
Enya_z, Flickr
www.flickr.com/photos/nawuxika/270033468/
Visibility
• A class is a container for data
and behavior
• Often want to control over
which code:
► Can read & write data
► Can call methods
• Access modifiers:
► Public
• No restrictions. Members visible
to any method of any class
► Private
• Members in class A marked private only accessible to methods of class
A
• Default visibility of class variables
► Protected
• Members in class A marked protected accessible to methods of class A
and subclasses of A.
Clearly Ambiguous, Flickr
www.flickr.com/photos/clearlyambiguous/47022668/
Visibility Example
class A
{
public int num_slugs;
protected int num_trees;
…
}
class B : A
{
private int num_tree_sitters;
…
}
class C
{
…
}
• Class A can see:
► num_slugs: is public
► num_trees: is protected, but is defined
in A
• Class B can see:
► num_slugs: is public in A
► num_trees: is protected in parent A
► num_tree_sitters: is private, but is
defined in B
• Class C can see:
► num_slugs: is public in A
► Can’t see:
• num_trees: protected in A
• num_tree_sitters: private in BRaindog, Flickr
www.flickr.com/photos/raindog/
436176848/
Constructors
• Use “new” to create a new
object instance
► This causes the “constructor”
to be called
• A constructor is a method called
when an object is created
► C# provides a default constructor
for every class
• Creates object but takes no other action
► Typically classes have explicitly
provided constructor
• Constructor
► Has same name as the class
► Can take arguments
► Usually public, though not always
• Singleton design pattern makes constructor private to ensure only one
object instance is created
bucklava, Flickr
www.flickr.com/photos/9229859@N02/1985775921/
Type System
• Value types
► Directly contain data
► Cannot be null
► Allocated on the stack
• Reference types
► Contain references to objects
► May be null
► Allocated on the heap
int i = 123;int i = 123;
string s = "Hello world";string s = "Hello world";
123123ii
ss "Hello world""Hello world" Slide adapted from “Introduction
to C#”, Anders Hejlsberg
www.ecma-international.org/activities/Languages/
Introduction%20to%20Csharp.ppt
Numeral type, by threedots
www.flickr.com/photos/threedots/115805043/
Predefined Types
• C# predefined types
► Reference object, string
► Signed sbyte, short, int, long
► Unsigned byte, ushort, uint, ulong
► Character char
► Floating-point float, double, decimal
► Logical bool
• Predefined types are simply aliases for system-
provided types
► For example, int == System.Int32
Slide from “Introduction to C#”,
Anders Hejlsberg
www.ecma-international.org/activities/Languages/
Introduction%20to%20Csharp.ppt
Unusual types in C#
• Bool
► Holds a boolean value,
“true” or “false”
► Integer values do not
equal to boolean values
• 0 does not equal false
• There is no built-in
conversion from integer
to boolean
• Decimal
► A fixed precision number
up to 28 digits plus decimal point
► Useful for money calculations
► 300.5m
• Suffix “m” or “M” indicates decimal
tackyspoons, Flickr
www.flickr.com/photos/tackyspoons/812710409/
Unified type system
• All types ultimately inherit from object
► Classes, enums, arrays, delegates, structs, …
• An implicit conversion exists from any type to type
object
StreamStream
MemoryStreamMemoryStream FileStreamFileStream
HashtableHashtable doubledoubleintint
objectobject
Slide from “Introduction to C#”,
Anders Hejlsberg
www.ecma-international.org/activities/Languages/
Introduction%20to%20Csharp.ppt
Variables
• Variables must be initialized or assigned to before
first use
• Class members take a visibility operator
beforehand
• Constants cannot be changed
type variable-name [= initialization-expression];
Examples:
int number_of_slugs = 0;
string name;
float myfloat = 0.5f;
bool hotOrNot = true;
Also constants:
const int freezingPoint = 32;
Enumerations
• Base type can be any integral type (ushort, long)
except for char
• Defaults to int
• Must cast to int to display in Writeln
► Example: (int)g.gradeA
enum identifier [: base-type]
{ enumerator-list}
Example:
enum Grades
{
gradeA = 94,
gradeAminus = 90,
gradeBplus = 87,
gradeB = 84
}
Conditionals
• C# supports C/C++/Java syntax for “if” statement
• Expression must evaluate to a bool value
► No integer expressions here
• == means “equal to” for boolean comparison
► if (i == 5) // if i equals 5
► if (i = 5) // error, since i = 5 is not a boolean expression
if (expression)
statement1
[else
statement2]
Example:
if (i < 5) {
System.Console.Writeln(“i is smaller than 5”);
} else {
System.Console.Writeln(“i is greater than or equal to 5”);
}
Switch statement
• Alternative to if
• Typically use break
• Can use goto to continue to another case
switch (expression)
{
case constant-expression:
statement(s);
jump-statement
[default: statement(s);]
Example:
const int raining = 1;
const int snowing = 0;
int weather = snowing;
switch (weather) {
case snowing:
System.Console.Writeln(“It is snowing!”);
goto case raining;
case raining;
System.Console.Writeln(“I am wet!”);
break;
default:
System.Console.Writeln(“Weather OK”);
break;
}
Homework
• Read in Programming C#
► Chapter 1 (C# and the .NET Framework)
► Chapter 2 (Getting Started: "Hello World")
► Chapter 3 (C# Language Fundamentals)
• Try one of the example code samples for yourself
in Visual C# Express
► Work with your partner
• Book is available online, via O’Reilly Safari
► http://safari.oreilly.com/0596006993
► Use on-campus computer to access
More resources
• Introduction to C#
Anders Hejlsberg
► http://www.ecma-international.org/activities/Languages/Introduction%20to%20Csharp.ppt
► High-level powerpoint presentation introducing the C# language by its designer

More Related Content

PDF
Louis Loizides iOS Programming Introduction
Lou Loizides
 
PDF
iOS Programming Intro
Lou Loizides
 
PPTX
introduction to c #
Sireesh K
 
PPT
Csharp_mahesh
Ananthu Mahesh
 
PPTX
C++ overview
Prem Ranjan
 
PDF
Java OO Revisited
Jussi Pohjolainen
 
PDF
What Makes Objective C Dynamic?
Kyle Oba
 
KEY
Artdm170 Week5 Intro To Flash
Gilbert Guerrero
 
Louis Loizides iOS Programming Introduction
Lou Loizides
 
iOS Programming Intro
Lou Loizides
 
introduction to c #
Sireesh K
 
Csharp_mahesh
Ananthu Mahesh
 
C++ overview
Prem Ranjan
 
Java OO Revisited
Jussi Pohjolainen
 
What Makes Objective C Dynamic?
Kyle Oba
 
Artdm170 Week5 Intro To Flash
Gilbert Guerrero
 

What's hot (20)

PPTX
Constructor and Destructor
Sunipa Bera
 
PPT
Objective c
ricky_chatur2005
 
PPT
vb.net Constructor and destructor
suraj pandey
 
PPT
C# basics
Dinesh kumar
 
PDF
Introduction to Type Script by Sam Goldman, SmartLogic
SmartLogic
 
PDF
YAPC::EU::2011 - Mostly Lazy DBIx::Class Testing
Chisel Wright
 
PPT
Static.18
myrajendra
 
PDF
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Pankaj Prateek
 
PPT
03class
Waheed Warraich
 
PDF
Calypso underhood
ESUG
 
PPTX
Concept of Object-Oriented in C++
Abdullah Jan
 
PPTX
06.1 .Net memory management
Victor Matyushevskyy
 
PDF
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Pankaj Prateek
 
PPT
Constructor
abhay singh
 
PPT
Java
Prabhat gangwar
 
PPTX
03 classes interfaces_principlesofoop
Vladislav Hadzhiyski
 
PPT
Basic info on java intro
kabirmahlotra
 
PDF
Few simple-type-tricks in scala
Ruslan Shevchenko
 
PPTX
Week10 packages using objects in objects
kjkleindorfer
 
PDF
Introduction to Smalltalk
kim.mens
 
Constructor and Destructor
Sunipa Bera
 
Objective c
ricky_chatur2005
 
vb.net Constructor and destructor
suraj pandey
 
C# basics
Dinesh kumar
 
Introduction to Type Script by Sam Goldman, SmartLogic
SmartLogic
 
YAPC::EU::2011 - Mostly Lazy DBIx::Class Testing
Chisel Wright
 
Static.18
myrajendra
 
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Pankaj Prateek
 
Calypso underhood
ESUG
 
Concept of Object-Oriented in C++
Abdullah Jan
 
06.1 .Net memory management
Victor Matyushevskyy
 
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Pankaj Prateek
 
Constructor
abhay singh
 
03 classes interfaces_principlesofoop
Vladislav Hadzhiyski
 
Basic info on java intro
kabirmahlotra
 
Few simple-type-tricks in scala
Ruslan Shevchenko
 
Week10 packages using objects in objects
kjkleindorfer
 
Introduction to Smalltalk
kim.mens
 
Ad

Viewers also liked (18)

PPTX
Summer in Sweden
Uncle Gary
 
PPTX
Orientationprogram2013
Meetendra Singh
 
PPT
Brandnv
qhan228
 
PPTX
Bornholm an island in the Baltic
Uncle Gary
 
PPTX
Valencia, photos from my spanish course there in 2000
Uncle Gary
 
PPT
Brandnv
qhan228
 
PDF
前端攻城獅?一堂適合小獅子的入門分享 20140729
Shu Ting Hsieh
 
PPTX
The mystery with the puck who disappeared
Uncle Gary
 
PPTX
Eee assignment
Meetendra Singh
 
PPT
Gmi presentation
Muhammad Faheem
 
PPTX
Some photos from Bohus Malmön
Uncle Gary
 
PDF
データベース入門1
tadaaki hayashi
 
PDF
データベース入門2
tadaaki hayashi
 
PDF
Urisa TU-74 final
Emmanuel Clemence
 
PPT
溝通升級版201005
Shu Ting Hsieh
 
PPT
網站解剖學
Shu Ting Hsieh
 
PPT
溝通升級版201006
Shu Ting Hsieh
 
PPT
溝通升級版201007
Shu Ting Hsieh
 
Summer in Sweden
Uncle Gary
 
Orientationprogram2013
Meetendra Singh
 
Brandnv
qhan228
 
Bornholm an island in the Baltic
Uncle Gary
 
Valencia, photos from my spanish course there in 2000
Uncle Gary
 
Brandnv
qhan228
 
前端攻城獅?一堂適合小獅子的入門分享 20140729
Shu Ting Hsieh
 
The mystery with the puck who disappeared
Uncle Gary
 
Eee assignment
Meetendra Singh
 
Gmi presentation
Muhammad Faheem
 
Some photos from Bohus Malmön
Uncle Gary
 
データベース入門1
tadaaki hayashi
 
データベース入門2
tadaaki hayashi
 
Urisa TU-74 final
Emmanuel Clemence
 
溝通升級版201005
Shu Ting Hsieh
 
網站解剖學
Shu Ting Hsieh
 
溝通升級版201006
Shu Ting Hsieh
 
溝通升級版201007
Shu Ting Hsieh
 
Ad

Similar to Dot Net csharp Language (20)

PPTX
Oops
Gayathri Ganesh
 
PPTX
Class introduction in java
yugandhar vadlamudi
 
PPT
Objective-C for iOS Application Development
Dhaval Kaneria
 
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
PPTX
Class and Object.pptx from nit patna ece department
om2348023vats
 
PPTX
Java2
Ranjitham N
 
PPTX
Java
Ranjitham N
 
PPTX
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
PPTX
C# classes objects
Dr.Neeraj Kumar Pandey
 
PPTX
C++ Presen. tation.pptx
mohitsinha7739289047
 
PPTX
Quick Interview Preparation for C# All Concepts
Karmanjay Verma
 
PPT
Core Java unit no. 1 object and class ppt
Mochi263119
 
PPT
Core Java unit no. 1 object and class ppt
Mochi263119
 
PPTX
unit 2 java.pptx
AshokKumar587867
 
PPTX
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
PPTX
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
PPT
Java cçccfftshrssfuutrfuuggiuffus201-java.ppt
scsankalp03
 
Class introduction in java
yugandhar vadlamudi
 
Objective-C for iOS Application Development
Dhaval Kaneria
 
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Class and Object.pptx from nit patna ece department
om2348023vats
 
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
C# classes objects
Dr.Neeraj Kumar Pandey
 
C++ Presen. tation.pptx
mohitsinha7739289047
 
Quick Interview Preparation for C# All Concepts
Karmanjay Verma
 
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Mochi263119
 
unit 2 java.pptx
AshokKumar587867
 
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
Java cçccfftshrssfuutrfuuggiuffus201-java.ppt
scsankalp03
 

Recently uploaded (20)

PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
FSSAI (Food Safety and Standards Authority of India) & FDA (Food and Drug Adm...
Dr. Paindla Jyothirmai
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PDF
Study Material and notes for Women Empowerment
ComputerScienceSACWC
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PDF
RA 12028_ARAL_Orientation_Day-2-Sessions_v2.pdf
Seven De Los Reyes
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
FSSAI (Food Safety and Standards Authority of India) & FDA (Food and Drug Adm...
Dr. Paindla Jyothirmai
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
Study Material and notes for Women Empowerment
ComputerScienceSACWC
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
RA 12028_ARAL_Orientation_Day-2-Sessions_v2.pdf
Seven De Los Reyes
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 

Dot Net csharp Language

  • 1. Introduction to C# Game Design Experience Professor Jim Whitehead January 22, 2008 Creative Commons Attribution 3.0 (Except imported slides, as noted) creativecommons.org/licenses/by/3.0
  • 2. Goals of the C# language • A simple, modern, general-purpose object-oriented langauge • Software robustness and programmer productivity ► Strong type checking, array bounds checking, detection of use of uninitialized variables, source code portability, automatic garbage collection • Useable in creating software components • Ease of learning by programmers familiar with C++ and Java • Usable for embedded and large system programming • Strong performance, but not intended to compete with C or assembly language Type II safety cans for flammables
  • 3. Brief history of C# • Originated by Microsoft as a response to Java ► Initial public release in 2000 • Language name inspired by musical note C# ► A “step above” C/C++ (and Java) ► Linux wags: Db (D-flat, same note, different name) • Lead designers: Anders Hejlsberg, Scott Wiltamuth ► Hejlsberg experience: Turbo Pascal, Borland Delphi, J+ + • C# standardized via ECMA and ISO ► However, Microsoft retains architectural control
  • 4. Key language features • Unified object system ► Everything type is an object, even primitives • Single inheritance • Interfaces ► Specify methods & interfaces, but no implementation • Structs ► A restricted, lightweight (efficient) type • Delegates ► Expressive typesafe function pointer ► Useful for strategy and observer design patterns • Preprocessor directives cking, Flickr www.flickr.com/photos/spotsgot/1414345/
  • 5. Hello World example class Hello { static void Main() { // Use the system console object System.Console.WriteLine(“Hello, World!”); } } Creates a new object type (class) called Hello. It contains a single method, called Main. Main contains one line, which writes “Hello, World!” on the display. The method that performs this action is called WriteLine. The WriteLine method belongs to the System.Console object. The keyword “static” means that the method Main can be called even if there is no current instance of the class. It’s a class method, not an instance method. The line beginning with // is a comment, and does not execute. Demonstration of creating Hello World inside Visual C# Express oskay, Flickr www.flickr.com/photos/oskay/472097903/
  • 6. Syntax • Case-sensitive • Whitespace has no meaning ► Sequences of space, tab, linefeed, carriage return • Semicolons are used to terminate statements (;) • Curly braces {} enclose code blocks • Comments: ► /* comment */ ► // comment ► /// <comment_in_xml> • Automatic XML commenting facility Peter Hellberg, Flickr www.flickr.com/photos/peterhellberg/1858249410
  • 7. Classes and Objects • A class combines together ► Data • Class variables ► Behavior • Methods • A key feature of object- oriented languages ► Procedural languages, such as C, did not require clustering of data and behavior • Class/instance distinction ► Class defines variables & methods ► Need to create instanced of the class, called objects, to use variables & methods ► Exception: static methods and variables ► Analogy: a jelly bean mold (class) can be used to create a large number of jelly beans (objects, instances of the class) Jelly bean mold, photo by daxiang stef www.flickr.com/photos/daxiang/96508482/
  • 8. Defining a class • Attributes: used to add metadata to a class ► Can safely be ignored • Access modifiers: one of ► public, private, protected, internal, protected internal • Base-class ► Indicates (optional) parent for inheritance • Interfaces ► Indicates (optional) interfaces that supply method signatures that need to be implemented in the class • Class-body ► Code for the variables and methods of the class [attributes] [access-modifiers] class identifier [:base-class [,interface(s)]] { class-body } Simple example: class A { int num = 0; // a simple variable A (int initial_num) { num = initial_num; } // set initial value of num } cking, Flickr www.flickr.com/photos/spotsgot/1559060/
  • 9. Inheritance • Operationally ► If class B inherits from base class A, it gains all of the variables and methods of A ► Class B can optionally add more variables and methods ► Class B can optionally change the methods of A • Uses ► Reuse of class by specializing it for a specific context ► Extending a general class for more specific uses • Interfaces ► Allow reuse of method definitions of interface ► Subclass must implement method definitions cking, Flickr www.flickr.com/photos/spotsgot/1500855/
  • 10. Inheritance Example class A { public void display_one() { System.Console.WriteLine("I come from A"); } } class B : A { public void display_two() { System.Console.WriteLine("I come from B, child of A"); } } class App { static void Main() { A a = new A(); // Create instance of A B b = new B(); // Create instance of B a.display_one(); // I come from A b.display_one(); // I come from A b.display_two(); // I come from B, child of A } } In-class demo of this code in Visual C# Express Enya_z, Flickr www.flickr.com/photos/nawuxika/270033468/
  • 11. Visibility • A class is a container for data and behavior • Often want to control over which code: ► Can read & write data ► Can call methods • Access modifiers: ► Public • No restrictions. Members visible to any method of any class ► Private • Members in class A marked private only accessible to methods of class A • Default visibility of class variables ► Protected • Members in class A marked protected accessible to methods of class A and subclasses of A. Clearly Ambiguous, Flickr www.flickr.com/photos/clearlyambiguous/47022668/
  • 12. Visibility Example class A { public int num_slugs; protected int num_trees; … } class B : A { private int num_tree_sitters; … } class C { … } • Class A can see: ► num_slugs: is public ► num_trees: is protected, but is defined in A • Class B can see: ► num_slugs: is public in A ► num_trees: is protected in parent A ► num_tree_sitters: is private, but is defined in B • Class C can see: ► num_slugs: is public in A ► Can’t see: • num_trees: protected in A • num_tree_sitters: private in BRaindog, Flickr www.flickr.com/photos/raindog/ 436176848/
  • 13. Constructors • Use “new” to create a new object instance ► This causes the “constructor” to be called • A constructor is a method called when an object is created ► C# provides a default constructor for every class • Creates object but takes no other action ► Typically classes have explicitly provided constructor • Constructor ► Has same name as the class ► Can take arguments ► Usually public, though not always • Singleton design pattern makes constructor private to ensure only one object instance is created bucklava, Flickr www.flickr.com/photos/9229859@N02/1985775921/
  • 14. Type System • Value types ► Directly contain data ► Cannot be null ► Allocated on the stack • Reference types ► Contain references to objects ► May be null ► Allocated on the heap int i = 123;int i = 123; string s = "Hello world";string s = "Hello world"; 123123ii ss "Hello world""Hello world" Slide adapted from “Introduction to C#”, Anders Hejlsberg www.ecma-international.org/activities/Languages/ Introduction%20to%20Csharp.ppt Numeral type, by threedots www.flickr.com/photos/threedots/115805043/
  • 15. Predefined Types • C# predefined types ► Reference object, string ► Signed sbyte, short, int, long ► Unsigned byte, ushort, uint, ulong ► Character char ► Floating-point float, double, decimal ► Logical bool • Predefined types are simply aliases for system- provided types ► For example, int == System.Int32 Slide from “Introduction to C#”, Anders Hejlsberg www.ecma-international.org/activities/Languages/ Introduction%20to%20Csharp.ppt
  • 16. Unusual types in C# • Bool ► Holds a boolean value, “true” or “false” ► Integer values do not equal to boolean values • 0 does not equal false • There is no built-in conversion from integer to boolean • Decimal ► A fixed precision number up to 28 digits plus decimal point ► Useful for money calculations ► 300.5m • Suffix “m” or “M” indicates decimal tackyspoons, Flickr www.flickr.com/photos/tackyspoons/812710409/
  • 17. Unified type system • All types ultimately inherit from object ► Classes, enums, arrays, delegates, structs, … • An implicit conversion exists from any type to type object StreamStream MemoryStreamMemoryStream FileStreamFileStream HashtableHashtable doubledoubleintint objectobject Slide from “Introduction to C#”, Anders Hejlsberg www.ecma-international.org/activities/Languages/ Introduction%20to%20Csharp.ppt
  • 18. Variables • Variables must be initialized or assigned to before first use • Class members take a visibility operator beforehand • Constants cannot be changed type variable-name [= initialization-expression]; Examples: int number_of_slugs = 0; string name; float myfloat = 0.5f; bool hotOrNot = true; Also constants: const int freezingPoint = 32;
  • 19. Enumerations • Base type can be any integral type (ushort, long) except for char • Defaults to int • Must cast to int to display in Writeln ► Example: (int)g.gradeA enum identifier [: base-type] { enumerator-list} Example: enum Grades { gradeA = 94, gradeAminus = 90, gradeBplus = 87, gradeB = 84 }
  • 20. Conditionals • C# supports C/C++/Java syntax for “if” statement • Expression must evaluate to a bool value ► No integer expressions here • == means “equal to” for boolean comparison ► if (i == 5) // if i equals 5 ► if (i = 5) // error, since i = 5 is not a boolean expression if (expression) statement1 [else statement2] Example: if (i < 5) { System.Console.Writeln(“i is smaller than 5”); } else { System.Console.Writeln(“i is greater than or equal to 5”); }
  • 21. Switch statement • Alternative to if • Typically use break • Can use goto to continue to another case switch (expression) { case constant-expression: statement(s); jump-statement [default: statement(s);] Example: const int raining = 1; const int snowing = 0; int weather = snowing; switch (weather) { case snowing: System.Console.Writeln(“It is snowing!”); goto case raining; case raining; System.Console.Writeln(“I am wet!”); break; default: System.Console.Writeln(“Weather OK”); break; }
  • 22. Homework • Read in Programming C# ► Chapter 1 (C# and the .NET Framework) ► Chapter 2 (Getting Started: "Hello World") ► Chapter 3 (C# Language Fundamentals) • Try one of the example code samples for yourself in Visual C# Express ► Work with your partner • Book is available online, via O’Reilly Safari ► http://safari.oreilly.com/0596006993 ► Use on-campus computer to access
  • 23. More resources • Introduction to C# Anders Hejlsberg ► http://www.ecma-international.org/activities/Languages/Introduction%20to%20Csharp.ppt ► High-level powerpoint presentation introducing the C# language by its designer