Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
C# Language Fundamentals
1
OBJECTIVES
Basic C# Class
Constructors
Basic Input and Output
Value Types and Reference Types
Iteration Statements
Control Flow Statements
Static Methods and Parameter passing Methods
Arrays, Strings, and String Manipulations
Enumerations and Structures
2
Basic C# Class
// Hello.cs The using keyword has two major uses:
using Directive Creates an alias for a namespace
using System; or imports types defined in other namespaces.
class HelloClass using Statement Defines a scope at the end of
{ which an object will be disposed.
public static int Main(string[ ] args)
{
Console.WriteLine("Hello World");
return 0;
}
}
3
Basic C# Class - Variations
// Hello1.cs // Hello2.cs
using System; using System;
class HelloClass class HelloClass
{ {
public static void Main()
public static void Main(string[ ] args)
{
{ // ………….
// ………. }
} }
}
4
Command Line Parameters
// clp.cs
using System;
class HelloClass
{
public static int Main(string[ ] args)
{
Console.WriteLine("Command Line parameters");
for (int x = 0; x < args.Length; x++) // foreach (string s in args)
Console.WriteLine("Args: {0}", args[x]);
return 0;
}
}
5
CONSTRUCTORS
Works almost same as C++
"new" is the de facto standard to create an object
instance
Example ( illegal ) Correct version
HelloClass c1; HelloClass c1 = new HelloClass();
c1.SayHi(); c1.SayHi();
C# object variables are references to the objects in memory
and not the actual objects
Garbage collection is taken care by .NET
6
EXAMPLE (Point.cs)
class Point
{
public Point()
{ Console.WriteLine("Default Constructor"); }
public Point(int px, int py)
{ x = px; y = py; }
public int x; Program
public int y; Entry Point
}
class PointApp
{
public static void Main(string[ ] args)
{
Point p1 = new Point(); // default constructor called
Point p2;
p2 = new Point(10, 20); // one –arg constructor called
Console.WriteLine("Out: {0}\t{1}", p1.x, p1.y);
Console.WriteLine("Out: {0}\t{1}", p2.x, p2.y);
}
}
Default Values
Public variables/members automatically get default values
Example
class Default
{
public int x; public object obj;
public static void Main (string [ ] args)
{
Default d = new Default();
// Check the default value
}
}
12
Example - 1
public void SomeMethod()
{
int i = 30; // i is 30
int j = i; // j is also 30
int j = 99; // still i is 30, changing j will not change i
}
13
Example - 2
struct Foo
{
public int x, y;
}
15
Value Types containing
Reference Types
When a value type contains other reference types,
assignment results only in "reference copy"
We have two independent structures, each of which
contain reference pointing to the same object in
memory – "shallow copy"
To perform deep copy (where state of internal
references fully copied into new object), we must use
ICloneable interface
Example: ValRef.cs
16
Example InnerRef valWithRef = new
// ValRef.cs InnerRef("Initial Value");
// This is a Reference type – because it is a class
class TheRefType
valWithRef.structData = 666;
{
public string x;
public TheRefType(string s) valWithRef
{ x = s; }
structData = 666
}
// This a Value type – because it is a structure type refType x=
struct InnerRef "I am NEW"
"Initial Value"
{
valWithRef2
public TheRefType refType; // ref type
public int structData; // value type structData = 777
class Person
{
public string fullName;
public int age;
public Person(string n, int a)
{
fullName = n;
age = a;
}
public Person(){}
public void PrintInfo()
{ Console.WriteLine("{0} is {1} years old", fullName, age); }
}
Passing Reference types by
Value
SendAPersonByValue() Method attempts to reassign the incoming Person reference to new object
as well as change some state data
27
Example
namespace System
{
public class Object
can be overridden
{
by derived class
public Object();
public virtual Boolean Equals(Object(obj);
public virtual Int32 GetHashCode();
public Type GetType();
public virtual String ToString();
protected virtual void Finalize();
protected Object MemberwiseClone();
public static bool Equals(object objA, object objB);
public static bool ReferenceEquals(object objA, object objB); }
}
28
Core Members of System.Object
Equals() Returns true only if the items being compared refer
to the exact same item in memory
GetHashCode() Returns an integer that identifies a specific object
instance
GetType() Returns System.Type
ToString() Returns <namespace.class name> in string format
29
Create System.Object Methods
// ObjTest.cs ToString: ObjTest
using System;
GetHashCode: 1
class ObjTest
{ GetType: System.Object
public static void Main (string [ ] args) Same Instance
{
ObjTest c1 = new ObjTest();
33
Example
class Person
{
public override bool Equals(object o)
{
Person temp = (Person) o;
if (temp.firstName == this.firstName &&
temp.lastName == this.lastName &&
temp.SSN == this.SSN &&
temp.age == this.age) return true;
else return false;
}
…
}
Overriding GetHashCode()
When a class override Equals(), it should also override
GetHashCode()
Returns All custom types will be put in a
System.Collections.Hashtable type. The Equals() and
GetHashCode() methods will be called behind the scene to
determine the correct type to return from the container
Generation of hash code can be customized. In our example
we shall use SSN – a String member that is expected to be
unique
Example: refer to: Override.cs
public override int GetHashCode()
{ return SSN.GetHashCode(); }
The System Data Types & C# Aliases
C# Alias CLS ? System Type Range
sbyte No System.SByte -128 to 127
byte Yes System.Byte 0 to 255
short Yes System.Int16 -32768 to 32767
ushort No System.UInt16 0 to 65535
int Yes System.Int32 -2,147,438,648 to +2,147,438,647
uint No System.UInt32 0 to 4,294,967,295
long Yes System.UInt64 -9,223,372,036,854,775,808 to +9,…..
ulong No System.UInt64 0 to 18,446,744,073,709,551,615
char Yes System.Char U10000 to U1FFFF
float Yes System.Single 1.5×10-45 to 3.4×1038
double Yes System.Double 5.0×10-324 to 1.7×10308
bool Yes System.Boolean true or false
decimal Yes System.Decimal 100 to 1028
string Yes System.String Limited by system memory
object Yes System.Object Anything at all
Hierarchy of System Types
Object Boolean
UInt16
Byte
Type UInt32
Char
ValueType
String UInt64
(derived one Decimal
is Void
Array struct or Double
enum DateTime
Exception and not Int16
class) Guid
Delegate Int32
TimeSpan
Int64
Single
MulticastDelegate SByte
37
Enumerations and Structures
Examples
Integers
UInt16.MaxValue
UInt16.MinValue
Double
double.Maxvalue
double.MinValue
double.PositiveInfinity
double.NegativeInfinity
Boolean
bool.FalseString
bool.TrueString
38
Examples
// These statements are identical.
bool b1 = new bool(); // b1 = false.
bool b2 = false;
// These statements are also semantically
identical.
System.Boolean b1 = new System.Bool(); // b1 = false.
System.Boolean sb2 = false;
39
Numerical data types
The numerical types of .NET support MaxValue and MinValue properties that
provide information regarding the range a given type can store
40
Numerical data types
// Now in System.UInt16 shorthand (e.g., a ushort).
ushort myOtherUInt16 = 12000;
Console.WriteLine("Max for an UInt16 is: {0} ", ushort.MaxValue); 65535
Console.WriteLine("Min for an UInt16 is: {0} ", ushort.MinValue); 0
Console.WriteLine("Value is: {0} ", myOtherUInt16); 12000
Console.WriteLine("I am a: {0} ", myOtherUInt16.GetType()); System.UInt16
Console.ReadLine();
}
41
Numerical data types
System.Double type allows you to obtain the values for Epsilon and
infinity values:
Console.WriteLine("-> double.Epsilon: {0}", double.Epsilon);
Console.WriteLine("-> double.PositiveInfinity: {0}", double.PositiveInfinity);
Console.WriteLine("-> double.NegativeInfinity: {0}", double.NegativeInfinity);
Console.WriteLine("-> double.MaxValue: {0}", double.MaxValue);
Console.WriteLine("-> double.MinValue: {0}",double.MinValue);
-> double.Epsilon: 4.94065645841247E-324
-> double.PositiveInfinity: Infinity
-> double.NegativeInfinity: -Infinity
-> double.MaxValue: 1.79769313486232E+308
-> double.MinValue: -1.79769313486232E+308
42
Members of System.Boolean
consider the System.Boolean data type. Unlike C(++), the only valid assignment a C#
bool can take is from the set {true | false}
System.Boolean does not support a MinValue/MaxValue property set, but rather
TrueString/FalseString:
bool b = 0; // Illegal!
bool b2 = -1; // Illegal!
bool b3 = true; // No problem.
bool b4 = false; // No problem.
Console.WriteLine("-> bool.FalseString: {0}", bool.FalseString); False
Console.WriteLine("-> bool.TrueString: {0}", bool.TrueString); True
43
Members of System.Char
C# textual data is represented by the intrinsic C# string and char data types.
Using the static methods of System.Char, we are able to determine if a given character
is numerical, alphabetical, a point of punctuation, or whatnot.ented by the intrinsic C#
string and char data types.
static void Main(string[] args)
{
// Test the truth of the following statements...
Console.WriteLine(“ {0}", char.IsDigit('K')); False
Console.WriteLine(“{0}", char.IsDigit('9')); True
Console.WriteLine(“ {0}", char.IsLetter("10", 1)); false
Console.WriteLine(“ {0}", char.IsLetter('p')); True
Console.WriteLine(“ {0}", char.IsWhiteSpace("Hello There", 5)); True
44
Members of System.Char
Console.WriteLine(“ {0}“,char.IsWhiteSpace("Hello There", 6)); False
Console.WriteLine(“ {0}“,char.IsLetterOrDigit('?')); False
Console.WriteLine(“ {0}“,char.IsPunctuation('!')); True
Console.WriteLine(“ {0}“,char.IsPunctuation('>')); False
Console.WriteLine(“ {0}“,char.IsPunctuation(',')); True
}
As we can see, each of these static members of System.Char has two calling
conventions: a single character or a string with a numerical index that specified the
position of the character to test.
45
Parsing Values from String Data
.NET data types provide the ability to generate a variable of their
underlying type given a textual equivalent (e.g., parsing).
static void Main(string[] args)
{
bool myBool = bool.Parse("True");
Console.WriteLine("-> Value of myBool: {0}", myBool); True
double myDbl = double.Parse("99.884");
Console.WriteLine("-> Value of myDbl: {0}", myDbl); 99.884
int myInt = int.Parse("8");
Console.WriteLine("-> Value of myInt: {0}", myInt); 8
char myChar = char.Parse("w");
Console.WriteLine("-> Value of myChar: {0}\n", myChar); w
} 46
System.DateTime and System.TimeSpan
The DateTime type contains data that represents a specific date (month, day, year) and time value,
both of which may be formatted in a variety of ways using the supplied members.
static void Main(string[] args)
{
// This constructor takes (year, month, day)
DateTime dt = new DateTime(2004, 10, 17);
// What day of the month is this?
Console.WriteLine("The day of {0} is {1}", dt.Date, dt.DayOfWeek);
dt = dt.AddMonths(2); // Month is now December.
Console.WriteLine("Daylight savings: {0}", dt.IsDaylightSavingTime());
}
The day of 10/17/2004 12:00:00 AM is Sunday
DaylightSavingTime: False
47
System.DateTime and System.TimeSpan
The TimeSpan structure allows you to easily define and transform units of time using various
members:
static void Main(string[] args)
{ // This constructor takes (hours, minutes, seconds)
TimeSpan ts = new TimeSpan(4, 30, 0);
Console.WriteLine(ts);
// Subtract 15 minutes from the current TimeSpan and print the result.
Console.WriteLine(ts.Subtract(new TimeSpan(0, 15, 0)));}
48
Value Type and Reference Type
Value Type
Value types are used directly by their values
int, float, char, enum, etc. are value types
These types are stored in a Stack based memory
Example: int Age = 42; or int Age = new int(42);
Stack
int 42
49
Reference Type
These types are allocated in a managed Heap
Objects of these types are indirectly referenced
Garbage collection is handled by .NET
Objects
Reference Variables
51
UnBoxing
Converting the value in an object reference (held in
heap) into the corresponding value type (stack)
//Unbox the reference back into corresponding int
int Age = (int) objAge; // OK
string str = (string) objAge; // Wrong!
The type contained in the box is int and not
string!
52
Examples
C# compiler automatically boxes variables when appropriate
class Program
{
static void Main(string[] args)
{
// Create an int (value type).
int myInt = 99;
// Because myInt is passed into a method prototyped to take an object, myInt is 'boxed' automatically.
UseThisObject(myInt);
Console.ReadLine();
}
static void UseThisObject(object o)
{
Console.WriteLine("Value of o is: {0}", o);
}
}
53
Examples
static void BoxAndUnboxInts()
{
// Box ints into ArrayList.
ArrayList myInts = new ArrayList();
myInts.Add(88);
myInts.Add(3.33);
myInts.Add(false);
// Unbox first item from ArrayList.
int firstItem = (int)myInts[0];
Console.WriteLine("First item is {0}", firstItem);
}
54
C# Iteration Constructs
for loop
foreach-in loop
while loop
do-while loop
55
The for Loop
C# for Loop is same as C, C++, Java, etc
Example
for (int i = 0; i < 10; i++)
Console.WriteLine(i);
You can use "goto", "break", "continue", etc like other
languages
56
The foreach/in Loop
using System;
class ForEach
{
public static void Main(string[] args)
{
string[ ] Names = new string [ ] {"Arvind 67", "Geetha 90",
"Madhu 34", "Priya 67"};
int n = 0;
foreach (string s in Names)
{
if (s.IndexOf("6") != -1)
n++;
}
Console.WriteLine("No. of Students scored above 60 = {0}", n);
}
}
57
The while and do/while Loop
class FileRead
{
public static void Main(string[] args)
{
try
{
StreamReader strReader = File.OpenText("d:\\in.dat");
string strLine = null;
while (strReader.ReadLine( ) != null)
{
Console.WriteLine(strLine);
}
strReader.Close();
}
catch (FileNotFoundException e)
{
Console.WriteLine(e.Message);
}
}
}
58
Control Statements
if, if-else Statements
Relational operators like ==, !=, <, >, <=, >=, etc are all
allowed in C#
Conditional operators like &&, ||, ! are also allowed in C#
Beware of the difference between int and bool in C#
Example
string s = "a b c";
if (s.Length) Error!
{ …. }
59
The switch Statement
Same as C, C++, etc. with some restrictions
Every case should have a break statement to avoid
fall through (this includes default case also)
Example switch(country)
switch(country) { // Correct
{ case "India": HiIndia();
// Error – no break break;
case "India": case "USA": HiUSA();
case "USA": break;
default: default: break;
} }
60
goto Statement
goto label;
Explicit fall-through in a switch statement can be
achieved by using goto statement
Example: switch(country)
{
case "India": HiIndia();
goto case "USA";
case "USA": HiUSA();
break;
default: break;
}
61
C# Operators
All operators that you have used in C and C++ can
also be used in C#
Example: +, -, *, /, %, ?:, ->, etc
Special operators in C# are : typeof, is and as
The is operator is used to verify at runtime whether
an object is compatible with a given type
The as operator is used to downcast between types
The typeof operator is used to represent runtime
type information of a class
62
Example - is
public void DisplayObject(object obj)
{
if (obj is int)
Console.WriteLine("The object is of type integer");
else
Console.WriteLine("It is not int");
}
63
Example - as
Using as, you can convert types without raising an exception
In casting, if the cast fails an InvalidCastException is raised
But in as no exception is raised, instead the reference will be
set to null
static void ChaseACar(Animal anAnimal)
{
Dog d = anAnimal as Dog; // Dog d = (Dog) anAnimal;
if (d != null)
d.ChaseCars();
else
Console.WriteLine("Not a Dog");
}
64
Example - typeof
Instance Level
MyClass m = new MyClass();
Console.WriteLine(m.GetType());
Output
Typeof.MyClass
Class Level
Type myType = typeof(MyClass);
Console.WriteLine(myType);
Output
Typeof.MyClass
65
Access Specifiers
public void MyMethod() { } » Accessible anywhere
private void MyMethod() { } » Accessible only from
the class where defined
protected void MyMethod() { } » Accessible from its own
class and its descendent
internal void MyMethod() { } » Accessible within the
same Assembly
void MyMethod() { } » private by default
protected internal void MyMethod() { }
» Access is limited to the current assembly or types derived from
the containing class
66
Understanding Static Methods
When a Method is marked with 'static' keyword, it
may be called directly from class level
This means, there is no need to create an instance
of the class (i.e. an object variable) and then call.
Console.WriteLine(). WriteLine is static.
If WriteLine is not declared as static then
Console c=new Console();
C.WriteLine()
At run time Main() method call be invoked without 67
68
Example of Static Methods
using System;
public class MathOperation
{
public static float mul(float x,float y)
{
return x*y;
}
public static float div(float x,float y)
{
return x/y;
}
Class MathAppln
{
public static void Main)
{
float a=MathOperation.mul(4.0f,5.0f);
float b=MathOperation.div(a,2.0f);
Console.WriteLine(“b={0}”,b);
}
Defining Static Data
Calling Called
Program Program
a, b x, y
r out ans
s.Add(a, b, out r); public void Add(int x, int y, out int ans)
74
The c#”out” keyword
It allows the caller to obtain multiple return values
from single method invocation
public static int Add(int x, int y,out int ans)
{ ans = x + y;}
static void Main(string[] args)
{ int ans; // no need to assign before use when var is used as out
Add(20,40,out ans);
Console.WriteLine(“20+40= {0}”,ans);
}
75
The c# ”ref” keyword
Reference parameters are necessary when
we wish to allow a method to operate on various
data points declared in the caller’s scope
Output parameters do not need to be initialized
before they passed to the method.
Reference parameters must be initialized before they
are passed to the method. We are passing a
reference to an existing variable. If we do not assign
it to an initialvalue, that would be the equivalent of
operating on an unassigned local variable. 76
The ref method
using System;
class Ref
{
public static void Upper(ref string s)
{
s=s.ToUpper();
}
77
The c# “params” keyword
To achieve variable number of parameters in a
Method declaration
The params parameter must be a single dimensional
array (else you get an error)
You can define any object in the parameter list
78
Example
using System;
class Params
{
public static void DispArrInts(string msg, params int[ ] list)
{
Console.WriteLine(msg);
for (int i = 0; i < list.Length; i++)
Console.WriteLine(list[i]);
}
static void Main(string[ ] args)
{
int[ ] intArray = new int[ ] {1, 2, 3};
DispArrInts("List1", intArray);
DispArrInts("List2", 4, 5, 6, 7); // you can send more elements
DispArrInts("List3", 8,9); // you can send less elements
}
}
79
Generic use of params
Instead of using only an integer list for the params parameter,
we can use an object
public class Person
{
private string name;
private byte age;
public Person(string n, byte a)
{
name = n;
age = a;
}
public void PrintPerson()
{ Console.WriteLine("{0} is {1} years old", name, age); }
}
80
pass any object
public static void DisplayObjects(params object[ ] list)
{
for (int i = 0; i < list.Length; i++)
{
if (list[i] is Person)
((Person)list[i]).PrintPerson();
Output:
else 777
Console.WriteLine(list[i]); John is 45 years old
} Instance of System.String
Console.WriteLine();
}
Calling Program:
Person p = new Person("John", 45);
DisplayObjects(777, p, "Instance of System.String"); 81
Passing Reference Types –
By Value
If a reference type is passed by value, the calling program may
change the value of the object's state data, but may not change
the object it is referencing (Refer to PassingRefTypes folder)
public static void PersonByValue(Person p)
{
// will change state of p
p.age = 60;
// will not change the state of p
p = new Person("Nikki", 90);
}
82
Passing Reference Types –
By Reference
If a class type is passed by reference, the calling program
may change the object's state data as well as the object it is
referencing
public static void PersonByRef(ref Person p)
{
// will change state of p
p.age = 60;
// p will point to a new object
p = new Person("Nikki", 90);
}
83
Calling Program
// Pass by Value
Console.WriteLine("Passing By Value...........");
Person guru = new Person("Guru", 25);
guru.PrintPerson();
Passing By Value...........
Guru is 25 years old
PersonByValue(guru);
Guru is 60 years old
guru.PrintPerson();
// Pass by Reference
Console.WriteLine("Passing By Reference........");
Person r = new Person("Guru", 25);
r.PrintPerson(); Passing By Reference........
Guru is 25 years old
PersonByRef(ref r); Nikki is 90 years old
r.PrintPerson();
84
Arrays in C#
C# arrays are derived from System.Array base class
Memory for arrays is allocated in heap
It works much same as C, C++, Java, etc.
Example
string[ ] strArray = new string[10]; // string array
int[ ] intArray = new int [10]; // integer array
int[2] Age = {34, 70}; // Error, requires new keyword
strArray[0] = "BIT"; // assign some value
int [ ] Age = new int[3] {25, 45, 30}; // array initialization
85
Example
public static int[ ] ReadArray( ) // reads the elements of the array
{
int[ ] arr = new int[5];
for (int i = 0; i < arr.Length; i++)
arr[i] = arr.Length – i ; // arr[0]=5,arr[1]=4,arr[2]=3…
return arr;
}
public static int[ ] SortArray(int[ ] a)
{
System.Array.Sort(a); // sorts an array
return a;
}
86
Calling Program
public static void Main(string[ ] args)
{
int[ ] intArray;
87
Arrays as Parameters and Return
values
static void PrintArray(int[] myInts)
{ for(int i = 0; i < myInts.Length; i++)
Console.WriteLine("Item {0} is {1}", i, myInts[i]);}
static string[] GetStringArray()
{string[ ] theStrings = { "Hello", "from", "GetStringArray" };
return theStrings;}
static void Main(string[] args)
{int[ ] ages = {20, 22, 23, 0} ;
PrintArray(ages);
string[ ] strs = GetStringArray();
foreach(string s in strs)
Console.WriteLine(s);
Console.ReadLine();} 88
Multidimensional Arrays
Rectangular Array : Array of multiple dimensions where
each row is of same length
int[ , ] myMatrix; // declare a rectangular array
int[ , ] myMatrix = new int[2, 2] { { 1, 2 }, { 3, 4 } }; // initialize
myMatrix[1,2] = 45; // access a cell
Jagged Array: Contains some no. of inner arrays, each
of which may have unique upper limit
int[ ][ ] myJaggedArr = new int[2][ ]; // 2 rows and variable columns
for (int i=0; i < myJaggedArr.Length; i++)
myJaggedArr[i] = new int[i + 7]; 89
st nd
Rectangular Arrays
static void Main(string[] args)
{int[,] myMatrix; // A rectangular MD array.
myMatrix = new int[6,6];
for(int i = 0; i < 6; i++) // Populate (6 * 6) array.
for(int j = 0; j < 6; j++)
myMatrix[i, j] = i * j;
for(int i = 0; i < 6; i++) // Print (6 * 6) array.
{ for(int j = 0; j < 6; j++)
Console.Write(myMatrix[i, j] + "\t");
Console.WriteLine();}
90
}
Rectangular Arrays
91
Jagged Array
static void Main(string[] args)
{// A jagged MD array (i.e., an array of arrays).
// Here we have an array of 5 different arrays.
int[][] myJagArray = new int[5][];
for (int i = 0; i < myJagArray.Length; i++) // Create the jagged array.
myJagArray[i] = new int[i + 7];
// Print each row (remember, each element is defaulted to zero!)
for(int i = 0; i < 5; i++)
{Console.Write("Length of row {0} is {1} :\t", i, myJagArray[i].Length);
for(int j = 0; j < myJagArray[i].Length; j++)
Console.Write(myJagArray[i][j] + " ");
Console.WriteLine();}}
92
Jagged Array
93
System.Array Base Class
BinarySearch( ) Static method - Finds a given item
Clear( ) Static method- Sets range of elements to 0/null
CopyTo( ) Copy source to Destination array
GetEnumerator( ) Returns the IEnumerator interface
GetLength( ) To determine no. of elements
Length Length is a read-only property
GetLowerBound( ) To determine lower and upper bound
GetUpperBound( )
GetValue( ) Retrieves or sets the value of an array cell, given its
SetValue( ) index
Reverse( ) Static method- Reverses the contents of one-
dimensional array
Sort( ) Sorts a one-dimensional array
String Manipulations in C#
95
Basic String Operations
static void Main(string[] args)
{ string s = "Boy, this is taking a long time.";
Console.WriteLine("--> s contains 'oy'?: {0}", s.Contains("oy"));
Console.WriteLine("--> s contains 'Boy'?: {0}", s.Contains("Boy"));
Console.WriteLine(s.Replace('.', '!'));
Console.WriteLine(s.Insert(0, "Boy O' "));
Console.ReadLine(); }
Basic String Operations
// Concatenation of strings.
string newString = s + s1 + s2;
Console.WriteLine("s + s1 + s2 = {0}", newString);
Console.WriteLine("string.Concat(s, s1, s2) = {0}",
string.Concat(s, s1, s2));
97
Escape Characters
98
More String Methods
string s3 = "Hello\tThere\tAgain";
Console.WriteLine(s3);
99
Working with C# Verbatim Strings
C# introduces the @-prefixed string literal notation termed a verbatim string.
Using verbatim strings, you disable the processing of a literal’s escape
characters. This can be most useful when working with strings representing
directory and network paths.
// The following string is printed verbatim thus, all escape characters are
displayed.
Console.WriteLine(@"C:\MyApp\bin\debug");
100
The Role of
System.Text.StringBuilder
Like Java, C# strings are immutable. This means, strings can not
be modified once established
For example, when you send ToUpper() message to a string
object, you are not modifying the underlying buffer of the existing
string object. Instead, you return a fresh copy of the buffer in
uppercase
It is not efficient, sometimes, to work on copies of strings –
solution?
Use StringBuilder from System.Text!
Note: A String is called immutable because its value cannot be modified once it has
been created. Methods that appear to modify a String actually return a new
String containing the modification. If it is necessary to modify the actual
contents of a string-like object, use the System.Text.StringBuilder class.
101
System.Text.StringBuilder
when you call ToUpper() on a string object, you are not modifying the
underlying buffer of an existing string object, but receive a new string object in
uppercase form
static void Main(string[] args)
{// Make changes to strFixed? Nope!
System.String strFixed = "This is how I began life";
Console.WriteLine(strFixed);
string upperVersion = strFixed.ToUpper();
Console.WriteLine(strFixed);
Console.WriteLine("{0}\n\n", upperVersion);
}
102
System.Text.StringBuilder
To help reduce the amount of string copying, the System.Text namespace
defines a class named StringBuilder
System.String, StringBuilder provides direct access to the underlying buffer.
Like System.String,StringBuilder provides numerous members that allow to
append, format, insert, and remove data from the object
When we create a StringBuilder object, you may specify (via a constructor
argument) the initial number of characters the object can contain. If we do not
do so, the default capacity of a StringBuilder is 16. In either case, if you add
more character data to a StringBuilder than it is able to hold, the buffer is
resized.
103
System.Text.StringBuilder
using System;
using System.Text; // StringBuilder lives here.
class StringApp
{ static void Main(string[] args)
{ StringBuilder myBuffer = new StringBuilder("My string data");
Console.WriteLine("Capacity of this StringBuilder: {0}",myBuffer.Capacity);
myBuffer.Append(" contains some numerical data: ");
myBuffer.AppendFormat("{0}, {1}.", 44, 99);
Console.WriteLine("Capacity of this StringBuilder: {0}",myBuffer.Capacity);
Console.WriteLine(myBuffer);
}}
The overhead associated with returning modified copies of character data will
be negligible. While we are building a text-intensive application (such as a word
104
processor program),we will most likely find that using System.Text.StringBuilder
Example
using System;
using System.Text;
class MainClass
{
public static void Main()
{
StringBuilder myBuffer = new StringBuilder("Buffer");
// create the buffer or string builder
myBuffer.Append( " is created");
Console.WriteLine(myBuffer);
// ToString() converts a StringBuilder to a string
string uppercase = myBuffer.ToString().ToUpper();
Console.WriteLine(uppercase);
string lowercase = myBuffer.ToString().ToLower();
Console.WriteLine(lowercase);
}
}
Enumerations in C#
Mapping symbolic names The internal type used for
to numerals enumeration is System.Int32
Example - 1 Using Enumerations
enum Colors Colors c;
{ c = Colors.Blue;
Red, // 0
Green, // 1 Console.WriteLine(c); // Blue
Blue // 2
}
Example - 2
enum Colors
{
Red = 10, // 10
Green, // 11
Blue // 12
}
106
System.Enum Base Class
Converts a value of an enumerated type to its
Format()
string equivalent
Retrieves the name for the constant in the
GetName()
enumeration
Returns the type of enumeration
GetUnderlyingType() Console.WriteLine(Enum.GetUnderlyingType(typeof
(Colors))); // System.Int32
Gives an array of values of the constants in
GetValues()
enumeration
To check whether a constant exists in enum
IsDefined()
if (Enum.IsDefined(typeof(Colors), "Blue") ….
Converts string/value to enum object
Parse() Colors CarColor =
107
(Colors)Enum.Parse(typeof(Colors), "Red");
Example
Array obj = Enum.GetValues(typeof(Colors));
foreach(Colors x in obj)
{
Console.WriteLine(x.ToString());
Console.WriteLine("int = {0}", Enum.Format(typeof(Colors), x, "D"));
}
Output
Red
int = 0
Blue
int = 1
Green
int = 2
108
Structures in C#
Structures can contain constructors (must have
arguments). We can't redefine default constructors
It can implement interfaces
Can have methods
There is no System.Structure class!
109
Example
using System;
struct STUDENT
{
public int RegNo;
public string Name;
public int Marks;
public STUDENT(int r, string n, int m)
{
RegNo = r;
Name = n;
Marks = m;
}
}
class MainClass
{
public static void Main()
{
STUDENT Giri;
Giri.RegNo = 111;
Giri.Name = "Giri";
Giri.Marks = 77;
large project
To use a namespace:
(1) System.Xml.XmlTextReader tr;
(2) using System.Xml;
XmlTextReader tr;
111
Example
Assume that you are developing a collection of graphic
classes: Square, Circle, and Hexagon
To organize these classes and share, two approaches could
be used:
// shapeslib.cs
using MyShapes;
{
public class Square { …}
public class Circle { …}
public class Hexagon { …}
}
112
Alternate Approach
// Square.cs
using System; All the three classes Square, Circle, and
namespace MyShapes Hexagon are put in the namespace
{ MyShapes
class Square { … }
using System;
}
using MyShapes;
// Circle.cs
namespace MyApplication
using System;
{
namespace MyShapes
class ShapeDemo
{
{
class Circle { … }
…..
}
Square sq = new Square();
// Hexagon.cs
Circle Ci = new Circle();
using System;
Heagone he = new Heagon();
namespace MyShapes
…….
{
}
class Hexagon { … }
}
}
defined in MyShapes namespace
Resolving Name clashes in
namespaces
using My3DShapes; The class Square is define in both
{ the namespaces (MyShapes and
public class Square { …} My3DShpaes)
public class Circle { …} To resolve this name clash, use
public class Hexagon { …}
My3DShapes. Square Sq =
}
new My3DShapes.Square();
using System;
Qualify the name of the class with the
using MyShapes;
appropriate namespace
usingMy3DShapes;
The default namespace given in VS
……..
IDE is the name of the project
// Error!
Square Sq = new Square();
…….
114
End of
Chapter 3