Unit 1
Unit 1
.NET Concepts
Books for Reference
• C# and the .NET Platform (2 Ed)
By Andrew Troelsen
Dreamtech Publications
• Microsoft Visual C# .NET
By Mickey Williams
Microsoft Press
2
Chapter - 1
3
Objectives
• Understanding the previous state of
affairs
• The .NET Solution
• Building blocks of .NET Platform
CLR, CTS, and CLS
• .NET Base Class Libraries
4
Understanding the
previous state of affairs
• As a C/Win32 API Programmer
It is complex
C is a short/abrupt language
Manual memory management, ugly pointer
arithmetic, ugly syntactic constructs
Not a OO language
• As a C++/MFC Programmer
Root is C
C++ with MFC is still complex and error-prone
• As a VB 6 Programmer
Not a complete OOP (“Object-aware”) – Why?
Doesn’t support inheritance
No multithreading
No parameterized Classes
Low-level API calls are complex
5
Previous state of affairs…
• As a Java/J2EE Programmer
Use of Java front-to-back during development
cycle
No language freedom!
Pure Java is not suitable for graphic intensive
problems (E.g. 3D game)
No cross-language integration
• As a COM Programmer
Complex creation of COM types
Active Template Library (ATL)
Forced to contend with brittle/fragile registration
entries
Deployment issues
6
.NET Solution
• Full interoperability with existing Win32 Code
Existing COM binaries can interoperate with .NET binaries
• Complete and total language integration
Supports cross-language inheritance, exception handling, and
debugging
• Common runtime engine shared by all .NET aware
languages
• A base class library
Good object model used by all .NET aware languages
• No more COM plumbing!
No IClassFactory, IUnKnown, IDispatch, etc.
• Truly simplified deployment model
No need to register a binary unit into the system registry
Allows multiple versions of same *.dll
7
.NET Framework
VB C++ C# JScript J#
Visual Studio.NET
ASP.NET Windows
Web Forms Web Services Forms
Operating System
8
Building Blocks of .NET
• CLR (Common Language Runtime)
To locate, load, and manage .NET types
Automatic memory management, language
integration, and type safety
• CTS (Common Type System)
Describes all possible data types and
programming constructs supported by the
runtime
• CLS (Common Language Specification)
A set of rules that defines a subset of types and
specifications
9
CLR (Common Language Runtime)
• CLR sits on top of OS (same as JVM of Java)
• CLR loads modules containing executables and executes
them
• Code may be managed or unmanaged
• Managed code consists of instructions in pseudo random
code called CIL (Common Intermediate Language). CIL
instructions are JIT compiled into native machine code at
runtime
• JIT compiled methods reside in cache until the application’s
life time
• Advantages of managed code: type safety, memory
management, and code verification security
• CLR can translate code from C#, J#, C, C++, VB, and
Jscript into CIL.
• CLR doesn’t launch a new process for every application. It
launches one process and hosts individual applications in
application domains
10
Base Class Libraries
• Encapsulates various primitives like: threads, file
IO, graphical rendering, and other interaction with
HW devices
• It also provides: database manipulation, XML
integration, Web-enabled front-end.
CTS CLS
S. Nandagopalan, B I T 11
C#
• Almost same as Java
• No pointers required
• Automatic memory management (No ‘delete’)
• Enumeration, class, structure, etc.
• Operator overloading allowed
• Interface-based programming techniques
• Assign characteristics to types (same as COM
IDL)
• C# can produce code that can run only on .NET
environment (unlike COM server or Win32 API)
S. Nandagopalan, B I T 12
Understanding Assemblies
• Windows applications have dependencies
on one or more DLLs
• These DLLs may contain COM classes
registered in System registry
• When these components are updated,
applications may break – 'DLL hell'
• Solution: .NET Assemblies
• C# .NET compiler doesn't generate
machine code.
• It is compiled into "assembly"
S. Nandagopalan, B I T 13
Assembly
Metadata
IL
C# source code + C# .NET Compiler =
Assembly
• Intermediate Language (IL/CIL):
Same as first pass of compiler. It can't be executed
(it is not in binary format)
• Metadata
Describes the assembly contents
No need for component registry
Each assembly includes information about references
to other assemblies
E.g. If you have a class called Car in a given
assembly, the type metadata describes Car's base
class, which interfaces are implemented by Car,
description of members of Car.
S. Nandagopalan, B I T 14
Assembly…
• When CLR loads your application, it examines your
program's metadata to know which external
assemblies are required for execution
• Private assemblies
Used by single application
Is not shared
Most preferred method
• Shared assemblies
Intended for multiple applications
Global Assembly Cache
• Manifest
The metadata of assemblies: version, list of
externally defined assemblies, etc.
S. Nandagopalan, B I T 15
Example of CIL
• CIL sits above a specific compiler public class Calc
(C#, J#, etc.) {
• The associated compiler emits CIL public int Add(int x, int y)
instructions { return x + y; }
using System; }
namespace Calculator }
{
S. Nandagopalan, B I T 16
CIL of Add() Method
.method public hidebysig instance int32 Add(int32 x,
int32 y) cil managed
{
// Code size 8 (0x8)
.maxstack 2
.locals init ([0] int32 CS$00000003$00000000)
IL_0000: ldarg.1
IL_0001: ldarg.2
IL_0002: add
IL_0003: stloc.0
IL_0004: br.s IL_0006
IL_0006: ldloc.0
IL_0007: ret
} // end of method Calc::Add
S. Nandagopalan, B I T 17
External
Manifest Assembly
S. Nandagopalan, B I T 18
CIL to Execution
Desktop
Pocket PC
S. Nandagopalan, B I T 19
Common Type System (CTS)
• CTS is a formal specification that
describes how a given type must be
defined for CLR
• CTS Class Type
• CTS Structure Type
• CTS Interface Type
• CTS Enumeration type
• CTS Delegate type
S. Nandagopalan, B I T 20
CTS Class Type
• Same as C++ class
• Can contain members: methods,
properties, events, etc.
• Support for abstract members that
define a polymorphic interface for
derived classes
• Multiple inheritance is not allowed
S. Nandagopalan, B I T 21
CTS Class Characteristics
• "sealed"? – sealed classes can't function
as base classes
• Implement any interfaces? – An
interface is a collection of abstract
members
• Abstract or Concrete? – Abstract classes
(to define common behaviors for derived)
can't be created directly but concrete
classes can.
• Visibility? – visibility attribute to know
whether external assemblies can use it.
S. Nandagopalan, B I T 22
• CTS Structure types
Same as C/C++
Derived from a common base class
System.ValueType
• CTS Interface Type
Same as pure abstract class of C++
A description of work that a derived class can
perform
Similar to a class, but can never be instantiated
• CTS Enumeration type
To group name/value pairs under a specific name
Default Storage: System.Int32 (could be
changed)
• CTS Delegate type
Same as C's function pointer (System.MulticastDelegate)
Useful for event handling (ASP .NET)
Intrinsic CTS Data Types
.NET Base Type C# Type
System.Byte Byte
System.SByte sbyte
System.Int16 short
System.Int32 int
System.Int64 long
System.UInt64 ulong
System.Single float
System.Double double
System.Object object
System.String string
System.Boolean bool
S. Nandagopalan, B I T 24
Common Language Specification
(CLS)
• Set of guidelines that describe the minimal
and complete set of features a given .NET
aware compiler must support
• C# uses + for concatenation whereas
VB .NET uses &
• C# allows operator overloading but
VB .NET does not!
• The void functions may differ in syntax:
' VB .NET // C#
Public Sub Foo() public void Foo()
'……. { ……. }
End Sub
S. Nandagopalan, B I T 25
CLS Compliance
C# Type CLS Compliance
byte Yes
sbyte No
short Yes
int Yes
long Yes
ulong No
float Yes
double Yes
object Yes
string Yes
char Yes
bool S. Nandagopalan,
YesB I T 26
Example
public class Calc
{
// CLS compliant
public int Add(int x, int y)
{ return x + y; }
S. Nandagopalan, B I T 27
CLR .NET .NET Compiler
Source
Code
DLL or EXE
(CIL)
mscoree.dll
Class Loader
Base Class
Libraries Jitter
(mscorlib.dll)
Platform
Specific code
mscoree.dll
Execute
MicroSoft Common
Object Runtime Execution Engine .NET Execution Engine
.NET Namespace
• MFC, Java, VB 6.0 have predefined
set of classes; C# doesn't
• C# uses namespace concept
• Any language targeting the .NET
runtime makes use of the same
namespaces and same types as C#
• System is the root namespace
S. Nandagopalan, B I T 29
Example in C# System Namespace
using System;
public Class MyApp
{
public static void Main() Console class in
System Namespace
{
Console.WriteLine("Hello World");
}
}
S. Nandagopalan, B I T 30
Example in VB .NET
Imports System
Public Module MyApp
Sub Main()
Console.WriteLine("Hello World")
End Sub
End Module
S. Nandagopalan, B I T 31
Example in Managed C++
#using <mscorlib.dll>
using namespace System;
void Main()
{
Console::WriteLine("Hello World");
}
S. Nandagopalan, B I T 32
Sample .NET namespaces
System primitive types, garbage
collection, etc
System.Collections Container objects: ArrayList,
Queue, etc.
System.Data For Database manipulations
System.Data.Common ADO .NET
System.Data.OleDb
System.Data.SqlClient
System.IO file IO, buffering, etc.
System.Drawing GDI+ primitives, bitmaps, fonts,
System.Drawing.2D icons, etc.
System.Threading Threads
S. Nandagopalan, B I T 33
Demo
• Console Application
• Windows Application
• Graphics
S. Nandagopalan, B I T 34
End of Chapter 1
S. Nandagopalan, B I T 35
Chapter 3
C# Language Fundamentals
36
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
37
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;
}
}
38
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)
{
{ // ………….
// ………. }
} }
}
39
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;
}
}
40
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
41
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
}
}
Local members/variables must be explicitly initialized
public static void Main (string [ ] args)
{
int x;
Console.WriteLine(x); // Error
}
43
BASIC INPUT & OUTPUT
System.Console Class
Write(), WriteLine(), Read(), and ReadLine()
Example (Read and Write a string):
// RW.cs
using System;
class BasicRW
{
public static void Main (string [ ] args)
{
string s;
Console.Write("Enter a string: ");
s = Console.ReadLine();
Console.WriteLine("String: {0}", s);
}
}
44
Basic IO…
// IO.cs
using System;
class BasicIO
{
public static void Main(string[ ] args)
{
int theInt = 20;
float theFloat = 20.2F; // double theFloat = 20.2; is OK
string theStr = "BIT";
Console.WriteLine("Int: {0}", theInt);
Console.WriteLine("Float: {0}", theFloat);
Console.WriteLine("String: {0}", theStr);
// array of objects
object[ ] obj = {"BIT", 20, 20.2};
Console.WriteLine("String: {0}\n Int: {1}\n Float: {2}\n", obj);
}
}
.NET String Formatting
1. C or c Currency ($) Example
2. D or d Decimal // Format.cs
using System;
3. E or e Exponential class Format
4. F or fFixed point {
5. G or g General public static void Main (string [ ] args)
6. N or n Numerical {
7. X or x Hexadecimal Console.WriteLine("C Format: {0:c}", 9999);
Console.WriteLine("D Format: {0:d}", 9999);
Console.WriteLine("E Format: {0:e}", 9999);
Console.WriteLine("F Format: {0:f}", 9999);
C Format: $9,999.00 Console.WriteLine("G Format: {0:g}", 9999);
D Format: 9999 Console.WriteLine("N Format: {0:n}", 9999);
Console.WriteLine("X Format: {0:x}", 9999);
E Format: 9.999000e+003
}
F Format: 9999.00 }
G Format: 9999
N Format: 9,999.00
X Format: 270f
46
Value and Reference Types
.NET types may be value type or reference type
Primitive types are always value types including
structures
These types are allocated on the stack. Outside the
scope, these variables will be popped out.
However, classes are not value type but reference
based
47
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
}
48
Example - 2
struct Foo
{
public int x, y;
}
50
Value Types containing
Reference Types
When a value type contains other reference type,
assignment results only "reference copy"
You have two independent structures, each one
pointing to the same object in memory – "shallow
copy"
For a more deeper copy, we must use ICloneable
interface
Example: ValRef.cs
51
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
53
Example
namespace System
{
public class Object
{ can be overridden
public Object(); by derived class
55
Create System.Object Methods
// ObjTest.cs ToString: ObjTest
using System;
class ObjTest
GetHashCode: 1
{ GetType: System.Object
public static void Main (string [ ] args) Same Instance
{
ObjTest c1 = new ObjTest();
59
Examples
Char
char.IsDigit('K')
char.IsLetter('a') or char.IsLetter("100", 1)
char.IsWhiteSpace("Hi BIT", 2)
char.IsPunctuation(',')
60
Boxing and UnBoxing
Boxing
Explicitly converting a value type into a corresponding
reference type
Example:
int Age = 42;
object objAge = Age;
No need for any wrapper class like Java
C# automatically boxes variables whenever needed. For
example, when a value type is passed to a method
requiring an object, then boxing is done automatically.
61
UnBoxing
Converting the value in an object reference (held in
heap) into the corresponding value type (stack)
Example:
object objAge;
int Age = (int) objAge; // OK
string str = (string) objAge; // Wrong!
The type contained in the box is int and not
string!
62
C# Iteration Constructs
for loop
foreach-in loop
while loop
do-while loop
63
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
64
The foreach/in Loop
using System;
class ForEach
{
public static void Main(string[] args)
{
string[ ] Names = new string [ ] {"Arvind ", "Geetha ",
"Madhu ", "Priya "};
}
}
65
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);
}
}
}
66
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!
{ …. }
67
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;
} }
68
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;
}
69
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
70
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");
}
71
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");
}
72
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
73
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
74
Static Methods
What does 'static' method mean?
Methods marked as 'static' may be called from class
level
This means, there is no need to create an instance
of the class (i.e. an object variable) and then call.
This is similar to Console.WriteLine()
public static void Main() – why static?
At run time Main() call be invoked without any object
variable of the enclosing class
75
Example
public class MyClass
{
public static void MyMethod()
{…}
}
public class StaticMethod
{ If MyMethod() is not declared
public static void Main(string[ ] args) as static, then
{ MyClass obj = new MyClass();
MyClass.MyMethod(); obj.MyMethod();
}
}
76
Stack Class (StaticMethod folder)
using System;
public class Stack
{
public static void Push(string s)
{
items[++top] = s;
}
public static string Pop()
{
return (items[top--]);
}
public static void Show()
{
for (int i = top; i >= 0; i--)
Console.WriteLine(items[i]);
}
private static string[ ] items = new string[5];
private static int top = -1;
}
Stack Class….
class StaticMethod
{
public static void Main(string[] args)
{
Console.WriteLine("Stack Contents:");
Stack.Push("BIT");
Stack.Push("GAT");
Stack.Show();
Console.WriteLine("Item Popped=> " + Stack.Pop());
Console.WriteLine("Stack Contents:");
Stack.Show();
}
}
Parameter Passing Methods
Default » Value parameter
out » Output parameter (called member)
ref » Same as pass-by-reference
params » Variable number of parameters
within a single parameter
79
Parameter Passing
One advantage of out parameter type is that we can return
more than one value from the called program to the caller
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)
80
The ref method
using System;
class Ref
{
public static void Swap(ref int x, ref int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
82
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
}
}
83
Generic use of params
Instead of using only an integer list for the params parameter,
we can use an object (Refer to ParamsMethod folder)
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); }
}
84
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();
else Output:
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"); 85
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);
}
86
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);
}
87
Calling Program
// Pass by Value
Console.WriteLine("Passing By Value...........");
Person geetha = new Person("Geetha", 25);
geetha.PrintPerson();
Passing By Value...........
PersonByValue(geetha); Geetha is 25 years old
geetha.PrintPerson(); Geetha is 60 years old
// Pass by Reference
Console.WriteLine("Passing By Reference........");
Person r = new Person("Geetha", 25);
r.PrintPerson();
Passing By Reference........
Geetha is 25 years old
PersonByRef(ref r);
Nikki is 90 years old
r.PrintPerson();
88
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
Person[ ] Staff = new Person[2]; // object array
strAarray[0] = "BIT"; // assign some value
int [ ] Age = new int[3] {25, 45, 30}; // array initialization
89
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;
return arr;
}
public static int[ ] SortArray(int[ ] a)
{
System.Array.Sort(a); // sorts an array
return a;
}
90
Multidimensional Arrays
Rectangular Array
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
int[ ][ ] myJaggedArr = new int[2][ ]; // 2 rows and variable columns
for (int i=0; i < myJaggedArr.Length; i++)
myJaggedArr[i] = new int[i + 7];
Note that, 1st row will have 7 columns and 2nd row will
have 8 columns 91
System.Array Base Class
BinarySearch( ) Finds a given item
Clear( ) 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( ) Reverses the contents of one-dimensional array
Sort( ) Sorts a one-dimensional array
Calling Program
public static void Main(string[ ] args)
{
int[ ] intArray;
93
String Manipulations in C#
94
Strings…
For string comparisons, use
Compare, CompareOrdinal, CompareTo(), Equals, EndsWith, and
StartsWith
To obtain the index of the substring or unicode, use
Use IndexOf, IndexOfAny, LastIndexOf, and LastIndexOfAny
To copy a string a substring, use
Copy and CopyTo
To create one or more strings, use
Substring and Split
To change the case, use
ToLower and ToUpper
To modify all or part of the string, use
Insert, Replace, Remove, PadLeft, PadRight, Trim, TrimEnd, and
TrimStart
Meaning of String Methods
String s1 = "a"; Console.WriteLine("Compare");
String s2 = "A"; if (y == 0)
Console.WriteLine("a = A");
int x = String.CompareOrdinal(s1, s2); else if (y > 0)
int y = String.Compare(s1, s2); Console.WriteLine("a > A");
else
Console.WriteLine("Ordinal"); Console.WriteLine("a < A");
if (x == 0)
Console.WriteLine("a = A"); Ouput:
else if (x > 0) Ordinal
Console.WriteLine("a > A"); a>A
else Compare
Console.WriteLine("a < A"); a<A
96
More String Methods
CompareTo() – int x = s1.CompareTo(s2); and returns
an int
Remove() – Deletes a specified number of characters
from this instance beginning at a specified position.
public string Remove (int startIndex, int count );
Insert() - Inserts a specified instance of String at a
specified index position in this instance.
public string Insert (int startIndex, string value );
ToLower() - Returns a copy of this String in lowercase
Example: s = s.ToUpper();
97
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.
98
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
}
100
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
103
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 Geetha;
Geetha.RegNo = 111;
Geetha.Name = "Geetha";
Geetha.Marks = 77;
105
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 { …}
}
106
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;
// Circle.cs using MyShapes;
using System; namespace MyApplication
namespace MyShapes {
{ class ShapeDemo
class Circle { … } {
} …..
// Heagon.cs Square sq = new Square();
using System; Circle Ci = new Circle();
namespace MyShapes Heagone he = new Heagon();
{ …….
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();
…….
108
End of
Chapter 3