Professional Documents
Culture Documents
C# Basics
IMCEITS
Need of C#
Goals of C#
Strengths of C#
Design of C#
C# Basics
Need of C#
Existing languages are powerful.
Important features are spread out over multiple
languages
While C++ gives programmers a tremendous amount of
power and control, it may take several more lines of
code to perform an operation requiring a single line of
code in languages like Visual Basic and Java
C# is the result in the search for a way to marry the
productivity of Visual Basic with the syntax and power
of C++.
Goals of C#
Give developers a single language with
– A full suite of powerful features
– A consistent and simple syntax
Increase developer productivity!
– Type safety
– Garbage collection
– Exceptions
– Leverage existing skills
Goals of C# (Cont.)
using Util.Figures;
class Test {
Rect r; // without qualification (because of using Util.Figures)
Triangle t;
Util.Color c; // with qualification
}
Foreignnamespaces
must either be imported (e.g. using Util;)
or specified in a qualified name (e.g. Util.Color)
Most programs need the namespace System => using System;
Namespaces (Cont.)
Fixed length
Store on the stack
When a value of a variable is assigned to another
variable, the value is actually copied (i.e two identical
copies of the value are available in memory)
Value Types (Cont.)
Example:
int hex = 0x9f;
Console.WriteLine("{0:x}",hex);
Real Literals
Example:
double exp = 3.18e3;
Console.WriteLine("{0:e}", exp);
Boolean Literals
2 values
true and false
Example:
bool flag = false;
Console.WriteLine(flag);
Single Character Literals & String Literals
Example:
char grade=‘A’;
string result=“Credit”;
Backslash Character Literals
\a - Alert (usually the HW beep)
\b - Backspace
\n - New line
\0 - Null
\t - Horizontal tab
\v - Vertical tab
\' - Single quote
\" - Double quote
\\ - Backslash
\f - Form feed
\r - Carriage return
Comments
Single-line comments - //
Multiline comments - /* */
Variables
Declaration
datatype identifier;
int i;
Initialization of Variables
- two methods
- if not initialized explicitly, variables are by default
zeroed out when they are created (for variables are fields
in a class or struct )
- Must be explicitly initialized (for local variables in a
method)
Variable scope
- region of code from which the variable can be accessed
- field , local variable in method, local variable in block
Default Values
A variable is either explicitly assigned a value or
automatically assigned a default value
Type Default Value
All integer types 0
Pre-test loop
bool condition =false;
int i=3;
while(!condition)
{
System.Console.WriteLine(“{0}\t”,i);
i--;
if (i==0) condition=true;
}
do-while
syntax:
do{
Statements;
} while (condition)
post-test version of while loop
bool condition =false;
int i=3;
do
{
System.Console.WriteLine(“{0}\t”,i);
i--;
if (i==0) condition=true;
} while(!condition);
for
syntax:
for (initializer;condition;iterator)
statement[s]
Pre-test loop
Loop condition is evaluated before the loop statements are
executed
for (int i=0;i<5;i++)
System.Console.WriteLine(i);
foreach
syntax:
foreach (variable1 in variable2) statement[s]
Iterates through all items in an array or collection
collection is a class which implements the interface
IEnumerable or declares GetEnumerator
To iterate through the values contained by any object which
implements the IEnumerable interface
When a 'foreach' loop runs, the given variable1 is set in turn to
each value exposed by the object named by variable2.
int[] a = new int[]{1,2,3};
foreach (int b in a)
System.Console.WriteLine(b);
break
breaks out of the 'while' and 'for' loops and the
'switch' statements
int a = 0;
while (true)
{
System.Console.WriteLine(a);
a++;
if (a == 5)
break;
}
continue
Can be placed in any loop structure
When it executes, it moves the program counter
immediately to the next iteration of the loop
int y = 0;
for (int x=1; x<101; x++)
{
if ((x % 7) == 0)
continue;
y++;
}
goto
Is used to make a jump to a particular labelled part of the
program code and in the 'switch' statement
To construct a loop (this usage is not recommended)
int a = 0;
start:
System.Console.WriteLine(a);
a++;
if (a < 5)
goto start;
return
A method will stop and return a value if it reaches a
'return' statement at any point in its execution
The type returned is given at the end of such a return
statement
Its type must correspond with that specified in the
method declaration
if (condition)
[statements]
else if (condition)
[statements]
else [statements]
Switch Expression
Type of switch expression switch ( expression )
{
case value-1:
- numeric, char, enum or
block-1
string break;
(null ok as a case label). case value-2:
block-2
No fall-through! break;
- Every statement sequence ……………..
default :
in a case must be terminated
default-block
with break (or return, goto, break;
throw) }
Boxing and Unboxing
Explicit Conversion
int m=100;
Object om=m;
int n= (int) om;
Arrays
One-dimensional Arrays
Multidimensional Arrays
Jagged Arrays
Arrays
All arrays are instances of the base class System.Array
Many useful properties and methods
Rank, Length, Sort, Clear, Clone, GetLength,
IndexOf
The overhead is greater than that for C++ arrays
IndexOutOfRangeException
Copying an array variable copies the reference only
Implement ICloneable, IList, ICollection, IEnumerable
One-dimensional Arrays
Multidimensional Arrays
One- Dimensional Arrays
Person[] beatles = {
new Person { FirstName="John", LastName="Lennon" },
new Person { FirstName="Paul", LastName="McCartney" }
};
Person[] beatlesClone = (Person[])beatles.Clone();
Sorting Array
string[] names = {
"Christina Aguilera",
"Shakira",
"Beyonce",
"Lady Gaga"
};
Array.Sort(names);
Declaration
string st1;
String st2;
string st1=“IMCEITS”;
String st2=“UCSY”
string st1;
st1= “DAST”
String st2;
st2=“MOST”;
Constructing Strings (Cont.)
Verbatim Strings - Verbatim string literals begin with @"
and end with the matching quote. They do not have escape
sequences.
create variables named
@if, @string
string st1=@“\EBG\CSharp\my.cs”;
or
string st1=“\\EBG\\CSharp\\my.cs”;
a single string to span more than one line
string str =
@"I'm so happy to be a string
that is split across
a number of different
lines.";
Constructing Strings (Cont.)
string st1=@“\EBG\CSharp\my.cs”;
or
string st1=“\\EBG\\CSharp\\my.cs”;
string st1;
st1= “DAST”
String st2;
st2=“MOST”;
public sealed class String
public char this[int index] {get;}
public int Length {get;}
public static int Compare(string strA, string strB); // Culture!
public static int CompareOrdinal(string strA, string strB); // without Culture!
public static string Format(string format, object arg0);
public int IndexOf(string);
public int IndexOfAny(char[] anyOf);
public int LastIndexOf(string value);
public string PadLeft(int width, char c); // s.PadLeft(10,'.'); ".....Hello"
public string[] Split(params char[] separator);
public string Substring(int startIndex, int length);
...
}
Operations on Strings
Copying Strings
Concatenating Strings
Inserting Strings
Searching Strings
Comparing Strings
Finding Substrings
Copying Strings
Output
String.Compare("bbc", "abc") =1
String.Compare(“abc", “bbc") =-1
String.Compare("bbc", “bbc") =0
Comparing Strings
result = String.Compare("bbc", "BBC", true);
Console.WriteLine("String.Compare(\"bbc\", \"BBC\", true) = " + result);
result = String.Compare("bbc", "BBC", false);
Console.WriteLine("String.Compare(\"bbc\", \"BBC\", false) = " + result);
result = String.Compare("Hello World", 6, "Goodbye World", 8, 5);
Console.WriteLine("String.Compare(\"Hello World\", 6, " + "\"Goodbye
World\", 8, 5) = " + result); // space compare
}
}
Output
String.Compare("bbc", "BBC", true) =0
String.Compare("bbc", "BBC", false) =-1
String.Compare("Hello World", 6, " + "Goodbye World", 8, 5) =0
Split Strings
using System;
class String_Split
{
public static void Main()
{
string[] myStrings = {"To", "be", "or", "not", "to", "be"};
string myString9 = String.Join(".", myStrings);
Console.WriteLine("After join is " + myString9);
myStrings = myString9.Split('.');
foreach (string mySplitString in myStrings)
{
Console.WriteLine("mySplitString = " + mySplitString);
}
}
}
Split Strings
Output
class Finding_string
{
public static void Main()
{
string[] myStrings = {"To", "be", "or", "not", "to", "be"};
foreach (string st in myStrings)
{
bool flag = st.StartsWith("b");
Console.WriteLine(flag.ToString()); Output
} False
}
} True
False
False
False
True
Remove, Replace,
using System;
class String_Remove
{
public static void Main()
{
string[] myStrings = {"To", "be", "or", "not", "to", "be"};
string myString = String.Join(".", myStrings);
string myString10 = myString.Insert(6, "A, ");
Console.WriteLine("myString.Insert(6, \"A, \") = " + myString10);
string myString11 = myString10.Remove(14, 7);
Console.WriteLine("myString10.Remove(14, 7) = " + myString11);
string myString12 = myString11.Replace(',', '?');
Console.WriteLine("myString11.Replace(',', '?') = " + myString12);
string myString13 = myString12.Replace("to be", "Or not to be A");
Console.WriteLine("myString12.Replace(\"to be\", \"Or not to be A\")
= " + myString13);
}
}
Remove, Replace,
Output
Initialization
string [] str= {“This”,”is”,”a”,”test”};
Strings & switch statements
Strings can be used in switch statements
foreach(string s in strs)
{ switch(s)
{ case “Mon” : num=1;break;
case “Tue” : num=2;break;
case “Wed” : num=3;break;
}
}
Formatting String
String.Format (format string , arguments)
Format string contains groups of the form
{ index[ , alignment][ : codes]}
Output
1: Amar
2: Akbar
3: Antony are friends
Regular Expressions : Example 2
using System;
using System.Text.RegularExpressions;
namespace Session2
{ class TestRegularExpressions
{ static void Main()
{ string[] sentences = { "cow over the moon", "Betsy the Cow", "cowering
in
the corner", "no match here“ };
string sPattern = "cow“;
foreach (string s in sentences)
{ System.Console.Write("{0,24}", s);
if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern,
RegexOptions.IgnoreCase))
{System.Console.WriteLine(" (match for '{0}' found)", sPattern); }
else
{ System.Console.WriteLine(); }
}
Regular Expressions : Example 2(cont.)
Output