lect unit2
DESCRIPTION
pptTRANSCRIPT
Tokens
There are following five types of tokens:Keywords IdentifiersLiteralsOperatorspunctuators
Keywords
Keywords are an essential part of a language definition. They implement specific features of the language. They are reserved, and cant be used as identifiers except when they are prefaced by the @ character.
Example : abstract as base checked const do double ref
Identifiers
Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, labels, namespaces, interfaces, etc.
C# identifiers enforce the following rules:They can have alphabets, digits and
underscore characters.They must not begin with a digit.Upper case letters and lower case letters
are distinct.Keywords in standalone mode cant be
used as identifiers.
Literals
C# literalsC# literals
Boolean Literals Character LiteralsNumeric Literals
Integer Real Single Character String Literals
Literals are the ways in which the values that are stored in variables are represented
Continued…
Examples : Integer literals : 123 -321 0 654321 0X2Real literals : 0.0083 -0.75 435.36 0.65e4Boolean literals : true falseSingle character literals : ‘X’ ‘5’ ‘;’String literals : “Hello” “2001” “5+3”
Continued…
Backslash Character Literals
ConstantConstant MeaningMeaning
‘‘\a’\a’ AlertAlert
‘‘\b’\b’ Back spaceBack space
‘‘\f’\f’ Form feedForm feed
‘‘\n’\n’ New-lineNew-line
‘‘\r’\r’ Carriage returnCarriage return
‘‘\t’\t’ Horizontal ruleHorizontal rule
‘‘\v’\v’ Vertical tabVertical tab
‘‘\”\” Single quoteSingle quote
‘‘\”’\”’ Double quoteDouble quote
‘‘\\’\\’ BackslashBackslash
‘‘\o’\o’ NullNull
Operators
Operators are symbols used in expressions to describe operations involving one or more operands.
Examples :+-/*%
Punctuators
Punctuators are symbols used for grouping and separating code. They define the shape and function of a program.
Punctuators (also called as ‘separators’) in C# include:
Parentheses ( )Braces { }Brackets [ ]Semicolon ;Colon :Comma ,Period .
Variables & Constants
Variables - Declaration
Syntax : type var1, var2, …., varN;Examples : int count;float x, y;double pi;ulong n;
Variables - Initialization
Syntax : variableName = value; Variables must have Value before being used.Examples : i = 0; y = ‘x’; String assignment expression : x = y = z; At the time of declaration : int val = 100; char y = ‘x’; bool test = true; ulong ul = 123UL; decimal d = 1.23M;
Default Values
Following are automatically initialized to their default values: Static variables Instance variables Array elements
Type Default Value All integer types 0 char type ‘\x000’ float type 0.0f double type 0.0d decimal type 0.0m bool type false enum type 0 All reference types null
Constants
The variables whose value don’t change during the execution of a program can be made unmodifiable by using the const keyword while initializing them.
Examples :const int rows = 10;const int m; //Illegal as constants must be m = 10; //Declared and initialized
simultaneouslyNon-constant values cant be used : int m = 10; //Non-constant value const int n = m * 5; // Error
Types Of Variables
C# defines several categories of variables as :Static variables Instance variablesArray elementsValue parametersReference parametersOutput parametersLocal variables
Continued… Example :Class ABC{
static int m;int n;void fun (int x, ref int y,out int z, int [] a) {
int j = 10;…………
}}This code contains the following variables: Static variable m Instance variable n Array elements a[0] Value parameter x Reference parameter y Output parameter z Local variable j
C# Statements
A statement is an executable combination of tokens ending with a semicolon.
C# implements several types of statements including :
Empty statements Jump statements Labeled statements The try statements Declaration statements
The checked statements
Expression statements
The unchecked statements
Selection statements
The lock statements
Interaction statements
The using statements
TYPE HERARCHY
C# Unified Type System
C# Type .NET Framework type
Bool System.Boolean
Byte System.Byte
Spite System.SByte
Char System.Char
Decimal System.Decimal
Double System.Double
C# Data Types
Float System.Single
Int System.Int32
Uint System.UInt32
Long System.Int64
Ulong System.UInt64
Object System.Object
Short System.Int16
Ushort System.UInt16
String System.String
C# Data Types(Contd…)
Storage of Basic Types
Sizes of Fundamental Types
Type Storage
char, unsigned char, signed char 1 byte short, unsigned short 2 bytes int, unsigned int 4 bytes long, unsigned long 4 bytes float 4 bytes double 8 bytes long double 8 bytes
The Object Type
C# predefines a reference type named object.
Every reference and value type is a kind of object. This means that any type we work with can be assigned to an instance of type object.
For example, object o;o = 10;o = "hello, object";o = 3.14159;o = new int[ 24 ];o = false;
Value and Reference Types
Value Types
A variable of a value type always contains a value of that type.
The assignment to a variable of a value type creates a copy of the assigned value
All value types are derived implicitly from the Object class.
Two Categories of value types:-1. Struct type: user-defined struct types, Numeric types,
Integral types, Floating-point types, decimal, bool 2. Enumeration type
Reference Types
Variables of reference types, referred to as objects, store references to the actual data.
Assignment to a variable of a reference type creates a copy of the reference but not of the referenced object.Following are some of the reference types:
class interface delegate
The following are built-in reference types: object string
Simple Types
Type Default value
Bool false
Byte 0
Char '\0'
Decimal 0.0M
Double 0.0D
Value Types Defaults
Float 0.0F
Int 0
Long 0L
Sbyte 0
Short 0
Uint 0
Ulong 0
Ushort 0
Value Types Defaults(Contd…)
Enumerations
An enumeration consists of a set of named integer constants.
An enumeration type declaration gives the name of the enumeration tag and defines the set of named integer identifiers (called the "enumeration set“ or "members").
A variable with enumeration type stores one of the values of the enumeration set defined by that type.
Variables of enum type can be used in indexing
Enumerations(Contd…)
Operations on Enumerations
Declaration of Local Variables
Type Conversions
•Type conversions depend on the specified operator and the type of the operand or operators.
•Type conversions are performed in the following cases:
•When a value of one type is assigned to a variable of a different type or an operator converts the type of its operand or operands before performing an operation
•When a value of one type is explicitly cast to a different type
•When a value is passed as an argument to a function or when a type is returned from a function
Boxing and Unboxing
Accessibility
Access ModifiersAccess Modifiers
Access modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the four access modifiers:
public protected internal private The following five accessibility levels can be specified using the
access modifiers: public: Access is not restricted. protected: Access is limited to the containing class or types derived
from the containing class. Internal: Access is limited to the current assembly. protected internal: Access is limited to the current assembly or types
derived from the containing class. private: Access is limited to the containing type.
ARRAYS
An array is a data structure that contains a number of variables called the elements of the array. The array elements are accessed through computed indexes.
C# arrays are zero indexed
Array types are reference types derived from the abstract base type System.Array.
Arrays
TYPES OF ARRAYS
Single-Dimensional Arrays
Multidimensional Arrays
Jagged Arrays
Array Types
int[] myArray = new int[] {1, 3, 5, 7, 9};
string[] weekDays = new string[]
{"Sun","Sat","Mon","Tue","Wed","Thu",“Fri"};
It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable.
For example:- int[] myArray;
myArray = new int[] {1, 3, 5, 7, 9}; // OK myArray = {1, 3, 5, 7, 9}; // Error
Array Initialization
Onedimensional Arrays
Multidimensional Arrays
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes.
A jagged array is sometimes called an “array-of-arrays.”
Example:
int[][] myJagArr = new int[3][];
It is also possible to use initializers to fill the array elements with values, in which case you don't need the array size;
Jagged Array
For Example:myJaggedArray[0] = new int[] {1,3,5,7,9};myJaggedArray[1] = new int[] {0,2,4,6};myJaggedArray[2] = new int[] {11,22};
Before you use myJaggedArray, its elements must be initialized. You can initialize the elements like this:
Example:My JaggedArray[0] = new int[5];myJaggedArray[1] = new int[4];myJaggedArray[2] = new int[2];
Jagged Array(Contd…)
For Example:myJaggedArray[0] = new int[] {1,3,5,7,9};myJaggedArray[1] = new int[] {0,2,4,6};myJaggedArray[2] = new int[] {11,22};
Before you use myJaggedArray, its elements must be initialized. You can initialize the elements like this:
Example:My JaggedArray[0] = new int[5];myJaggedArray[1] = new int[4];myJaggedArray[2] = new int[2];
Jagged Array(Contd…)
You can also initialize the array upon declaration like this:
int[][] myJagArr = new int [][] {
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22} };
Jagged Array(Contd…)
Strings
Strings
Characters, words, sentences, paragraphs, spaces, punctuation marks, and even numbers can be stored as a string in a variable. Strings are always enclosed within quotations marks and must be declared.
The following are some string variable examples:
String word = "Hello"; String sentence = "This is a sentence!"; String letter = "y"; String no = "5";
Strings
You don't have to declare a variable as a string and assign a value to it at the same time, as illustrated in the next example:
String sentence; sentence = "This is a sentence!";
Multiple string variables can be declared simultaneously by separating each variable with a comma:
String var1, var2, var3, var4; The String class is a core .NET C# base class.
Variables declared as a string are actually objects of the String class. String variables have access to all the methods and properties within the String class.
Strings
Method: Purpose Compare(): Compares two strings and returns
True if they are equal.Concat(): Joins two strings together.IndexOf(): Returns the first occurrence of a
character or string.Last IndexOf(): Returns the last occurrence of a
character or string.PadLeft(): Adds spaces to the beginning of a
string.PadRight(): Adds spaces at the end of a string.
Strings
Method: Purpose Substring(): Extracts a portion of a string.ToLower(): Converts all characters in a string to
lowercase.ToUpper(): Converts all characters in a string to
uppercase.Trim(): Removes spaces at the beginning and end
of a string.TrimEnd(): Removes spaces at the end of a string.TrimStart(): Removes spaces at the beginning of a
string.
Strings
In the following example, we declare a variable, assign a value to it, and then use the ToUpper() and ToLower() methods to change case:
String name = "Aneesha"; String lowercaseName = name.ToLower();
(aneesha)String uppercaseName = name.ToUpper();
(ANEESHA)
Strings – Special Characters
Data that is assigned to a string variable is always enclosed within quotation marks. This raises an interesting question: What if you have to include a quote within a string? The \ is a special escape character that allows you to include quotation marks within the string. The \ escape character must precede the quotation marks embedded within a string.
The following code would cause a syntax error because quotation marks are used in a string without being escaped:
String quote = "Celine said "Hello!" "; The correct way to include quotation marks is to place a \
in front of each quotation mark:String quote = "Celine said \"Hello!\"";
Strings – Special Characters
Now, if \ is the escape character, how do you declare a string that includes slashes, such as a file path (for example, c:\temp\files\temp.txt)? The following declaration would also cause a syntax error:
String path = "c:\temp\files\"; All intentional slashes need to be preceded by
the \ escape character. So the declaration of the path should look like the following:
String quote = "c:\\temp\\files\\";
Strings – Special Characters
Escape Sequence Special Character
\' Single quotation mark\" Double quotation mark\\ Backslash\t Tab
Strings – Special Characters
Placing the @ symbol in front of a string in C# creates a verbatim string. In verbatim strings, there is no need to escape characters. An example of a verbatim string follows:
String path = @"c:\temp\files\"; Verbatim strings can even span multiple lines:
String paragraph = @"This is the first sentence. This is the second sentence printed on a new line. This is the third sentence printed on a new line"
String Length
It is useful to be able to calculate the number of characters in a string. Sometimes, you'll also need to set a limit on the amount of text that a user can enter into a form element.
The Length property of a string variable returns a count of the number of characters stored within the string.
In the following code, we initialize a string variable and then determine the number of characters in the string:
String name = "My name is Celine Bakharia";
int noOfChars = name.Length;
Number to String Conversion
A numeric value can be converted to a string by calling the ToString() method. The ToString() method changes the data type of the value from an integer to a string. Here is an example:
int no = 10; string noAsString = no.ToString();
Joining Strings
The process of appending two strings together is known as concatenation. The + operator or the Concat() method can be used to concatenate strings.
The following example uses the + operator to construct a sentence containing a user's full name. As you can see, the + operator allows many strings to be appended to each other and stored:
String firstname = "Celine"; String surname = "Bakharia"; String sentence = "Welcome " + firstname + " " +
surname + "."; The sentence variable will contain the string
"Welcome Celine Bakharia."
Joining Strings
The Concat() method can only join two strings together:
String countTo5 = "12345";
String countTo9 = "6789";
String full Count = string.Concat(countTo5, countTo9);
The full Count variable will contain the string "123456789".
String Comparison
Two strings can be compared by using the equal to (==) or not equal to (!=) operators:
string name=“Hasan”;if (name == “Hasan”){
textBox1.Text=“Correct”;}
String Comparison
The String class also contains a Compare() method, which returns:less than zero if the invoking string is less
than second string greater than zero if the invoking string is
greater than second string zero if the strings are equal.
string answer1 = "madonna"; string answer2 = "MADONNA";
int checkAnswer = string.Compare(answer1,answer2);
String Comparison
We can, however, force the Compare() method to be case insensitive by passing an additional parameter to the method:int checkAnswer2 = string.Compare(answer1, answer2, true);
This allows us to compare the two answers without using the ToUpper() or ToLower() method to convert both answers to the same case. 0 will give equality.
Trim and Pad Strings
The String class even contains methods to remove and add spaces at the beginning or end of a string. The ability to remove extra spaces is particularly useful when you need to process and store data that a user has entered into a form:
The TrimEnd() method removes extra spaces from the end of a string:
string Name = "Celine "; Name = Name.TrimEnd(); // Name will be
"Celine"
Trim and Pad Strings
The TrimStart() method removes extra spaces from the beginning of a string: string Name = " Celine"; Name = Name.TrimStart(); // Name will be "Celine"
The Trim() method removes extra spaces from the beginning and end of a string:
string Name = " Celine "; Name = Name.Trim(); // Name will now be
"Celine"
Trim and Pad Strings
We can also add extra spaces to either the beginning or end of a string. The PadLeft() method adds spaces to the beginning of a string, while the PadRight() method adds spaces to the end of the string. An example of using PadLeft() follows:
string Sentence = "This is a sentence! "; Sentence = Sentence.PadLeft(5);
// Sentence will contain " This is a sentence!"
Immutable String Object
The contents of a string object are immutable. That is, once created, the character sequence comprising that string cannot be altered. This restriction allows C# to implement strings more efficiently. Even though this probably sounds like a serious drawback, it isn’t. When you need a string that is a variation on one that already exists, simply create a new string that contains the desired changes. Since unused string objects are automatically garbage-collected, you don’t even need to worry about what happens to the discarded strings.
It must be made clear, however, that string reference variables may, of course, change the object to which they refer. It is just that the contents of a specific string object cannot be changed after it is created.
Substring
To fully understand why immutable strings are not a hindrance, we will use another of string’s methods: Substring( ).
The Substring( ) method returns a new string that contains a specified portion of the invoking string. Because a new string object is manufactured that contains the substring, the original string is unaltered, and the rule of immutability is still intact. The form of Substring( ) that we will be using is shown here:
string Substring(int start, int len) Here, start specifies the beginning index, and len
specifies the length of the substring.
Substring
Here is a program that demonstrates Substring( ) and the principle of immutable strings:
// Use Substring(). using System; class SubStr {
public static void Main() { string orgstr = "C# makes strings
easy."; // construct a substring string substr = orgstr.Substring(5,
12); Console.WriteLine("orgstr: " + orgstr); Console.WriteLine("substr: " + substr);
} } Here is the output from the program:
orgstr: C# makes strings easy. substr: kes strings
Substring
As you can see, the original string orgstr is unchanged and substr contains the substring.
One more point: Although the immutability of string objects is not usually a restriction or hindrance, there may be times when it would be beneficial to be able to modify a string. To allow this, C# offers a class called StringBuilder, which is in the System.Text namespace. It creates string objects that can be changed. For most purposes, however, you will want to use string, not StringBuilder.
Contains
Contains: Returns a Boolean indicating whether the current string instance contains the given substring.
string str.Contains(char value)
Search for Username
The aim is to check the validity of a given e-mail address for “@” and “.”. And reply by user’s name which is defined as the string before “@” character.
Search for Username
string orgstr,username; orgstr = textBox1.Text;
// find @ in substring if (orgstr.Contains ("@")) { // find . in substring if (orgstr.Contains(".")) { username = orgstr.Substring(0,
orgstr.IndexOf("@")); textBox1.Text = "Hello " + username;
} }
Split Words of a Sentence
string orgstr,username, substr; int a, b; substr = textBox1.Text; orgstr = textBox1.Text; textBox1.Text = "";
while (substr.Contains(" ")) { username = substr.Substring(0, substr.IndexOf(" ")); textBox1.Text = textBox1.Text + username + " + "; a = substr.IndexOf(" "); b = substr.Length; orgstr = substr.Substring(a+1, b-a-1); substr = orgstr; } textBox1.Text = textBox1.Text + substr; } }
Search and Replace
The Replace() method allows you to search for and replace a sequence of characters within a string.
When the Replace() method is called, all occurrences of the search string are replaced.
The Replace() method takes two parameters. The first string that is passed to the Replace() method is the substring that you want to replace. The string passed as the second parameter will replace the first parameter when the Replace() method is called.
In the following example, all occurrences of the word car are replaced with the word bicycle:
String travel = @"I use a car every day. The car is a luxury.";
travel = travel.Replace("car", "bicycle");