0% found this document useful (0 votes)
14 views

Chapter One Window Programming Handout-1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Chapter One Window Programming Handout-1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Yeju College

Computer Science Department

3/22/2024 1
 Introduction  Windows Programming Fundamentals in C#
 C# and Windows Programming  Types
 Object-Oriented Programming  Value and Reference
 Event-Driven Programming  Types Conversions
 Visual Programming  Types hierarchy
 Asynchronous Programming with  Predefined Types
 User-defined Types
async and await
 Program Structure
 Microsoft’s .NET  control statements
 Common Language Runtime
 Platform Independence
 Language Interoperability
 Visual Studio Integrated
Development Environment

3/22/2024 2
 C#, pronounced “C Sharp,” is one of the new languages in the .NET framework being
implemented by Microsoft.
 All .NET languages compile to a common byte code Microsoft Intermediate Language
(MSIL) making their integration into programs written in different languages easier.
 C# combines the power of C and C++ with the productivity of Visual Basic
 With its familiar syntax the transition for Java and C++ programmers will be an easy
one

3/22/2024 3
 In 2000, Microsoft announced the C# programming language.
 The C# language provides almost everything you need to create a computer and
mobile application.
 A Windows application primarily appears as a rectangular object that
occupies a portion of the screen.
 This type of object is under the management of the operating system:
Microsoft Windows.
 The C# language defines this entry point with a function called Main.

3/22/2024 4
 C# is object oriented
 Every class is a subclass of an object.
 Everything is an object.
 This makes generic programming easier.
Example:
int n = 3;
string s = n.ToString();

3/22/2024 5
 C# graphical user interfaces (GUIs) are event driven.
 You can write programs that respond to user-initiated events such as
 mouse clicks,
 keystrokes,
 timer expirations
 touches
 finger swipes that are widely used on smartphones and
 Gestures tablets.

3/22/2024 6
 Microsoft’s Visual Studio enables you to use C# as a visual programming
language.
 You’ll use Visual Studio to conveniently drag and drop predefined GUI objects like
buttons and textboxes into place on your screen, and label and resize them.
 Visual Studio will write much of the GUI code for you.

3/22/2024 7
 Today’s apps can be written with the aim of communicating among the
world’s computers.
 C# is in sync with current web standards and is easily integrated
with existing applications.
 This is the focus of Microsoft’s .NET strategy.

3/22/2024 8
 In most programming today, each task in a program must finish
executing before the next task can begin.
 This is called synchronous programming
 C# also allows asynchronous programming in which multiple tasks
can be performed at the same time.
 Asynchronous programming can help you make your apps more
responsive to user interactions, such as mouse clicks and keystrokes,
among many other uses.

3/22/2024 9
 Asynchronous programming in early versions of Visual C# was difficult
and error prone.
 C#’s async and await capabilities simplify asynchronous programming
by enabling the compiler to hide much of the associated complexity
from the developer.

3/22/2024 10
 In 2000, Microsoft announced its .NET initiative (www.microsoft.com/net), a broad
vision for using the Internet and the web in the development, engineering,
distribution and use of software.
 Rather than forcing you to use a single programming language, .NET permits you to
create apps in any .NET-compatible language (such as C#, Visual Basic, Visual
C++ and others).

3/22/2024 11
 The .NET Framework Class Library provides many capabilities that you’ll use to
build substantial C# apps quickly and easily.
 It contains thousands of valuable prebuilt classes that have been tested and tuned to
maximize performance.
 You should re-use the .NET Framework classes whenever possible
 to speed up the software-development process
 enhancing the quality and performance of the software you develop.

3/22/2024 12
Fig 1.1 : Some key capabilities in the .NET Framework Class library

3/22/2024 13
 The Common Language Runtime (CLR) executes .NET programs and provides
functionality to make them easier to develop and debug.
 The CLR is a virtual machine (VM):-software that manages the execution of
programs and hides from them the underlying operating system and hardware.
 The source code for programs that are executed and managed by the CLR is called
managed code.

3/22/2024 14
 The CLR provides various services to managed code
 integrating software components written in different .NET languages,
 error handling between such components,
 enhanced security,
 automatic memory management and more.
 Unmanaged-code programs do not have access to the CLR’s services.
 unmanaged code more difficult to write.

3/22/2024 15
 Managed code is compiled into machine-specific instructions in the
following steps:
 First, the code is compiled into Microsoft Intermediate Language (MSIL).
Code converted into MSIL from other languages and sources can be woven together
by the CLR—this allows programmers to work in their preferred .NET
programming language.
The MSIL for an app’s components is placed into the app’s executable file:-the file
that causes the computer to perform the app’s tasks.
 When the app executes, another compiler (known as the just-in-time
compiler or JIT compiler) in the CLR translates the MSIL in the executable
file into machine-language code (for a particular platform).
 The machine-language code executes on that platform.

3/22/2024 16
 If the .NET Framework exists and it is installed for a platform, that platform
can run any .NET program.
 The ability of a program to run without modification across multiple platforms
is known as platform independence.
 Code written once can be used on another type of computer without
modification, saving time and money.

3/22/2024 17
 The .NET Framework provides a high level of language interoperability.
 Because software components written in different .NET languages (such as C# and
Visual Basic) are all compiled into MSIL, the components can be combined to create
a single unified program.
 Thus, MSIL allows the .NET Framework to be language independent.
 The .NET Framework Class Library can be used by any .NET language.

3/22/2024 18
 C# programs can be created using Microsoft’s Visual Studio
 a collection of software tools called an Integrated Development Environment
(IDE).
 The Visual Studio Community edition IDE enables you to write, run,
test and debug C# programs quickly and conveniently.
 It also supports Microsoft’s Visual Basic, Visual C++ and F#
programming languages and more.

3/22/2024 19
 C# simple example

Output

 The Hello World application is very simple in C#.


Some key points:
 In C# there are no global methods.
 Everything belongs to a class.
3/22/2024 20
 A method named Main is the entry point for a C# application.
 Note that Main is spelled with a capital “M”, which is different than C and C++.
 The reason is that for consistency
 all method names start with a capital letter in the .NET Framework
 The line using System;
 means that we’ll be accessing members of the System namespace.
 in the Hello World example,
 the class Console, which contains the method WriteLine belongs to the System namespace.
 We could avoid the “using” statement by writing the complete path of the method:
System.Console.WriteLine(“Hello World”);

3/22/2024 21
 A C# program is a collection of types  Types can be instantiated…
 Classes, structs, enums, interfaces, etc.  …and then used: call methods, get
and set properties, etc.
 C# provides a set of predefined types
 Can convert from one type to another
 E.g. int, char, string, object, …
 Implicitly and explicitly
 You can create your own types
 Types are organized
 Types contain:
 Namespaces, files, assemblies
 Data members
 There are two categories of types:
 Fields, constants, arrays, etc.
 Value and Reference
 Function members
 Methods, operators, constructors, destructors  Types are arranged in a hierarchy
 Properties, indexers
 Other types
 Classes, structs, enums, interfaces

3/22/2024 22
 Value types:that directly hold the data on the stack
 Directly contain data
 Cannot be null
 Default value 0
 Assignment method Copy data
 Reference types:that keeps a reference on the stack, but allocates the real memory
on the heap.
 Contain references to objects

 May be null

 Assignment method Copy reference

int i = 123; i 123


string s = "Hello world";

s "Hello world"
3/22/2024 23
 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];

3/22/2024 24
 Implicit conversions  Explicit conversions
 Occur automatically  Require a cast

 Guaranteed to succeed  May not succeed

 No information (precision) loss  Information (precision) might be lost

 Both implicit and explicit conversions can be user-defined


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

3/22/2024 25
 Everything is an object:including primitive types, structs or classes.
 All types ultimately inherit from object
 Any piece of data can be stored, transported, and manipulated with no extra work

object

Stream Hashtable int double

MemoryStream FileStream

3/22/2024 26
Value Reference
 Integral type  Decimal  object
 Floating point types  bool  string
 char
 All are predefined structs
Signed sbyte, short, int, long
Unsigned byte, ushort, uint, ulong
Character char
Floating point float, double, decimal

Logical bool

3/22/2024 27
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

3/22/2024 28
3/22/2024 29
 Floating Point Types
 Supports ± 0, ± Infinity, NaN (Not a Number):-is numeric data type that means an undefined value
or value that cannot be presented example 0/0 , the square root of any negative number.

 Decimal type  All integer types can be implicitly


 128 bits
converted to a decimal type
 Decimal values represented precisely
 Doesn’t support signed zeros, infinities or NaN  Conversions between decimal and
floating types require explicit
Size conversion due to possible loss of
C# Type System Type
(bytes) precision
decimal System.Decimal 16
3/22/2024 30
 Integral Literals Real Literals  bool
 Integer literals can be  F or f: float  Represents logical values
expressed as decimal or  Literal values are true and
 D or d: double
hexadecimal false
 U or u: uint or ulong  M or m: decimal  Cannot use 1 and 0 as
 L or l: long or ulong boolean values
 No standard conversion
 UL or ul: ulong
between other types
and bool
123 // Decimal 123f // Float Size
0x7B // Hexadecimal 123D // Double C# Type System Type
123U // Unsigned 123.456m // Decimal (bytes)
123ul // Unsigned long 1 (2 for
123L // Long bool System.Boolean
arrays)

3/22/2024 31
 char
 Represents a Unicode character
 Escape sequence characters
 Literals
(partial list)
C# Type System Type Size (bytes)
Char Meaning
Char System.Char 2
\’ Single quote
\” Double quote
\\ Backslash
\0 Null
\n New line
\r Carriage return
\t Tab

3/22/2024 32
 Reference Types  String
 An immutable sequence of Unicode
characters
Root type object
 Reference type
string
Character string
 Special syntax for literals
 string s = “I am a string”;

C# Type System Type Size (bytes)


String System.String 20 minimum

3/22/2024 33
 User-defined types  Arrays
 Arrays allow a group of elements of a specific type
Arrays int[], string[] to be stored in a contiguous block of memory
 Arrays are reference types
Interface interface
 Derived from System.Array
Reference type class  Zero-based
Value type struct  Can be multidimensional
 Arrays know their length(s) and rank

 Bounds checking

3/22/2024 34
 Declare  Multidimensional arrays
int[] primes;
 Rectangular
 Allocate int[,] matR = new int[2,3];
int[] primes = new int[9];
 Can initialize declaratively
 Initialize int[,] matR = new int[2,3] { {1,2,3}, {4,5,6} };
int[] prime = new int[]{1,2,3,5};
int[] prime = {1,2,3,5};
 Access and assign
prime2[i] = prime[i];
 Enumerate
foreach (int i in prime)
Console.WriteLine(i);

3/22/2024 35
 Organizing Types  Types are defined in files
 Physical organization  A file can contain multiple types
 Types are defined in files  Each type is defined in a single file
 Files are compiled into modules  Files are compiled into modules
 Modules are grouped into assembly  Module is a DLL or EXE
 A module can contain multiple files
Assembly  Modules are grouped into
Module
assemblies
File
Type  Assembly can contain multiple
modules

3/22/2024 36
 Namespaces
 Namespace is a method of organizing similar files together.

 This is similar in some way to the java package idea. Every program is either
explicitly within a namespace or in by default.
Example: namespace N1 { // N1
class C1 { // N1.C1
 namespace Project{ public class P1{} } class C2 { // N1.C1.C2
}
 public class P2{} }
namespace N2 { // N1.N2
To use a namespace, you just simply class C2 { // N1.N2.C2
}
import by using the keyword using. Example: }
using system; }

public class P1{}


 Can nest namespaces
 The fully qualified name of a type includes all namespaces
3/22/2024 37
 References  Namespaces vs. References
 In Visual Studio you specify references  Namespaces provide
for a project language-level naming
 Each reference identifies a specific assembly shortcuts
 Passed as reference (/r or /reference)  Don’t have to type a long fully
to the C# compiler qualified name over and over
 References specify which
assembly to use

3/22/2024 38
 Main Method  Syntax
 Execution begins at the static Main()  Identifiers
method
 Names for types, methods, fields, etc.
 Can have only one method with one of
 Must be whole word – no white space
the following signatures in an assembly
 Unicode characters
 static void Main()
 Begins with letter or underscore
 static int Main()
 Case sensitive
 static void Main(string[] args)
 Must not clash with keyword
 static int Main(string[] args)
 Unless prefixed with @

3/22/2024 39
 Statements Overview
 In the Statements and Expressions area C# is just like C++ with some key
differences to improve code robustness.
 Other than solving the old assignment problem in if statements,
 goto usage is limited to safer scenarios and
 switch statements require break between each options avoiding the infamous fall
through bug.
 C# has a foreach statement to iterate through arrays and collections
 Expression statements must do work

3/22/2024 40
 Statement lists  Loop Statements
 Block statements  while

 Labeled statements  do

 Declarations  for

 Constants  foreach

 Variables  Jump Statements


 Conditionals  break

 if  continue

 switch  goto

 return

3/22/2024 41
Statements
Lists & Block Statements
 Statements are terminated with a semicolon (;)  Statement list: one or more
 Just like C, C++ and Java statements in sequence
 Block statements { ... } don’t need a semicolon  Block statement: a statement list
 Comments delimited by braces { ... }
 // Comment a single line, C++ style static void Main() {
 /* Comment multiple F();
G();
lines, { // Start block
C style H();
; // Empty statement
*/ I();
} // End block
}

3/22/2024 42
 The scope of a variable or constant runs  Variables must be assigned a value
from the point of declaration to the end before they can be used
of the enclosing block ◦ Explicitly or automatically
◦ Called definite assignment
 Automatic assignment occurs for
static void Main() { static fields, class instance fields and
const float pi = 3.14f;
const int r = 123;
array elements
Console.WriteLine(pi * r * r);
void Foo() {
int a; string s;
int b = 2, c = 3; Console.WriteLine(s); // Error
a = 1; }
Console.WriteLine(a + b + c);
}

3/22/2024 43
 Normally, statements execute one  Sequence Structure
after the other in sequential  The sequence structure is built into
execution. C#.
 Various C# statements enable you  the computer executes C# statements one
to specify the next statement to after the other in the order in which
they’re written in sequence.
execute. This is called transfer of
 Single-entry/single-exit control
control.
statements make it easy to build apps.
 Control statements are “attached” to
one another by connecting the exit
point of one to the entry point of the
next.

3/22/2024 44
Selection Statements
 C# has three types of selection structures
 The if statement performs (selects) an action if a condition is true or skips
the action if the condition is false.
 The if…else statement performs an action if a condition is true
or performs a different action if the condition is false.
 The switch statement performs one of many different actions,
depending on the value of an expression.

3/22/2024 45
If example
 If---else example

3/22/2024 46
 If----else if---else statement  switch statement example

3/22/2024 47
 C# provides four iteration statements (sometimes called repetition
statements or looping statements) that enable programs to perform
statements repeatedly as long as a condition (called the loop-continuation
condition) remains true.
 while,
 do…while,
Iteration(loop) control statements
 for
 foreach.
 The while, for and foreach statements perform the action (or group of
actions) in their bodies zero or more times.
 The do…while statement performs the action (or group of actions) in its
body one or more times.

3/22/2024 48
while Iteration Statement  do…while iteration statement
 A iteration statement allows you  The do…while iteration statement is
to specify that an app should similar to the while statement. However,
repeat an action: ◦ First the iteration is executed and then
the truth expression is evaluated.
 First the truth expression is
evaluated and then the iteration is ◦ When the test evaluates to false, the
executed loop exits.

3/22/2024 49
 while loop control statement example  Do----while loop control statement example

3/22/2024 50
 For loop control statement  Foreach loop control statement
 The foreach construct simplifies traversing over
collections of data.
 It has no explicit counter.
 The foreach statement
 goes through the array or collection one by one
 the current value is copied to a variable defined in
the construct.

3/22/2024 51
 Sometimes you want finer-grained control
over the processing of looping code.
 C# provides four commands to help you
here, three of which were shown in other
situations:
 Break—Causes the loop to end immediately.
 Continue—Causes the current loop cycle to end
immediately (execution continues with the next
loop cycle)
 Goto—allows jumping out of a loop to a labeled
position (not recommended if you want your
code to be easy to read and understand)
 Return—Jumps out of the loop and its
containing function

3/22/2024 52
3/22/2024 53
 The conditional operator (?:) can be used in
place of an if…else statement.
 Console.WriteLine(
studentGrade >= 60 ? "Passed" : "Failed");
 The first operand is a boolean expression
that evaluates to true or false.
 The second operand is the value if the
expression is true
 The third operand is the value if the
expression is false.
 Example: write c# program that accept two
number and display minimum number from
accepted number ?(by using conditional
operator)
3/22/2024 54
 write C# program that accept three
integer numbers from the user and
display maximum number?
◦ By using if -----else Thank You !!!
◦ Conditional
 Write the definition of the types of
operators in C# program with program
examples.
◦ Arithmetic operator
◦ Assignment operator
◦ Logical operator
◦ Relational operator
◦ Increment and decrement operator
◦ precedence of operator

3/22/2024 55

You might also like