1 - Core C# Programming Constructs - Part I

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 66

Core C# Programming

Constructs
PART 1
Outline
• In this lesson, we will begin our formal investigation of the C#
programming language
• In particular we will discuss about
• Main() method
• fundamental C# data types
• var keyword
• C# keywords and operators for flow control
The Anatomy of a Simple C# Program
• C# demands that all program logic be contained within a type
definition
• Unlike other languages such as C++/C, in C# it is not possible to
create global functions or global points of data.
The Anatomy of …. Cont’d

• Note C# is a case-sensitive programming language


• Main is not the same as main, and Readline is not the same as
ReadLine.
• Be aware that all C# keywords are lowercase (e.g., public, lock,
class, dynamic).
• Namespaces, types, and member names begin (by convention)
with an initial capital letter and have capitalized the first letter of
any embedded words
The Main Method
• Main method is a special method with in application that serves as
the entry point
• Formally speaking, the class that defines the Main() method is
termed the application object
• By default Visual Studio create a Main Method with void return
type and array of string as a parameter
• However, variations on the Main() Method do exist
Variations of Main Method - 1
// int return type, array of strings as the parameter.
static int Main(string[] args)
{
// Must return a value before exiting!
return 0;
}
Variations of Main Method - 2
// No return type, no parameters.
static void Main()
{

}
Variations of Main Method - 3
// int return type, no parameters.
static int Main()
{
// Must return a value before exiting!
return 0;
}
Choosing a Main Method variation
• Your choice of how to construct Main() will be based on two
questions
• Do you want to return a value to the system when Main() has
completed and your program terminates?
• Do you need to process any user-supplied, command-line
parameters?
Specifying an Application Error Code
• Vast majority of your Main() methods will return void as the
return value
• The ability to return an int from Main() keeps C# consistent
with other C-based languages.
• By convention, returning the value 0 indicates the program has
terminated successfully
• While any other value (such as -1) represents an error condition
Specifying an Application Error Code
• The value 0 is automatically returned, even if you construct a
Main() method prototyped to return void
• An application’s return value is stored within a system
environment variable named %ERRORLEVEL%.
• If you were to create an application that programmatically
launches another executable, you can obtain the exit value using
the static System.Diagnostics.Process.ExitCode
property.
Processing Command-Line Arguments
• To access the command line arguments you can iterate
through the string array parameters of the Main() method
• You can also use the GetCommandLineArgs() method of
the System.Environment type
• The return value of this method is an array of strings
• When using this approach, it is no longer necessary to define
Main() as taking a string array as the input parameter
Processing Command-Line Arguments
• During the development cycle, you might wish to specify
possible command-line flags for testing purposes with in Visual
Studio
• To do so
• Double click on the properties icon in the solution view
• Select the Debug tab on the left side of the newly opened panel
• From there, specify values using the command-line arguments text
box
The System.Console Class
• A console user interface (CUI) is not as enticing as a graphical user
interface (GUI) or web-application
• But we will restrict the early examples of the course to console
programs
• This allows us to keep focused on the syntax of C# and the core
aspects of the .NET platform
• Thus, we don’t need to deal with the complexities of building
desktop GUIs or web sites at first
The System.Console Class Cont’d
• As its name implies, the Console class encapsulates IO and
error-stream manipulations for console-based applications.
• Some members of interest are presented on the next slide
• The Console class does provide ability to
• Change background and foreground colors
• Issue beep noises
The System.Console Class Cont’d
Member Meaning
Beep() This method forces the console to emit a beep of a
specified frequency and duration.
BackgroundColor These properties set the background/foreground
ForegroundColor colors for the current output. They may be assigned
any member of the ConsoleColor enumeration
BufferHeight These properties control the height/width of the
BufferWidth console’s buffer area.
Title This property sets the title of the current console
The System.Console Class Cont’d
Member Meaning
WindowHeight These properties control the dimensions of the
WindowWidth console in relation to the established buffer.
WindowTop
WindowLeft

Clear() This method clears the established buffer and


console display area.
Basic I/O with the Console Class
• In addition to the above members, the Console type
defines a set of methods to capture I/O
• All of these methods are static
• Therefore, they called by prefixing the name of the class
(Console) to the method name
• As you have seen, WriteLine() pumps a text string
(including a carriage return) to the output stream
Basic I/O with the Console Class
• The Write() method pumps text to the output stream
without a carriage return
• ReadLine() allows you to receive information from the
input stream up until the Enter key is pressed
• Read() is used to capture a single character from the
input stream
Formatting Console Output
• The .NET platform supports a style of string formatting slightly akin to the
printf() statement of C.
• When you are defining a string literal that contains segments of data whose
value is not known until runtime, you are able to specify a placeholder
within the literal using this curly-bracket syntax.
• The first parameter to WriteLine() represents a string literal that contains
optional placeholders designated by {0}, {1}, {2}, and so forth.
• The remaining parameters to WriteLine() are simply the values to be
inserted into the respective placeholders.
System Data Types & Corresponding C#
Keywords
• Like any programming language, C# defines keywords for
fundamental data types
• They are used to represent local variables, class data
member variables, method return values, and parameters.
• Unlike other programming languages, however, these
keywords are much more than simple compiler recognized
tokens.
System Data Types… Cont’d
• Rather, the C# data type keywords are actually shorthand
notations for full-blown types in the System namespace.
• The Table in the next slide lists each system data type, its
range, the corresponding C# keyword, and the type’s
compliance with the CLS.
System Data Types… Cont’d
C# Shorthand System Type Range Meaning
bool System.Boolean true or false Represents truth or falsity
sbyte System.SByte –128 to 127 Signed 8-bit number
byte System.Byte 0 to 255 Unsigned 8-bit number
short System.Int16 –32,768 to 32,767 Signed 16-bit number
ushort System.UInt16 0 to 65,535 Unsigned 16-bit number
System Data Types… Cont’d
C# System Type Range Meaning
Shorthand
int System.Int32 –2,147,483,648 to Signed 32-bit
2,147,483,647 number
uint System.UInt32 0 to 4,294,967,295 Unsigned 32-bit
number
long System.Int64 –9,223,372,036,854,775,808 Signed 64-bit
to number
9,223,372,036,854,775,807
ulong System.UInt64 0 to Unsigned 64-bit
18,446,744,073,709,551,615 number
System Data Types… Cont’d
C# System Type Range Meaning
Shorthand
char System.Char U+0000 to U+ffff Single 16-bit
Unicode
character
float System.Single -3.4 1038 to +3.4 1038 32-bit floating-
point
number
double System.Double ±5.0 10–324 to ±1.7 10308 64-bit floating-
point
number
System Data Types… Cont’d
C# System Type Range Meaning
Shorthand
decimal System.Decimal (-7.9 x 1028 to 7.9 x 128-bit signed
1028) / (100 to 28) number
string System.String Limited by system memory Represents a set of
Unicode characters
Object System.Object Can store any data type in The base class of all
an object variable types in the .NET
universe
System Data Types… Cont’d
• By default, a floating-point number is treated as a double.
• To declare a float variable, use the suffix f or F to the raw
numerical value (5.3F)
• Suffix m or M to a floating-point number to declare a
decimal (300.5M).
• Raw whole numbers default to an int data type.
• To set the underlying data type to a long, suffix l or L (4L).
Variable Declaration and Initialization
• When you are declaring a local variable you do so by specifying the data
type followed by the variable’s name
• It is a compiler error to make use of a local variable before assigning an
initial value
•It is good practice to assign an initial value to your local data
points at the time of declaration.
•You may do so on a single line, or by separating the declaration
and assignment into two code statements.
Variable Declaration …. Cont’d
• It is also permissible to declare multiple variables of
the same underlying type on a single line of code
• Every C# data type keyword is an alias/shorthand
notation for a type in System namespace
• Hence you can use either the shorthand keyword or
the type in System namespace
Intrinsic Data Types and the new Operator
• All intrinsic data types support what is known as a
default constructor
• This feature allows you to create a variable using the
new keyword
• This automatically sets the variable to its default value
Intrinsic Data…. Cont’d
• bool variables are set to false.
• Numeric data is set to 0 (or 0.0 in the case of floating point
data types)
• char variables are set to a single empty character.
• BigInteger variables are set to 0.
• DateTime variables are set to 1/1/0001 12:00:00 AM
• Object references (including strings) are set to null.
The Data Type Class Hierarchy
• It is very interesting to note that even the primitive .NET
data types are arranged in a class hierarchy.
• The relationship between these core system types can be
understood as shown in the figure on the next slide
The Data Type Class Hierarchy
• Note that many numerical data types derive from a class
named System.ValueType
• Descendents of ValueType are automatically allocated on
the stack and, therefore, have a very predictable lifetime and
are quite efficient
• Other types are not allocated on the stack, but on the
garbage-collected heap
The Data Type Class Hierarchy
• All of these types ultimately derive from System.Object
• This type defines a set of methods common to all types in
the .NET base class libraries
• For example
• ToString()
• Equals()
• GetHashCode()
Members of Numerical Data Types
• Numerical types of .NET support MaxValue and MinValue
properties
• They provide information regarding the range a given type
can store
• A given numerical system type may define further useful
members.
• For example, the System.Double type allows you to obtain
the values for epsilon and infinity
Members of System.Boolean
• The only valid assignment a C# bool can take is from the set {true
| false}
• Hence, System.Boolean does not support a MinValue &
MaxValue property set
• Rather bool supports TrueString & FalseString
• These yield “True” & “False” respectively
Members of System.Char
• C# textual data is represented by the string and char
keywords
• These are simple shorthand notations for System.String
and System.Char
• Both are Unicode under the hood
• String represents a contiguous set of characters
• char represents a single slot in a string
Members of System.Char Cont’d
• The System.Char type provides you with a great deal of
functionality beyond the ability to hold a single point of
character data
• Using the static methods of System.Char, you are able to
determine whether a given character is
• Numerical
• Alphabetical
• A point of punctuation……
Parsing Values from String Data
• The .NET data types provide the ability to generate a
variable of their underlying type given a textual equivalent
(e.g., parsing).
• This technique can be extremely helpful when you wish to
convert a bit of user input data into a numerical value.
System.DateTime and System.TimeSpan
• The System namespace defines a few useful data types for
which there are no C# keywords
• This includes the DateTime and TimeSpan structures
• The DateTime type contains data that represents a specific
date time value, both of which may be formatted in a
variety of ways using the supplied members.
• The TimeSpan structure allows you to easily define and
transform units of time using various members.
System.DateTime and System.TimeSpan
• The System.Numerics namespace defines a structure
named BigInteger.
• As its name implies, the BigInteger data type can be used
when you need to represent humongous numerical values
• These are not constrained by a fixed upper or lower limit
• The System.Numerics namespace defines a second
structure named Complex, which allows you to model
mathematically complex numerical data
Working with String Data
• System.String provides a number of methods
• This include methods that
• Return the length of the character data
• Find substrings within the current string
• Convert to and from uppercase/lowercase
• The table on the next slide list some of this methods
String Members
Member Meaning
Length This property returns the length of the current string
Compare() This static method compares two strings.
Contains() This method determines whether a string contains a specific substring.
Equals() This method tests whether two string objects contain identical character
data.
Format() This static method formats a string using other primitives (e.g., numerical
data, other strings) and the {0} notation examined earlier in this chapter.
Insert() This method inserts a string within a given string.
String Members Cont’d
Member Meaning
PadLeft() These methods are used to pad a string with some characters.
PadRight()
Remove() Use these methods to receive a copy of a string with modifications
Replace() (characters removed or replaced).
Split() This method returns a String array containing the substrings in this instance
that are delimited by elements of a specified char array or string array.
Trim() This method removes all occurrences of a set of specified characters from
the beginning and end of the current string.
ToUpper() These methods create a copy of the current string in uppercase or lowercase
ToLower() format, respectively
String Concatenation
• String variables can be connected together to build
larger strings via the C# + operator
• This technique is formally termed string
concatenation
Escape Characters
• C# string literals may contain various escape
characters,
• This qualify how the character data should be printed
to the output stream.
• Each escape character begins with a backslash,
followed by a specific token.
Escape Characters Cont’d
Character Meaning
\' Inserts a single quote into a string literal
\" Inserts a double quote into a string literal
\\ Inserts a backslash into a string literal. This can be quite helpful when
defining file or network paths.
\a Triggers a system alert (beep). For console programs, this can be an audio
clue to the user.
\n Inserts a new line (on Windows platforms).
\r Inserts a carriage return
\t Inserts a horizontal tab into the string literal
Defining Verbatim Strings
• When you prefix a string literal with the @ symbol, you
have created what is termed a verbatim string.
• This way you disable the processing of a literal’s escape
characters and print out a string as is.
• This can be most useful when working with strings
representing directory and network path
Defining Verbatim Strings Cont’d
• Therefore, rather than making use of \\ escape characters,
you can simply write the string as is with single \
• Verbatim strings can be used to preserve white space for
strings that flow over multiple lines
• Using verbatim strings, you can also directly insert a
double quote into a literal string by doubling the " token
Strings and Equality
• A reference type is an object allocated on the
garbage-collected managed heap.
• By default, the C# == and != operators), compare if
the references are pointing to the same object in
memory.
• However, for string data type the equality operators
compare the values of string objects themselves
Strings and Equality
• The C# equality operators perform a case-sensitive,
character-by-character equality test on string objects.
• Therefore, "Hello!" is not equal to "HELLO!"
• Also, We are able to test for equality using the
Equals() method of String
• We are also able to access string-centric functionality
from a fixed sequence of characters.
Strings Are Immutable
• After you assign a string object with its initial value,
the character data cannot be changed.
• Methods of the string type are, in fact, returning you
a brand-new string object in a modified format.
Understanding Implicitly Typed Local
Variables
• Up until this point, when we have been defining
local variables, we’ve explicitly specified the
underlying data type of each variable being declared.
• However, The C# language does provide for
implicitly typing of local variables using the var
keyword
Understanding Implicitly Typed Local
Variables
• The var keyword can be used in place of specifying a
specific data type
• When you do so, the compiler will automatically infer the
underlying data type
• This is based on the initial value used to initialize the local
data point
Restrictions on Implicitly Typed Variables
• Implicit typing applies only to local variables in a method
or property scope
• It is illegal to use the var keyword to define return values,
parameters, or field data of a custom type
• Local variables declared with the var keyword must be
assigned an initial value at the exact time of declaration
• cannot be assigned the initial value of null
C# Iteration Constructs
• All programming languages provide ways to repeat
blocks of code until a terminating condition has been met
• C# provides the following four iteration constructs
• for loop
• foreach/in loop
• while loop
• do/while loop
The for Loop
• When you need to iterate over a block of code a
fixed number of times, the for statement provides a
good deal of flexibility
• You are able to specify how many times a block of
code repeats itself, as well as the terminating
condition
The foreach Loop
• The C# foreach keyword allows you to iterate over
all items in a container without the need to test for an
upper limit.
• Unlike a for loop however, the foreach loop will only
walk the container in a linear (n+1) fashion
• Thus, you cannot go backward through the container,
skip every third element, or whatnot.
The foreach Loop Cont’d
• However, when you simply need to walk a collection
item-by-item, the foreach loop is the perfect choice.
• The data type before the in keyword represents the
type of data in the container
The while Looping Construct
• The while looping construct is useful should you
wish to execute a block of statements until some
terminating condition has been reached.
• Within the scope of a while loop, you will need to
ensure this terminating event is indeed established
• Otherwise, you will be stuck in an endless loop
The do/while Looping Construct
• Closely related to the while loop is the do/while
statement.
• do/while is also used when you need to perform
some action an undetermined number of times
• However, do/while loops are guaranteed to
execute the corresponding block of code at least once
Decision Constructs and the
Relational/Equality Operators
• C# defines two simple constructs to alter the flow of
your program, based on various contingencies
• The if/else statement
• The switch statement
• Unlike in C and C++, the if/else statement in C#
operates only on Boolean expressions
Equality and Relational Operators
C# Equality/Relational Meaning
Operator
== Returns true only if each expression is the same.
!= Returns true only if each expression is different.
< Returns true if expression A is less than, greater
> than, less than or equal to, or greater than or equal
<= to expression B.
>=
Conditional Operators
Operator Meaning
&& Short circuit AND operator. Returns true if all expressions are
true.
|| OR operator. Returns true if at least one expression is true.
! NOT operator. Returns true if false, or false if true.
& AND operator. Same as && but bot operands are always
evaluated
| OR operator. Same as || but bot operands are always evaluated
Conditional Statements
• C# defines two simple constructs to alter the flow of
your program, based on various contingencies
• The if/else statement
• The switch statement
• Unlike in C and C++, the if/else statement in C#
operates only on Boolean expressions

You might also like