SlideShare a Scribd company logo
Introduction to C#
Mark Sapossnek
CS 594
Computer Science Department
Metropolitan College
Boston University
Prerequisites
īˇ This module assumes that you understand the
fundamentals of
īŽ Programming
īŦ Variables, statements, functions, loops, etc.
īŽ Object-oriented programming
īŦ Classes, inheritance, polymorphism,
members, etc.
īŦ C++ or Java
Learning Objectives
īˇ C# design goals
īˇ Fundamentals of the C# language
īŽ Types, program structure, statements, operators
īˇ Be able to begin writing and debugging C#
programs
īŽ Using the .NET Framework SDK
īŽ Using Visual Studio.NET
īˇ Be able to write individual C# methods
Agenda
īˇ Hello World
īˇ Design Goals of C#
īˇ Types
īˇ Program Structure
īˇ Statements
īˇ Operators
īˇ Using Visual Studio.NET
īˇ Using the .NET Framework SDK
Hello World
using System;
class Hello {
static void Main( ) {
Console.WriteLine("Hello world");
Console.ReadLine(); // Hit enter to finish
}
}
Agenda
īˇ Hello World
īˇ Design Goals of C#
īˇ Types
īˇ Program Structure
īˇ Statements
īˇ Operators
īˇ Using Visual Studio.NET
īˇ Using the .NET Framework SDK
Design Goals of C#
The Big Ideas
īˇ Component-orientation
īˇ Everything is an object
īˇ Robust and durable software
īˇ Preserving your investment
Design Goals of C#
Component-Orientation
īˇ C# is the first “Component-Oriented” language in
the C/C++ family
īˇ What is a component?
īŽ An independent module of reuse and deployment
īŽ Coarser-grained than objects
(objects are language-level constructs)
īŽ Includes multiple classes
īŽ Often language-independent
īŽ In general, component writer and user don’t know
each other, don’t work for the same company, and
don’t use the same language
Design Goals of C#
Component-Orientation
īˇ Component concepts are first class
īŽ Properties, methods, events
īŽ Design-time and run-time attributes
īŽ Integrated documentation using XML
īˇ Enables “one-stop programming”
īŽ No header files, IDL, etc.
īŽ Can be embedded in ASP pages
Design Goals of C#
Everything is an Object
īˇ Traditional views
īŽ C++, Javaâ„ĸ: Primitive types are “magic” and do not
interoperate with objects
īŽ Smalltalk, Lisp: Primitive types are objects, but at
some performance cost
īˇ C# unifies with no performance cost
īŽ Deep simplicity throughout system
īˇ Improved extensibility and reusability
īŽ New primitive types: Decimal, SQLâ€Ļ
īŽ Collections, etc., work for all types
Design Goals of C#
Robust and Durable Software
īˇ Garbage collection
īŽ No memory leaks and stray pointers
īˇ Exceptions
īˇ Type-safety
īŽ No uninitialized variables, no unsafe casts
īˇ Versioning
īˇ Avoid common errors
īŽ E.g. if (x = y) ...
īˇ One-stop programming
īŽ Fewer moving parts
Design Goals of C#
Preserving Your Investment
īˇ C++ Heritage
īŽ Namespaces, pointers (in unsafe code),
unsigned types, etc.
īŽ Some changes, but no unnecessary sacrifices
īˇ Interoperability
īŽ What software is increasingly about
īŽ C# talks to XML, SOAP, COM, DLLs, and any
.NET Framework language
īˇ Increased productivity
īŽ Short learning curve
īŽ Millions of lines of C# code in .NET
Agenda
īˇ Hello World
īˇ Design Goals of C#
īˇ Types
īˇ Program Structure
īˇ Statements
īˇ Operators
īˇ Using Visual Studio.NET
īˇ Using the .NET Framework SDK
Types
Overview
īˇ A C# program is a collection of types
īŽ Classes, structs, enums, interfaces, delegates
īˇ C# provides a set of predefined types
īŽ E.g. int, byte, char, string, object, â€Ļ
īˇ You can create your own types
īˇ All data and code is defined within
a type
īŽ No global variables, no global functions
Types
Overview
īˇ Types contain:
īŽ Data members
īŦ Fields, constants, arrays
īŦ Events
īŽ Function members
īŦ Methods, operators, constructors, destructors
īŦ Properties, indexers
īŽ Other types
īŦ Classes, structs, enums, interfaces, delegates
Types
Overview
īˇ Types can be instantiatedâ€Ļ
īŽ â€Ļand then used: call methods,
get and set properties, etc.
īˇ Can convert from one type to another
īŽ Implicitly and explicitly
īˇ Types are organized
īŽ Namespaces, files, assemblies
īˇ There are two categories of types:
value and reference
īˇ Types are arranged in a hierarchy
Types
Unified Type System
īˇ Value types
īŽ Directly contain data
īŽ Cannot be null
īˇ Reference types
īŽ Contain references to objects
īŽ May be null
int i = 123;
string s = "Hello world";
123
i
s "Hello world"
Types
Unified Type System
īˇ Value types
īŽ Primitives int i; float x;
īŽ Enums enum State { Off, On }
īŽ Structs struct Point {int x,y;}
īˇ Reference types
īŽ Root object
īŽ String string
īŽ Classes class Foo: Bar, IFoo {...}
īŽ Interfaces interface IFoo: IBar {...}
īŽ Arrays string[] a = new string[10];
īŽ Delegates delegate void Empty();
Types
Unified Type System
Value (Struct) Reference (Class)
Variable holds Actual value Memory location
Allocated on Stack, member Heap
Nullability Always has value May be null
Default value 0 null
Aliasing (in a scope) No Yes
Assignment means Copy data Copy reference
Types
Unified Type System
īˇ Benefits of value types
īŽ No heap allocation, less GC pressure
īŽ More efficient use of memory
īŽ Less reference indirection
īŽ Unified type system
īŦ No primitive/object dichotomy
Types
Conversions
īˇ Implicit conversions
īŽ Occur automatically
īŽ Guaranteed to succeed
īŽ No information (precision) loss
īˇ Explicit conversions
īŽ Require a cast
īŽ May not succeed
īŽ Information (precision) might be lost
īˇ Both implicit and explicit conversions can be
user-defined
Types
Conversions
int x = 123456;
long y = x; // implicit
short z = (short)x; // explicit
double d = 1.2345678901234;
float f = (float)d; // explicit
long l = (long)d; // explicit
Types
Unified Type System
īˇ Everything is an object
īŽ All types ultimately inherit from object
īŽ Any piece of data can be stored, transported, and
manipulated with no extra work
MemoryStream FileStream
Stream Hashtable int double
object
Types
Unified Type System
īˇ Polymorphism
īŽ The ability to perform an operation on an object
without knowing the precise type of the object
void Poly(object o) {
Console.WriteLine(o.ToString());
}
Poly(42);
Poly(“abcd”);
Poly(12.345678901234m);
Poly(new Point(23,45));
Types
Unified Type System
īˇ Question: How can we treat value and reference
types polymorphically?
īŽ How does an int (value type) get converted into an
object (reference type)?
īˇ Answer: Boxing!
īŽ Only value types get boxed
īŽ Reference types do not get boxed
Types
Unified Type System
īˇ Boxing
īŽ Copies a value type into a reference type (object)
īŽ Each value type has corresponding “hidden”
reference type
īŽ Note that a reference-type copy is made of the
value type
īŦ Value types are never aliased
īŽ Value type is converted implicitly to object, a
reference type
īŦ Essentially an “up cast”
Types
Unified Type System
īˇ Unboxing
īŽ Inverse operation of boxing
īŽ Copies the value out of the box
īŦ Copies from reference type to value type
īŽ Requires an explicit conversion
īŦ May not succeed (like all explicit conversions)
īŦ Essentially a “down cast”
Types
Unified Type System
īˇ Boxing and unboxing
int i = 123;
object o = i;
int j = (int)o;
123
i
o
123
j
123
System.Int32
Types
Unified Type System
īˇ Benefits of boxing
īŽ Enables polymorphism across all types
īŽ Collection classes work with all types
īŽ Eliminates need for wrapper classes
īŽ Replaces OLE Automation's Variant
īˇ Lots of examples in .NET Framework
Hashtable t = new Hashtable();
t.Add(0, "zero");
t.Add(1, "one");
t.Add(2, "two");
string s = string.Format(
"Your total was {0} on {1}",
total, date);
Types
Unified Type System
īˇ Disadvantages of boxing
īŽ Performance cost
īˇ The need for boxing will decrease when the CLR
supports generics (similar to C++ templates)
Types
Predefined Types
īˇ Value
īŽ Integral types
īŽ Floating point types
īŽ decimal
īŽ bool
īŽ char
īˇ Reference
īŽ object
īŽ string
Predefined Types
Value Types
īˇ All are predefined structs
Signed sbyte, short, int, long
Unsigned byte, ushort, uint, ulong
Character char
Floating point float, double, decimal
Logical bool
Predefined Types
Integral Types
C# Type System Type Size (bytes) Signed?
sbyte System.Sbyte 1 Yes
short System.Int16 2 Yes
int System.Int32 4 Yes
long System.Int64 8 Yes
byte System.Byte 1 No
ushort System.UInt16 2 No
uint System.UInt32 4 No
ulong System.UInt64 8 No
Predefined Types
Floating Point Types
īˇ Follows IEEE 754 specification
īˇ Supports Âą 0, Âą Infinity, NaN
C# Type System Type Size (bytes)
float System.Single 4
double System.Double 8
Predefined Types
decimal
īˇ 128 bits
īˇ Essentially a 96 bit value scaled by a
power of 10
īˇ Decimal values represented precisely
īˇ Doesn’t support signed zeros, infinities
or NaN
C# Type System Type Size (bytes)
decimal System.Decimal 16
Predefined Types
decimal
īˇ All integer types can be implicitly converted to a
decimal type
īˇ Conversions between decimal and floating types
require explicit conversion due to possible loss
of precision
īˇ s * m * 10e
īŽ s = 1 or –1
īŽ 0 ī‚Ŗ m ī‚Ŗ 296
īŽ -28 ī‚Ŗ e ī‚Ŗ 0
Predefined Types
Integral Literals
īˇ Integer literals can be expressed as decimal
or hexadecimal
īˇ U or u: uint or ulong
īˇ L or l: long or ulong
īˇ UL or ul: ulong
123 // Decimal
0x7B // Hexadecimal
123U // Unsigned
123ul // Unsigned long
123L // Long
Predefined Types
Real Literals
īˇ F or f: float
īˇ D or d: double
īˇ M or m: decimal
123f // Float
123D // Double
123.456m // Decimal
1.23e2f // Float
12.3E1M // Decimal
Predefined Types
bool
īˇ Represents logical values
īˇ Literal values are true and false
īˇ Cannot use 1 and 0 as boolean values
īŽ No standard conversion between other types
and bool
C# Type System Type Size (bytes)
bool System.Boolean 1 (2 for arrays)
Predefined Types
char
īˇ Represents a Unicode character
īˇ Literals
īŽ ‘A’ // Simple character
īŽ ‘u0041’ // Unicode
īŽ ‘x0041’ // Unsigned short hexadecimal
īŽ ‘n’ // Escape sequence character
C# Type System Type Size (bytes)
Char System.Char 2
Predefined Types
char
īˇ Escape sequence characters (partial list)
Char Meaning Value
’ Single quote 0x0027
” Double quote 0x0022
 Backslash 0x005C
0 Null 0x0000
n New line 0x000A
r Carriage return 0x000D
t Tab 0x0009
Predefined Types
Reference Types
Root type object
Character string string
Predefined Types
object
īˇ Root of object hierarchy
īˇ Storage (book keeping) overhead
īŽ 0 bytes for value types
īŽ 8 bytes for reference types
īˇ An actual reference (not the object)
uses 4 bytes
C# Type System Type Size (bytes)
object System.Object 0/8 overhead
Predefined Types
object Public Methods
īˇ public bool Equals(object)
īˇ protected void Finalize()
īˇ public int GetHashCode()
īˇ public System.Type GetType()
īˇ protected object MemberwiseClone()
īˇ public void Object()
īˇ public string ToString()
Predefined Types
string
īˇ An immutable sequence of Unicode characters
īˇ Reference type
īˇ Special syntax for literals
īŽ string s = “I am a string”;
C# Type System Type Size (bytes)
String System.String 20 minimum
Predefined Types
string
īˇ Normally have to use escape characters
īˇ Verbatim string literals
īŽ Most escape sequences ignored
īŦ Except for “”
īŽ Verbatim literals can be multi-line
string s1= “serverfilesharefilename.cs”;
string s2 = @“serverfilesharefilename.cs”;
Types
User-defined Types
īˇ User-defined types
Enumerations enum
Arrays int[], string[]
Interface interface
Reference type class
Value type struct
Function pointer delegate
Types
Enums
īˇ An enum defines a type name for a related
group of symbolic constants
īˇ Choices must be known at compile-time
īˇ Strongly typed
īŽ No implicit conversions to/from int
īŽ Can be explicitly converted
īŽ Operators: +, -, ++, --, &, |, ^, ~, â€Ļ
īˇ Can specify underlying type
īŽ byte, sbyte, short, ushort, int, uint, long, ulong
Types
Enums
enum Color: byte {
Red = 1,
Green = 2,
Blue = 4,
Black = 0,
White = Red | Green | Blue
}
Color c = Color.Black;
Console.WriteLine(c); // 0
Console.WriteLine(c.Format()); // Black
Types
Enums
īˇ All enums derive from System.Enum
īŽ Provides methods to
īŦ determine underlying type
īŦ test if a value is supported
īŦ initialize from string constant
īŦ retrieve all values in enum
īŦ â€Ļ
Types
Arrays
īˇ Arrays allow a group of elements of a specific
type to be stored in a contiguous block of
memory
īˇ Arrays are reference types
īˇ Derived from System.Array
īˇ Zero-based
īˇ Can be multidimensional
īŽ Arrays know their length(s) and rank
īˇ Bounds checking
Types
Arrays
īˇ Declare
īˇ Allocate
īˇ Initialize
īˇ Access and assign
īˇ Enumerate
int[] primes;
int[] primes = new int[9];
int[] prime = new int[] {1,2,3,5,7,11,13,17,19};
int[] prime = {1,2,3,5,7,11,13,17,19};
prime2[i] = prime[i];
foreach (int i in prime) Console.WriteLine(i);
Types
Arrays
īˇ Multidimensional arrays
īŽ Rectangular
īŦ int[,] matR = new int[2,3];
īŦ Can initialize declaratively
īŦ int[,] matR =
new int[2,3] { {1,2,3}, {4,5,6} };
īŽ Jagged
īŦ An array of arrays
īŦ int[][] matJ = new int[2][];
īŦ Must initialize procedurally
Types
Interfaces
īˇ An interface defines a contract
īŽ Includes methods, properties, indexers, events
īŽ Any class or struct implementing an interface must
support all parts of the contract
īˇ Interfaces provide polymorphism
īŽ Many classes and structs may implement
a particular interface
īˇ Contain no implementation
īŽ Must be implemented by a class or struct
Types
Classes
īˇ User-defined reference type
īŽ Similar to C++, Java classes
īˇ Single class inheritance
īˇ Multiple interface inheritance
Types
Classes
īˇ Members
īŽ Constants, fields, methods, operators,
constructors, destructors
īŽ Properties, indexers, events
īŽ Static and instance members
īˇ Member access
īŽ public, protected, private, internal,
protected internal
īŦ Default is private
īˇ Instantiated with new operator
Types
Structs
īˇ Similar to classes, but
īŽ User-defined value type
īŽ Always inherits from object
īˇ Ideal for lightweight objects
īŽ int, float, double, etc., are all structs
īŽ User-defined “primitive” types
īŦ Complex, point, rectangle, color, rational
īˇ Multiple interface inheritance
īˇ Same members as class
īˇ Member access
īŽ public, internal, private
īˇ Instantiated with new operator
Types
Classes and Structs
struct SPoint { int x, y; ... }
class CPoint { int x, y; ... }
SPoint sp = new SPoint(10, 20);
CPoint cp = new CPoint(10, 20);
10
20
sp
cp
10
20
CPoint
Types
Delegates
īˇ A delegate is a reference type that defines a
method signature
īˇ When instantiated, a delegate holds one or more
methods
īŽ Essentially an object-oriented function pointer
īˇ Foundation for framework events
Agenda
īˇ Hello World
īˇ Design Goals of C#
īˇ Types
īˇ Program Structure
īˇ Statements
īˇ Operators
īˇ Using Visual Studio.NET
īˇ Using the .NET Framework SDK
Program Structure
Overview
īˇ Organizing Types
īˇ Namespaces
īˇ References
īˇ Main Method
īˇ Syntax
Program Structure
Organizing Types
īˇ Physical organization
īŽ Types are defined in files
īŽ Files are compiled into
modules
īŽ Modules are grouped
into assemblies
Assembly
Module
File
Type
Program Structure
Organizing Types
īˇ Types are defined in files
īŽ A file can contain multiple types
īŽ Each type is defined in a single file
īˇ Files are compiled into modules
īŽ Module is a DLL or EXE
īŽ A module can contain multiple files
īˇ Modules are grouped into assemblies
īŽ Assembly can contain multiple modules
īŽ Assemblies and modules are often 1:1
Program Structure
Organizing Types
īˇ Types are defined in ONE place
īŽ “One-stop programming”
īŽ No header and source files to synchronize
īŽ Code is written “in-line”
īŽ Declaration and definition are one and
the same
īŽ A type must be fully defined in one file
īŦ Can’t put individual methods in different files
īˇ No declaration order dependence
īŽ No forward references required
Program Structure
Namespaces
īˇ Namespaces provide a way to
uniquely identify a type
īˇ Provides logical organization of types
īˇ Namespaces can span assemblies
īˇ Can nest namespaces
īˇ There is no relationship between namespaces
and file structure (unlike Java)
īˇ The fully qualified name of a type includes all
namespaces
Program Structure
Namespaces
namespace N1 { // N1
class C1 { // N1.C1
class C2 { // N1.C1.C2
}
}
namespace N2 { // N1.N2
class C2 { // N1.N2.C2
}
}
}
Program Structure
Namespaces
īˇ The using statement lets you use types without
typing the fully qualified name
īˇ Can always use a fully qualified name
using N1;
C1 a; // The N1. is implicit
N1.C1 b; // Fully qualified name
C2 c; // Error! C2 is undefined
N1.N2.C2 d; // One of the C2 classes
C1.C2 e; // The other one
Program Structure
Namespaces
īˇ The using statement also lets you create
aliases
using C1 = N1.N2.C1;
using N2 = N1.N2;
C1 a; // Refers to N1.N2.C1
N2.C1 b; // Refers to N1.N2.C1
Program Structure
Namespaces
īˇ Best practice: Put all of your types in a unique
namespace
īˇ Have a namespace for your company, project,
product, etc.
īˇ Look at how the .NET Framework classes are
organized
Program Structure
References
īˇ In Visual Studio you specify references
for a project
īˇ Each reference identifies a specific assembly
īˇ Passed as reference (/r or /reference)
to the C# compiler
csc HelloWorld.cs /reference:System.WinForms.dll
Program Structure
Namespaces vs. References
īˇ Namespaces provide language-level naming
shortcuts
īŽ Don’t have to type a long fully qualified name over
and over
īˇ References specify which assembly to use
Program Structure
Main Method
īˇ Execution begins at the static Main() method
īˇ Can have only one method with one of
the following signatures in an assembly
īŽ static void Main()
īŽ static int Main()
īŽ static void Main(string[] args)
īŽ static int Main(string[] args)
Program Structure
Syntax
īˇ Identifiers
īŽ Names for types, methods, fields, etc.
īŽ Must be whole word – no white space
īŽ Unicode characters
īŽ Begins with letter or underscore
īŽ Case sensitive
īŽ Must not clash with keyword
īŦ Unless prefixed with @
Agenda
īˇ Hello World
īˇ Design Goals of C#
īˇ Types
īˇ Program Structure
īˇ Statements
īˇ Operators
īˇ Using Visual Studio.NET
īˇ Using the .NET Framework SDK
Statements
Overview
īˇ High C++ fidelity
īˇ if, while, do require bool condition
īˇ goto can’t jump into blocks
īˇ switch statement
īŽ No fall-through
īˇ foreach statement
īˇ checked and unchecked statements
īˇ Expression
statements
must do work
void Foo() {
i == 1; // error
}
Statements
Overview
īˇ Statement lists
īˇ Block statements
īˇ Labeled statements
īˇ Declarations
īŽ Constants
īŽ Variables
īˇ Expression statements
īŽ checked, unchecked
īŽ lock
īŽ using
īˇ Conditionals
īŽ if
īŽ switch
īˇ Loop Statements
īŽ while
īŽ do
īŽ for
īŽ foreach
īˇ Jump Statements
īŽ break
īŽ continue
īŽ goto
īŽ return
īŽ throw
īˇ Exception handling
īŽ try
īŽ throw
Statements
Syntax
īˇ Statements are terminated with a
semicolon (;)
īˇ Just like C, C++ and Java
īˇ Block statements { ... } don’t need a semicolon
Statements
Syntax
īˇ Comments
īŽ // Comment a single line, C++ style
īŽ /* Comment multiple
lines,
C style
*/
Statements
Statement Lists & Block Statements
īˇ Statement list: one or more statements in
sequence
īˇ Block statement: a statement list delimited by
braces { ... }
static void Main() {
F();
G();
{ // Start block
H();
; // Empty statement
I();
} // End block
}
Statements
Variables and Constants
static void Main() {
const float pi = 3.14f;
const int r = 123;
Console.WriteLine(pi * r * r);
int a;
int b = 2, c = 3;
a = 1;
Console.WriteLine(a + b + c);
}
Statements
Variables and Constants
īˇ The scope of a variable or constant runs
from the point of declaration to the end of
the enclosing block
Statements
Variables and Constants
īˇ Within the scope of a variable or constant it is an
error to declare another variable or constant with
the same name
{
int x;
{
int x; // Error: can’t hide variable x
}
}
Statements
Variables
īˇ Variables must be assigned a value before they
can be used
īŽ Explicitly or automatically
īŽ Called definite assignment
īˇ Automatic assignment occurs for static fields,
class instance fields and array elements
void Foo() {
string s;
Console.WriteLine(s); // Error
}
Statements
Labeled Statements & goto
īˇ goto can be used to transfer control within or
out of a block, but not into a nested block
static void Find(int value, int[,] values,
out int row, out int col) {
int i, j;
for (i = 0; i < values.GetLength(0); i++)
for (j = 0; j < values.GetLength(1); j++)
if (values[i, j] == value) goto found;
throw new InvalidOperationException(“Not found");
found:
row = i; col = j;
}
Statements
Expression Statements
īˇ Statements must do work
īŽ Assignment, method call, ++, --, new
static void Main() {
int a, b = 2, c = 3;
a = b + c;
a++;
MyClass.Foo(a,b,c);
Console.WriteLine(a + b + c);
a == 2; // ERROR!
}
Statements
if Statement
īˇ Requires bool expression
int Test(int a, int b) {
if (a > b)
return 1;
else if (a < b)
return -1;
else
return 0;
}
Statements
switch Statement
īˇ Can branch on any predefined type
(including string) or enum
īŽ User-defined types can provide implicit conversion
to these types
īˇ Must explicitly state how to end case
īŽ With break, goto case, goto label, return,
throw or continue
īŽ Eliminates fall-through bugs
īŽ Not needed if no code supplied after the label
Statements
switch Statement
int Test(string label) {
int result;
switch(label) {
case null:
goto case “runner-up”;
case “fastest”:
case “winner”:
result = 1; break;
case “runner-up”:
result = 2; break;
default:
result = 0;
}
return result;
}
Statements
while Statement
īˇ Requires bool expression
int i = 0;
while (i < 5) {
...
i++;
}
int i = 0;
do {
...
i++;
}
while (i < 5); while (true) {
...
}
Statements
for Statement
for (int i=0; i < 5; i++) {
...
}
for (;;) {
...
}
Statements
foreach Statement
īˇ Iteration of arrays
public static void Main(string[] args) {
foreach (string s in args)
Console.WriteLine(s);
}
Statements
foreach Statement
īˇ Iteration of user-defined collections
īˇ Created by implementing IEnumerable
foreach (Customer c in customers.OrderBy("name")) {
if (c.Orders.Count != 0) {
...
}
}
Statements
Jump Statements
īˇ break
īŽ Exit inner-most loop
īˇ continue
īŽ End iteration of inner-most loop
īˇ goto <label>
īŽ Transfer execution to label statement
īˇ return [<expression>]
īŽ Exit a method
īˇ throw
īŽ See exception handling
Statements
Exception Handling
īˇ Exceptions are the C# mechanism for handling
unexpected error conditions
īˇ Superior to returning status values
īŽ Can’t be ignored
īŽ Don’t have to handled at the point they occur
īŽ Can be used even where values are not returned
(e.g. accessing a property)
īŽ Standard exceptions are provided
Statements
Exception Handling
īˇ try...catch...finally statement
īˇ try block contains code that could throw an
exception
īˇ catch block handles exceptions
īŽ Can have multiple catch blocks to handle different
kinds of exceptions
īˇ finally block contains code that will always be
executed
īŽ Cannot use jump statements (e.g. goto)
to exit a finally block
Statements
Exception Handling
īˇ throw statement raises an exception
īˇ An exception is represented as an instance of
System.Exception or derived class
īŽ Contains information about the exception
īŽ Properties
īŦ Message
īŦ StackTrace
īŦ InnerException
īˇ You can rethrow an exception, or catch
one exception and throw another
Statements
Exception Handling
try {
Console.WriteLine("try");
throw new Exception(“message”);
}
catch (ArgumentNullException e) {
Console.WriteLine(“caught null argument");
}
catch {
Console.WriteLine("catch");
}
finally {
Console.WriteLine("finally");
}
Statements
Synchronization
īˇ Multi-threaded applications have to protect
against concurrent access to data
īŽ Must prevent data corruption
īˇ The lock statement uses an instance to provide
mutual exclusion
īŽ Only one lock statement can have access to the
same instance
īŽ Actually uses the .NET Framework
System.Threading.Monitor class to
provide mutual exclusion
Statements
Synchronization
public class CheckingAccount {
decimal balance;
public void Deposit(decimal amount) {
lock (this) {
balance += amount;
}
}
public void Withdraw(decimal amount) {
lock (this) {
balance -= amount;
}
}
}
Statements
using Statement
īˇ C# uses automatic memory management
(garbage collection)
īŽ Eliminates most memory management problems
īˇ However, it results in non-deterministic
finalization
īŽ No guarantee as to when and if object destructors
are called
Statements
using Statement
īˇ Objects that need to be cleaned up after use
should implement the System.IDisposable
interface
īŽ One method: Dispose()
īˇ The using statement allows you to create an
instance, use it, and then ensure that Dispose
is called when done
īŽ Dispose is guaranteed to be called, as if it were in a
finally block
Statements
using Statement
public class MyResource : IDisposable {
public void MyResource() {
// Acquire valuble resource
}
public void Dispose() {
// Release valuble resource
}
public void DoSomething() {
...
}
} using (MyResource r = new MyResource()) {
r.DoSomething();
} // r.Dispose() is called
Statements
checked and unchecked Statements
īˇ The checked and unchecked statements allow
you to control overflow checking for integral-type
arithmetic operations and conversions
īˇ checked forces checking
īˇ unchecked forces no checking
īˇ Can use both as block statements or
as an expression
īˇ Default is unchecked
īˇ Use the /checked compiler option to make
checked the default
Statements
Basic Input/Output Statements
īˇ Console applications
īŽ System.Console.WriteLine();
īŽ System.Console.ReadLine();
īˇ Windows applications
īŽ System.WinForms.MessageBox.Show();
string v1 = “some value”;
MyObject v2 = new MyObject();
Console.WriteLine(“First is {0}, second is {1}”,
v1, v2);
Agenda
īˇ Hello World
īˇ Design Goals of C#
īˇ Types
īˇ Program Structure
īˇ Statements
īˇ Operators
īˇ Using Visual Studio.NET
īˇ Using the .NET Framework SDK
Operators
Overview
īˇ C# provides a fixed set of operators, whose
meaning is defined for the predefined types
īˇ Some operators can be overloaded (e.g. +)
īˇ The following table summarizes the C#
operators by category
īŽ Categories are in order of decreasing precedence
īŽ Operators in each category have the same
precedence
Operators
Precedence
Category Operators
Primary
Grouping: (x)
Member access: x.y
Method call: f(x)
Indexing: a[x]
Post-increment: x++
Post-decrement: x—
Constructor call: new
Type retrieval: typeof
Arithmetic check on: checked
Arithmetic check off: unchecked
Operators
Precedence
Category Operators
Unary
Positive value of: +
Negative value of: -
Not: !
Bitwise complement: ~
Pre-increment: ++x
Post-decrement: --x
Type cast: (T)x
Multiplicative
Multiply: *
Divide: /
Division remainder: %
Operators
Precedence
Category Operators
Additive
Add: +
Subtract: -
Shift
Shift bits left: <<
Shift bits right: >>
Relational
Less than: <
Greater than: >
Less than or equal to: <=
Greater than or equal to: >=
Type equality/compatibility: is
Type conversion: as
Operators
Precedence
Category Operators
Equality
Equals: ==
Not equals: !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Logical AND &&
Logical OR ||
Operators
Precedence
Category Operators
Ternary conditional ?:
Assignment
=, *=, /=, %=, +=, -=, <<=, >>=,
&=, ^=, |=
Operators
Associativity
īˇ Assignment and ternary conditional operators
are right-associative
īŽ Operations performed right to left
īŽ x = y = z evaluates as x = (y = z)
īˇ All other binary operators are left-associative
īŽ Operations performed left to right
īŽ x + y + z evaluates as (x + y) + z
īˇ Use parentheses to control order
Agenda
īˇ Hello World
īˇ Design Goals of C#
īˇ Types
īˇ Program Structure
īˇ Statements
īˇ Operators
īˇ Using Visual Studio.NET
īˇ Using the .NET Framework SDK
Using Visual Studio.NET
īˇ Types of projects
īŽ Console Application
īŽ Windows Application
īŽ Web Application
īŽ Web Service
īŽ Windows Service
īŽ Class Library
īŽ ...
Using Visual Studio.NET
īˇ Windows
īŽ Solution Explorer
īŽ Class View
īŽ Properties
īŽ Output
īŽ Task List
īŽ Object Browser
īŽ Server Explorer
īŽ Toolbox
Using Visual Studio.NET
īˇ Building
īˇ Debugging
īŽ Break points
īˇ References
īˇ Saving
Agenda
īˇ Hello World
īˇ Design Goals of C#
īˇ Types
īˇ Program Structure
īˇ Statements
īˇ Operators
īˇ Using Visual Studio.NET
īˇ Using the .NET Framework SDK
Using .NET Framework SDK
īˇ Compiling from command line
csc /r:System.WinForms.dll class1.cs file1.cs
More Resources
īˇ http://msdn.microsoft.com
īˇ http://windows.oreilly.com/news/hejlsberg_0800.html
īˇ http://www.csharphelp.com/
īˇ http://www.csharp-station.com/
īˇ http://www.csharpindex.com/
īˇ http://msdn.microsoft.com/msdnmag/issues/0900/csharp/cs
harp.asp
īˇ http://www.hitmill.com/programming/dotNET/csharp.html
īˇ http://www.c-sharpcorner.com/
īˇ http://msdn.microsoft.com/library/default.asp?URL=/libr
ary/dotnet/csspec/vclrfcsharpspec_Start.htm

More Related Content

Similar to IntroductionToCSharp.ppt

Introduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh SinghIntroduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh Singh
singhadarsh
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
megersaoljira
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
Almamoon
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
mothertheressa
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
SDFG5
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
NALESVPMEngg
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
InfinityWorld3
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
ssusera0bb35
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
Abou Bakr Ashraf
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
Ananthu Mahesh
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
Vasuki Ramasamy
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
MAHESHV559910
 
Csharp
CsharpCsharp
Csharp
Swaraj Kumar
 
PERTEMUAN 1 - MENGENAL ENVIRONTMENT PROGRAM VISUAL C#.pptx
PERTEMUAN 1 - MENGENAL ENVIRONTMENT PROGRAM VISUAL C#.pptxPERTEMUAN 1 - MENGENAL ENVIRONTMENT PROGRAM VISUAL C#.pptx
PERTEMUAN 1 - MENGENAL ENVIRONTMENT PROGRAM VISUAL C#.pptx
TriSandhikaJaya
 
C#ppt
C#pptC#ppt
C#
C#C#
C#
Joni
 
.Net Framework Introduction
.Net Framework Introduction.Net Framework Introduction
.Net Framework Introduction
Abhishek Sahu
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
Shoaib Ghachi
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
Md. Mahedee Hasan
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
Rasan Samarasinghe
 

Similar to IntroductionToCSharp.ppt (20)

Introduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh SinghIntroduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh Singh
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
 
Csharp
CsharpCsharp
Csharp
 
PERTEMUAN 1 - MENGENAL ENVIRONTMENT PROGRAM VISUAL C#.pptx
PERTEMUAN 1 - MENGENAL ENVIRONTMENT PROGRAM VISUAL C#.pptxPERTEMUAN 1 - MENGENAL ENVIRONTMENT PROGRAM VISUAL C#.pptx
PERTEMUAN 1 - MENGENAL ENVIRONTMENT PROGRAM VISUAL C#.pptx
 
C#ppt
C#pptC#ppt
C#ppt
 
C#
C#C#
C#
 
.Net Framework Introduction
.Net Framework Introduction.Net Framework Introduction
.Net Framework Introduction
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 

More from ReemaAsker1

frontendwebdevelopment-190510024804 (1).pptx
frontendwebdevelopment-190510024804 (1).pptxfrontendwebdevelopment-190510024804 (1).pptx
frontendwebdevelopment-190510024804 (1).pptx
ReemaAsker1
 
IntroductionToCSharp.ppt
IntroductionToCSharp.pptIntroductionToCSharp.ppt
IntroductionToCSharp.ppt
ReemaAsker1
 
Programming Lesson by Slidesgo - Copy.pptx
Programming Lesson by Slidesgo - Copy.pptxProgramming Lesson by Slidesgo - Copy.pptx
Programming Lesson by Slidesgo - Copy.pptx
ReemaAsker1
 
Stuttgarter Weindorf by Slidesgo.pptx
Stuttgarter Weindorf  by Slidesgo.pptxStuttgarter Weindorf  by Slidesgo.pptx
Stuttgarter Weindorf by Slidesgo.pptx
ReemaAsker1
 
Formal Presentation Template.pptx
Formal Presentation Template.pptxFormal Presentation Template.pptx
Formal Presentation Template.pptx
ReemaAsker1
 
note2_DesignPatterns (1).pptx
note2_DesignPatterns (1).pptxnote2_DesignPatterns (1).pptx
note2_DesignPatterns (1).pptx
ReemaAsker1
 
Business Case Training - Slides.pptx
Business Case Training - Slides.pptxBusiness Case Training - Slides.pptx
Business Case Training - Slides.pptx
ReemaAsker1
 

More from ReemaAsker1 (7)

frontendwebdevelopment-190510024804 (1).pptx
frontendwebdevelopment-190510024804 (1).pptxfrontendwebdevelopment-190510024804 (1).pptx
frontendwebdevelopment-190510024804 (1).pptx
 
IntroductionToCSharp.ppt
IntroductionToCSharp.pptIntroductionToCSharp.ppt
IntroductionToCSharp.ppt
 
Programming Lesson by Slidesgo - Copy.pptx
Programming Lesson by Slidesgo - Copy.pptxProgramming Lesson by Slidesgo - Copy.pptx
Programming Lesson by Slidesgo - Copy.pptx
 
Stuttgarter Weindorf by Slidesgo.pptx
Stuttgarter Weindorf  by Slidesgo.pptxStuttgarter Weindorf  by Slidesgo.pptx
Stuttgarter Weindorf by Slidesgo.pptx
 
Formal Presentation Template.pptx
Formal Presentation Template.pptxFormal Presentation Template.pptx
Formal Presentation Template.pptx
 
note2_DesignPatterns (1).pptx
note2_DesignPatterns (1).pptxnote2_DesignPatterns (1).pptx
note2_DesignPatterns (1).pptx
 
Business Case Training - Slides.pptx
Business Case Training - Slides.pptxBusiness Case Training - Slides.pptx
Business Case Training - Slides.pptx
 

Recently uploaded

dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
flufftailshop
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Jeffrey Haguewood
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 

Recently uploaded (20)

dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 

IntroductionToCSharp.ppt

  • 1. Introduction to C# Mark Sapossnek CS 594 Computer Science Department Metropolitan College Boston University
  • 2. Prerequisites īˇ This module assumes that you understand the fundamentals of īŽ Programming īŦ Variables, statements, functions, loops, etc. īŽ Object-oriented programming īŦ Classes, inheritance, polymorphism, members, etc. īŦ C++ or Java
  • 3. Learning Objectives īˇ C# design goals īˇ Fundamentals of the C# language īŽ Types, program structure, statements, operators īˇ Be able to begin writing and debugging C# programs īŽ Using the .NET Framework SDK īŽ Using Visual Studio.NET īˇ Be able to write individual C# methods
  • 4. Agenda īˇ Hello World īˇ Design Goals of C# īˇ Types īˇ Program Structure īˇ Statements īˇ Operators īˇ Using Visual Studio.NET īˇ Using the .NET Framework SDK
  • 5. Hello World using System; class Hello { static void Main( ) { Console.WriteLine("Hello world"); Console.ReadLine(); // Hit enter to finish } }
  • 6. Agenda īˇ Hello World īˇ Design Goals of C# īˇ Types īˇ Program Structure īˇ Statements īˇ Operators īˇ Using Visual Studio.NET īˇ Using the .NET Framework SDK
  • 7. Design Goals of C# The Big Ideas īˇ Component-orientation īˇ Everything is an object īˇ Robust and durable software īˇ Preserving your investment
  • 8. Design Goals of C# Component-Orientation īˇ C# is the first “Component-Oriented” language in the C/C++ family īˇ What is a component? īŽ An independent module of reuse and deployment īŽ Coarser-grained than objects (objects are language-level constructs) īŽ Includes multiple classes īŽ Often language-independent īŽ In general, component writer and user don’t know each other, don’t work for the same company, and don’t use the same language
  • 9. Design Goals of C# Component-Orientation īˇ Component concepts are first class īŽ Properties, methods, events īŽ Design-time and run-time attributes īŽ Integrated documentation using XML īˇ Enables “one-stop programming” īŽ No header files, IDL, etc. īŽ Can be embedded in ASP pages
  • 10. Design Goals of C# Everything is an Object īˇ Traditional views īŽ C++, Javaâ„ĸ: Primitive types are “magic” and do not interoperate with objects īŽ Smalltalk, Lisp: Primitive types are objects, but at some performance cost īˇ C# unifies with no performance cost īŽ Deep simplicity throughout system īˇ Improved extensibility and reusability īŽ New primitive types: Decimal, SQLâ€Ļ īŽ Collections, etc., work for all types
  • 11. Design Goals of C# Robust and Durable Software īˇ Garbage collection īŽ No memory leaks and stray pointers īˇ Exceptions īˇ Type-safety īŽ No uninitialized variables, no unsafe casts īˇ Versioning īˇ Avoid common errors īŽ E.g. if (x = y) ... īˇ One-stop programming īŽ Fewer moving parts
  • 12. Design Goals of C# Preserving Your Investment īˇ C++ Heritage īŽ Namespaces, pointers (in unsafe code), unsigned types, etc. īŽ Some changes, but no unnecessary sacrifices īˇ Interoperability īŽ What software is increasingly about īŽ C# talks to XML, SOAP, COM, DLLs, and any .NET Framework language īˇ Increased productivity īŽ Short learning curve īŽ Millions of lines of C# code in .NET
  • 13. Agenda īˇ Hello World īˇ Design Goals of C# īˇ Types īˇ Program Structure īˇ Statements īˇ Operators īˇ Using Visual Studio.NET īˇ Using the .NET Framework SDK
  • 14. Types Overview īˇ A C# program is a collection of types īŽ Classes, structs, enums, interfaces, delegates īˇ C# provides a set of predefined types īŽ E.g. int, byte, char, string, object, â€Ļ īˇ You can create your own types īˇ All data and code is defined within a type īŽ No global variables, no global functions
  • 15. Types Overview īˇ Types contain: īŽ Data members īŦ Fields, constants, arrays īŦ Events īŽ Function members īŦ Methods, operators, constructors, destructors īŦ Properties, indexers īŽ Other types īŦ Classes, structs, enums, interfaces, delegates
  • 16. Types Overview īˇ Types can be instantiatedâ€Ļ īŽ â€Ļand then used: call methods, get and set properties, etc. īˇ Can convert from one type to another īŽ Implicitly and explicitly īˇ Types are organized īŽ Namespaces, files, assemblies īˇ There are two categories of types: value and reference īˇ Types are arranged in a hierarchy
  • 17. Types Unified Type System īˇ Value types īŽ Directly contain data īŽ Cannot be null īˇ Reference types īŽ Contain references to objects īŽ May be null int i = 123; string s = "Hello world"; 123 i s "Hello world"
  • 18. Types Unified Type System īˇ Value types īŽ Primitives int i; float x; īŽ Enums enum State { Off, On } īŽ Structs struct Point {int x,y;} īˇ Reference types īŽ Root object īŽ String string īŽ Classes class Foo: Bar, IFoo {...} īŽ Interfaces interface IFoo: IBar {...} īŽ Arrays string[] a = new string[10]; īŽ Delegates delegate void Empty();
  • 19. Types Unified Type System Value (Struct) Reference (Class) Variable holds Actual value Memory location Allocated on Stack, member Heap Nullability Always has value May be null Default value 0 null Aliasing (in a scope) No Yes Assignment means Copy data Copy reference
  • 20. Types Unified Type System īˇ Benefits of value types īŽ No heap allocation, less GC pressure īŽ More efficient use of memory īŽ Less reference indirection īŽ Unified type system īŦ No primitive/object dichotomy
  • 21. Types Conversions īˇ Implicit conversions īŽ Occur automatically īŽ Guaranteed to succeed īŽ No information (precision) loss īˇ Explicit conversions īŽ Require a cast īŽ May not succeed īŽ Information (precision) might be lost īˇ Both implicit and explicit conversions can be user-defined
  • 22. Types Conversions int x = 123456; long y = x; // implicit short z = (short)x; // explicit double d = 1.2345678901234; float f = (float)d; // explicit long l = (long)d; // explicit
  • 23. Types Unified Type System īˇ Everything is an object īŽ All types ultimately inherit from object īŽ Any piece of data can be stored, transported, and manipulated with no extra work MemoryStream FileStream Stream Hashtable int double object
  • 24. Types Unified Type System īˇ Polymorphism īŽ The ability to perform an operation on an object without knowing the precise type of the object void Poly(object o) { Console.WriteLine(o.ToString()); } Poly(42); Poly(“abcd”); Poly(12.345678901234m); Poly(new Point(23,45));
  • 25. Types Unified Type System īˇ Question: How can we treat value and reference types polymorphically? īŽ How does an int (value type) get converted into an object (reference type)? īˇ Answer: Boxing! īŽ Only value types get boxed īŽ Reference types do not get boxed
  • 26. Types Unified Type System īˇ Boxing īŽ Copies a value type into a reference type (object) īŽ Each value type has corresponding “hidden” reference type īŽ Note that a reference-type copy is made of the value type īŦ Value types are never aliased īŽ Value type is converted implicitly to object, a reference type īŦ Essentially an “up cast”
  • 27. Types Unified Type System īˇ Unboxing īŽ Inverse operation of boxing īŽ Copies the value out of the box īŦ Copies from reference type to value type īŽ Requires an explicit conversion īŦ May not succeed (like all explicit conversions) īŦ Essentially a “down cast”
  • 28. Types Unified Type System īˇ Boxing and unboxing int i = 123; object o = i; int j = (int)o; 123 i o 123 j 123 System.Int32
  • 29. Types Unified Type System īˇ Benefits of boxing īŽ Enables polymorphism across all types īŽ Collection classes work with all types īŽ Eliminates need for wrapper classes īŽ Replaces OLE Automation's Variant īˇ Lots of examples in .NET Framework Hashtable t = new Hashtable(); t.Add(0, "zero"); t.Add(1, "one"); t.Add(2, "two"); string s = string.Format( "Your total was {0} on {1}", total, date);
  • 30. Types Unified Type System īˇ Disadvantages of boxing īŽ Performance cost īˇ The need for boxing will decrease when the CLR supports generics (similar to C++ templates)
  • 31. Types Predefined Types īˇ Value īŽ Integral types īŽ Floating point types īŽ decimal īŽ bool īŽ char īˇ Reference īŽ object īŽ string
  • 32. Predefined Types Value Types īˇ All are predefined structs Signed sbyte, short, int, long Unsigned byte, ushort, uint, ulong Character char Floating point float, double, decimal Logical bool
  • 33. Predefined Types Integral Types C# Type System Type Size (bytes) Signed? sbyte System.Sbyte 1 Yes short System.Int16 2 Yes int System.Int32 4 Yes long System.Int64 8 Yes byte System.Byte 1 No ushort System.UInt16 2 No uint System.UInt32 4 No ulong System.UInt64 8 No
  • 34. Predefined Types Floating Point Types īˇ Follows IEEE 754 specification īˇ Supports Âą 0, Âą Infinity, NaN C# Type System Type Size (bytes) float System.Single 4 double System.Double 8
  • 35. Predefined Types decimal īˇ 128 bits īˇ Essentially a 96 bit value scaled by a power of 10 īˇ Decimal values represented precisely īˇ Doesn’t support signed zeros, infinities or NaN C# Type System Type Size (bytes) decimal System.Decimal 16
  • 36. Predefined Types decimal īˇ All integer types can be implicitly converted to a decimal type īˇ Conversions between decimal and floating types require explicit conversion due to possible loss of precision īˇ s * m * 10e īŽ s = 1 or –1 īŽ 0 ī‚Ŗ m ī‚Ŗ 296 īŽ -28 ī‚Ŗ e ī‚Ŗ 0
  • 37. Predefined Types Integral Literals īˇ Integer literals can be expressed as decimal or hexadecimal īˇ U or u: uint or ulong īˇ L or l: long or ulong īˇ UL or ul: ulong 123 // Decimal 0x7B // Hexadecimal 123U // Unsigned 123ul // Unsigned long 123L // Long
  • 38. Predefined Types Real Literals īˇ F or f: float īˇ D or d: double īˇ M or m: decimal 123f // Float 123D // Double 123.456m // Decimal 1.23e2f // Float 12.3E1M // Decimal
  • 39. Predefined Types bool īˇ Represents logical values īˇ Literal values are true and false īˇ Cannot use 1 and 0 as boolean values īŽ No standard conversion between other types and bool C# Type System Type Size (bytes) bool System.Boolean 1 (2 for arrays)
  • 40. Predefined Types char īˇ Represents a Unicode character īˇ Literals īŽ ‘A’ // Simple character īŽ ‘u0041’ // Unicode īŽ ‘x0041’ // Unsigned short hexadecimal īŽ ‘n’ // Escape sequence character C# Type System Type Size (bytes) Char System.Char 2
  • 41. Predefined Types char īˇ Escape sequence characters (partial list) Char Meaning Value ’ Single quote 0x0027 ” Double quote 0x0022 Backslash 0x005C 0 Null 0x0000 n New line 0x000A r Carriage return 0x000D t Tab 0x0009
  • 42. Predefined Types Reference Types Root type object Character string string
  • 43. Predefined Types object īˇ Root of object hierarchy īˇ Storage (book keeping) overhead īŽ 0 bytes for value types īŽ 8 bytes for reference types īˇ An actual reference (not the object) uses 4 bytes C# Type System Type Size (bytes) object System.Object 0/8 overhead
  • 44. Predefined Types object Public Methods īˇ public bool Equals(object) īˇ protected void Finalize() īˇ public int GetHashCode() īˇ public System.Type GetType() īˇ protected object MemberwiseClone() īˇ public void Object() īˇ public string ToString()
  • 45. Predefined Types string īˇ An immutable sequence of Unicode characters īˇ Reference type īˇ Special syntax for literals īŽ string s = “I am a string”; C# Type System Type Size (bytes) String System.String 20 minimum
  • 46. Predefined Types string īˇ Normally have to use escape characters īˇ Verbatim string literals īŽ Most escape sequences ignored īŦ Except for “” īŽ Verbatim literals can be multi-line string s1= “serverfilesharefilename.cs”; string s2 = @“serverfilesharefilename.cs”;
  • 47. Types User-defined Types īˇ User-defined types Enumerations enum Arrays int[], string[] Interface interface Reference type class Value type struct Function pointer delegate
  • 48. Types Enums īˇ An enum defines a type name for a related group of symbolic constants īˇ Choices must be known at compile-time īˇ Strongly typed īŽ No implicit conversions to/from int īŽ Can be explicitly converted īŽ Operators: +, -, ++, --, &, |, ^, ~, â€Ļ īˇ Can specify underlying type īŽ byte, sbyte, short, ushort, int, uint, long, ulong
  • 49. Types Enums enum Color: byte { Red = 1, Green = 2, Blue = 4, Black = 0, White = Red | Green | Blue } Color c = Color.Black; Console.WriteLine(c); // 0 Console.WriteLine(c.Format()); // Black
  • 50. Types Enums īˇ All enums derive from System.Enum īŽ Provides methods to īŦ determine underlying type īŦ test if a value is supported īŦ initialize from string constant īŦ retrieve all values in enum īŦ â€Ļ
  • 51. Types Arrays īˇ Arrays allow a group of elements of a specific type to be stored in a contiguous block of memory īˇ Arrays are reference types īˇ Derived from System.Array īˇ Zero-based īˇ Can be multidimensional īŽ Arrays know their length(s) and rank īˇ Bounds checking
  • 52. Types Arrays īˇ Declare īˇ Allocate īˇ Initialize īˇ Access and assign īˇ Enumerate int[] primes; int[] primes = new int[9]; int[] prime = new int[] {1,2,3,5,7,11,13,17,19}; int[] prime = {1,2,3,5,7,11,13,17,19}; prime2[i] = prime[i]; foreach (int i in prime) Console.WriteLine(i);
  • 53. Types Arrays īˇ Multidimensional arrays īŽ Rectangular īŦ int[,] matR = new int[2,3]; īŦ Can initialize declaratively īŦ int[,] matR = new int[2,3] { {1,2,3}, {4,5,6} }; īŽ Jagged īŦ An array of arrays īŦ int[][] matJ = new int[2][]; īŦ Must initialize procedurally
  • 54. Types Interfaces īˇ An interface defines a contract īŽ Includes methods, properties, indexers, events īŽ Any class or struct implementing an interface must support all parts of the contract īˇ Interfaces provide polymorphism īŽ Many classes and structs may implement a particular interface īˇ Contain no implementation īŽ Must be implemented by a class or struct
  • 55. Types Classes īˇ User-defined reference type īŽ Similar to C++, Java classes īˇ Single class inheritance īˇ Multiple interface inheritance
  • 56. Types Classes īˇ Members īŽ Constants, fields, methods, operators, constructors, destructors īŽ Properties, indexers, events īŽ Static and instance members īˇ Member access īŽ public, protected, private, internal, protected internal īŦ Default is private īˇ Instantiated with new operator
  • 57. Types Structs īˇ Similar to classes, but īŽ User-defined value type īŽ Always inherits from object īˇ Ideal for lightweight objects īŽ int, float, double, etc., are all structs īŽ User-defined “primitive” types īŦ Complex, point, rectangle, color, rational īˇ Multiple interface inheritance īˇ Same members as class īˇ Member access īŽ public, internal, private īˇ Instantiated with new operator
  • 58. Types Classes and Structs struct SPoint { int x, y; ... } class CPoint { int x, y; ... } SPoint sp = new SPoint(10, 20); CPoint cp = new CPoint(10, 20); 10 20 sp cp 10 20 CPoint
  • 59. Types Delegates īˇ A delegate is a reference type that defines a method signature īˇ When instantiated, a delegate holds one or more methods īŽ Essentially an object-oriented function pointer īˇ Foundation for framework events
  • 60. Agenda īˇ Hello World īˇ Design Goals of C# īˇ Types īˇ Program Structure īˇ Statements īˇ Operators īˇ Using Visual Studio.NET īˇ Using the .NET Framework SDK
  • 61. Program Structure Overview īˇ Organizing Types īˇ Namespaces īˇ References īˇ Main Method īˇ Syntax
  • 62. Program Structure Organizing Types īˇ Physical organization īŽ Types are defined in files īŽ Files are compiled into modules īŽ Modules are grouped into assemblies Assembly Module File Type
  • 63. Program Structure Organizing Types īˇ Types are defined in files īŽ A file can contain multiple types īŽ Each type is defined in a single file īˇ Files are compiled into modules īŽ Module is a DLL or EXE īŽ A module can contain multiple files īˇ Modules are grouped into assemblies īŽ Assembly can contain multiple modules īŽ Assemblies and modules are often 1:1
  • 64. Program Structure Organizing Types īˇ Types are defined in ONE place īŽ “One-stop programming” īŽ No header and source files to synchronize īŽ Code is written “in-line” īŽ Declaration and definition are one and the same īŽ A type must be fully defined in one file īŦ Can’t put individual methods in different files īˇ No declaration order dependence īŽ No forward references required
  • 65. Program Structure Namespaces īˇ Namespaces provide a way to uniquely identify a type īˇ Provides logical organization of types īˇ Namespaces can span assemblies īˇ Can nest namespaces īˇ There is no relationship between namespaces and file structure (unlike Java) īˇ The fully qualified name of a type includes all namespaces
  • 66. Program Structure Namespaces namespace N1 { // N1 class C1 { // N1.C1 class C2 { // N1.C1.C2 } } namespace N2 { // N1.N2 class C2 { // N1.N2.C2 } } }
  • 67. Program Structure Namespaces īˇ The using statement lets you use types without typing the fully qualified name īˇ Can always use a fully qualified name using N1; C1 a; // The N1. is implicit N1.C1 b; // Fully qualified name C2 c; // Error! C2 is undefined N1.N2.C2 d; // One of the C2 classes C1.C2 e; // The other one
  • 68. Program Structure Namespaces īˇ The using statement also lets you create aliases using C1 = N1.N2.C1; using N2 = N1.N2; C1 a; // Refers to N1.N2.C1 N2.C1 b; // Refers to N1.N2.C1
  • 69. Program Structure Namespaces īˇ Best practice: Put all of your types in a unique namespace īˇ Have a namespace for your company, project, product, etc. īˇ Look at how the .NET Framework classes are organized
  • 70. Program Structure References īˇ In Visual Studio you specify references for a project īˇ Each reference identifies a specific assembly īˇ Passed as reference (/r or /reference) to the C# compiler csc HelloWorld.cs /reference:System.WinForms.dll
  • 71. Program Structure Namespaces vs. References īˇ Namespaces provide language-level naming shortcuts īŽ Don’t have to type a long fully qualified name over and over īˇ References specify which assembly to use
  • 72. Program Structure Main Method īˇ Execution begins at the static Main() method īˇ Can have only one method with one of the following signatures in an assembly īŽ static void Main() īŽ static int Main() īŽ static void Main(string[] args) īŽ static int Main(string[] args)
  • 73. Program Structure Syntax īˇ Identifiers īŽ Names for types, methods, fields, etc. īŽ Must be whole word – no white space īŽ Unicode characters īŽ Begins with letter or underscore īŽ Case sensitive īŽ Must not clash with keyword īŦ Unless prefixed with @
  • 74. Agenda īˇ Hello World īˇ Design Goals of C# īˇ Types īˇ Program Structure īˇ Statements īˇ Operators īˇ Using Visual Studio.NET īˇ Using the .NET Framework SDK
  • 75. Statements Overview īˇ High C++ fidelity īˇ if, while, do require bool condition īˇ goto can’t jump into blocks īˇ switch statement īŽ No fall-through īˇ foreach statement īˇ checked and unchecked statements īˇ Expression statements must do work void Foo() { i == 1; // error }
  • 76. Statements Overview īˇ Statement lists īˇ Block statements īˇ Labeled statements īˇ Declarations īŽ Constants īŽ Variables īˇ Expression statements īŽ checked, unchecked īŽ lock īŽ using īˇ Conditionals īŽ if īŽ switch īˇ Loop Statements īŽ while īŽ do īŽ for īŽ foreach īˇ Jump Statements īŽ break īŽ continue īŽ goto īŽ return īŽ throw īˇ Exception handling īŽ try īŽ throw
  • 77. Statements Syntax īˇ Statements are terminated with a semicolon (;) īˇ Just like C, C++ and Java īˇ Block statements { ... } don’t need a semicolon
  • 78. Statements Syntax īˇ Comments īŽ // Comment a single line, C++ style īŽ /* Comment multiple lines, C style */
  • 79. Statements Statement Lists & Block Statements īˇ Statement list: one or more statements in sequence īˇ Block statement: a statement list delimited by braces { ... } static void Main() { F(); G(); { // Start block H(); ; // Empty statement I(); } // End block }
  • 80. Statements Variables and Constants static void Main() { const float pi = 3.14f; const int r = 123; Console.WriteLine(pi * r * r); int a; int b = 2, c = 3; a = 1; Console.WriteLine(a + b + c); }
  • 81. Statements Variables and Constants īˇ The scope of a variable or constant runs from the point of declaration to the end of the enclosing block
  • 82. Statements Variables and Constants īˇ Within the scope of a variable or constant it is an error to declare another variable or constant with the same name { int x; { int x; // Error: can’t hide variable x } }
  • 83. Statements Variables īˇ Variables must be assigned a value before they can be used īŽ Explicitly or automatically īŽ Called definite assignment īˇ Automatic assignment occurs for static fields, class instance fields and array elements void Foo() { string s; Console.WriteLine(s); // Error }
  • 84. Statements Labeled Statements & goto īˇ goto can be used to transfer control within or out of a block, but not into a nested block static void Find(int value, int[,] values, out int row, out int col) { int i, j; for (i = 0; i < values.GetLength(0); i++) for (j = 0; j < values.GetLength(1); j++) if (values[i, j] == value) goto found; throw new InvalidOperationException(“Not found"); found: row = i; col = j; }
  • 85. Statements Expression Statements īˇ Statements must do work īŽ Assignment, method call, ++, --, new static void Main() { int a, b = 2, c = 3; a = b + c; a++; MyClass.Foo(a,b,c); Console.WriteLine(a + b + c); a == 2; // ERROR! }
  • 86. Statements if Statement īˇ Requires bool expression int Test(int a, int b) { if (a > b) return 1; else if (a < b) return -1; else return 0; }
  • 87. Statements switch Statement īˇ Can branch on any predefined type (including string) or enum īŽ User-defined types can provide implicit conversion to these types īˇ Must explicitly state how to end case īŽ With break, goto case, goto label, return, throw or continue īŽ Eliminates fall-through bugs īŽ Not needed if no code supplied after the label
  • 88. Statements switch Statement int Test(string label) { int result; switch(label) { case null: goto case “runner-up”; case “fastest”: case “winner”: result = 1; break; case “runner-up”: result = 2; break; default: result = 0; } return result; }
  • 89. Statements while Statement īˇ Requires bool expression int i = 0; while (i < 5) { ... i++; } int i = 0; do { ... i++; } while (i < 5); while (true) { ... }
  • 90. Statements for Statement for (int i=0; i < 5; i++) { ... } for (;;) { ... }
  • 91. Statements foreach Statement īˇ Iteration of arrays public static void Main(string[] args) { foreach (string s in args) Console.WriteLine(s); }
  • 92. Statements foreach Statement īˇ Iteration of user-defined collections īˇ Created by implementing IEnumerable foreach (Customer c in customers.OrderBy("name")) { if (c.Orders.Count != 0) { ... } }
  • 93. Statements Jump Statements īˇ break īŽ Exit inner-most loop īˇ continue īŽ End iteration of inner-most loop īˇ goto <label> īŽ Transfer execution to label statement īˇ return [<expression>] īŽ Exit a method īˇ throw īŽ See exception handling
  • 94. Statements Exception Handling īˇ Exceptions are the C# mechanism for handling unexpected error conditions īˇ Superior to returning status values īŽ Can’t be ignored īŽ Don’t have to handled at the point they occur īŽ Can be used even where values are not returned (e.g. accessing a property) īŽ Standard exceptions are provided
  • 95. Statements Exception Handling īˇ try...catch...finally statement īˇ try block contains code that could throw an exception īˇ catch block handles exceptions īŽ Can have multiple catch blocks to handle different kinds of exceptions īˇ finally block contains code that will always be executed īŽ Cannot use jump statements (e.g. goto) to exit a finally block
  • 96. Statements Exception Handling īˇ throw statement raises an exception īˇ An exception is represented as an instance of System.Exception or derived class īŽ Contains information about the exception īŽ Properties īŦ Message īŦ StackTrace īŦ InnerException īˇ You can rethrow an exception, or catch one exception and throw another
  • 97. Statements Exception Handling try { Console.WriteLine("try"); throw new Exception(“message”); } catch (ArgumentNullException e) { Console.WriteLine(“caught null argument"); } catch { Console.WriteLine("catch"); } finally { Console.WriteLine("finally"); }
  • 98. Statements Synchronization īˇ Multi-threaded applications have to protect against concurrent access to data īŽ Must prevent data corruption īˇ The lock statement uses an instance to provide mutual exclusion īŽ Only one lock statement can have access to the same instance īŽ Actually uses the .NET Framework System.Threading.Monitor class to provide mutual exclusion
  • 99. Statements Synchronization public class CheckingAccount { decimal balance; public void Deposit(decimal amount) { lock (this) { balance += amount; } } public void Withdraw(decimal amount) { lock (this) { balance -= amount; } } }
  • 100. Statements using Statement īˇ C# uses automatic memory management (garbage collection) īŽ Eliminates most memory management problems īˇ However, it results in non-deterministic finalization īŽ No guarantee as to when and if object destructors are called
  • 101. Statements using Statement īˇ Objects that need to be cleaned up after use should implement the System.IDisposable interface īŽ One method: Dispose() īˇ The using statement allows you to create an instance, use it, and then ensure that Dispose is called when done īŽ Dispose is guaranteed to be called, as if it were in a finally block
  • 102. Statements using Statement public class MyResource : IDisposable { public void MyResource() { // Acquire valuble resource } public void Dispose() { // Release valuble resource } public void DoSomething() { ... } } using (MyResource r = new MyResource()) { r.DoSomething(); } // r.Dispose() is called
  • 103. Statements checked and unchecked Statements īˇ The checked and unchecked statements allow you to control overflow checking for integral-type arithmetic operations and conversions īˇ checked forces checking īˇ unchecked forces no checking īˇ Can use both as block statements or as an expression īˇ Default is unchecked īˇ Use the /checked compiler option to make checked the default
  • 104. Statements Basic Input/Output Statements īˇ Console applications īŽ System.Console.WriteLine(); īŽ System.Console.ReadLine(); īˇ Windows applications īŽ System.WinForms.MessageBox.Show(); string v1 = “some value”; MyObject v2 = new MyObject(); Console.WriteLine(“First is {0}, second is {1}”, v1, v2);
  • 105. Agenda īˇ Hello World īˇ Design Goals of C# īˇ Types īˇ Program Structure īˇ Statements īˇ Operators īˇ Using Visual Studio.NET īˇ Using the .NET Framework SDK
  • 106. Operators Overview īˇ C# provides a fixed set of operators, whose meaning is defined for the predefined types īˇ Some operators can be overloaded (e.g. +) īˇ The following table summarizes the C# operators by category īŽ Categories are in order of decreasing precedence īŽ Operators in each category have the same precedence
  • 107. Operators Precedence Category Operators Primary Grouping: (x) Member access: x.y Method call: f(x) Indexing: a[x] Post-increment: x++ Post-decrement: x— Constructor call: new Type retrieval: typeof Arithmetic check on: checked Arithmetic check off: unchecked
  • 108. Operators Precedence Category Operators Unary Positive value of: + Negative value of: - Not: ! Bitwise complement: ~ Pre-increment: ++x Post-decrement: --x Type cast: (T)x Multiplicative Multiply: * Divide: / Division remainder: %
  • 109. Operators Precedence Category Operators Additive Add: + Subtract: - Shift Shift bits left: << Shift bits right: >> Relational Less than: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Type equality/compatibility: is Type conversion: as
  • 110. Operators Precedence Category Operators Equality Equals: == Not equals: != Bitwise AND & Bitwise XOR ^ Bitwise OR | Logical AND && Logical OR ||
  • 111. Operators Precedence Category Operators Ternary conditional ?: Assignment =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
  • 112. Operators Associativity īˇ Assignment and ternary conditional operators are right-associative īŽ Operations performed right to left īŽ x = y = z evaluates as x = (y = z) īˇ All other binary operators are left-associative īŽ Operations performed left to right īŽ x + y + z evaluates as (x + y) + z īˇ Use parentheses to control order
  • 113. Agenda īˇ Hello World īˇ Design Goals of C# īˇ Types īˇ Program Structure īˇ Statements īˇ Operators īˇ Using Visual Studio.NET īˇ Using the .NET Framework SDK
  • 114. Using Visual Studio.NET īˇ Types of projects īŽ Console Application īŽ Windows Application īŽ Web Application īŽ Web Service īŽ Windows Service īŽ Class Library īŽ ...
  • 115. Using Visual Studio.NET īˇ Windows īŽ Solution Explorer īŽ Class View īŽ Properties īŽ Output īŽ Task List īŽ Object Browser īŽ Server Explorer īŽ Toolbox
  • 116. Using Visual Studio.NET īˇ Building īˇ Debugging īŽ Break points īˇ References īˇ Saving
  • 117. Agenda īˇ Hello World īˇ Design Goals of C# īˇ Types īˇ Program Structure īˇ Statements īˇ Operators īˇ Using Visual Studio.NET īˇ Using the .NET Framework SDK
  • 118. Using .NET Framework SDK īˇ Compiling from command line csc /r:System.WinForms.dll class1.cs file1.cs
  • 119. More Resources īˇ http://msdn.microsoft.com īˇ http://windows.oreilly.com/news/hejlsberg_0800.html īˇ http://www.csharphelp.com/ īˇ http://www.csharp-station.com/ īˇ http://www.csharpindex.com/ īˇ http://msdn.microsoft.com/msdnmag/issues/0900/csharp/cs harp.asp īˇ http://www.hitmill.com/programming/dotNET/csharp.html īˇ http://www.c-sharpcorner.com/ īˇ http://msdn.microsoft.com/library/default.asp?URL=/libr ary/dotnet/csspec/vclrfcsharpspec_Start.htm