2. 2
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
3. 3
Basic C# Class
// Hello.cs
using System;
class HelloClass
{
public static int Main(string[ ] args)
{
Console.WriteLine("Hello World");
return 0;
}
}
The using keyword has two major uses:
using Directive Creates an alias for a namespace
or imports types defined in other namespaces.
using Statement Defines a scope at the end of
which an object will be disposed.
4. 4
Basic C# Class - Variations
// Hello1.cs
using System;
class HelloClass
{
public static void Main(string[ ] args)
{
// ……….
}
}
// Hello2.cs
using System;
class HelloClass
{
public static void Main()
{
// ………….
}
}
5. 5
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;
}
}
6. 6
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
7. EXAMPLE (Point.cs)
class Point
{
public Point()
{ Console.WriteLine("Default Constructor"); }
public Point(int px, int py)
{ x = px; y = py; }
public int x;
public int y;
}
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);
}
}
Program
Entry Point
8. 8
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);
}
}
9. 9
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
}
10. 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);
}
}
11. 11
.NET String Formatting
1. C or c Currency ($)
2. D or d Decimal
3. E or e Exponential
4. F or f Fixed point
5. G or g General
6. N or n Numerical
7. X or x Hexadecimal
Example
// Format.cs
using System;
class Format
{
public static void Main (string [ ] args)
{
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);
Console.WriteLine("G Format: {0:g}", 9999);
Console.WriteLine("N Format: {0:n}", 9999);
Console.WriteLine("X Format: {0:x}", 9999);
}
}
C Format: $9,999.00
D Format: 9999
E Format: 9.999000e+003
F Format: 9999.00
G Format: 9999
N Format: 9,999.00
X Format: 270f
12. 12
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
13. 13
Reference Type
These types are allocated in a managed Heap
Objects of these types are indirectly referenced
Garbage collection is handled by .NET
Reference Variables
Shape rect = new Shape();
Shape Temprect = rect;
Objects
Shape
Shape
Shape Newrect = new Shape();
14. 14
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
15. 15
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
}
16. 16
Example - 2
struct Foo
{
public int x, y;
}
public void SomeMethod()
{
Foo f1 = new Foo();
// assign values to x and y
Foo f2 = f1;
// Modifying values of f2 members will not change f1 members
….
}
17. 17
Class Types
Class types are always reference types
These are allocated on the garbage-collected heap
Assignment of reference types will reference the same object
Example:
class Foo
{
public int x, y;
}
Now the statement Foo f2 = f1; has a reference to the object
f1 and any changes made for f2 will change f1
18. 18
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
19. Example
// ValRef.cs
// This is a Reference type – because it is a class
class TheRefType
{
public string x;
public TheRefType(string s)
{ x = s; }
}
// This a Value type – because it is a structure type
struct InnerRef
{
public TheRefType refType; // ref type
public int structData; // value type
public InnerRef(string s)
{
refType = new TheRefType(s);
structData = 9;
}
}
InnerRef valWithRef = new
InnerRef("Initial Value");
valWithRef.structData = 666;
valWithRef
structData = 666
refType x =
"Initial Value"
valWithRef2
structData = 777
refType
InnerRef valWithRef2 = valWithRef;
valWithRef2.refType.x = "I am NEW";
valWithRef2.structData = 777
x =
"I am NEW"
20. 20
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);
}
21. 21
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);
}
22. 22
System.Object
Every C# data type is derived from the base class
called System.Object
class HelloClass
{ .... } is same as
class HelloClass : System.Object
{ ....}
23. 23
Example
namespace System
{
public class Object
{
public Object();
public virtual Boolean Equals(Object(obj);
public virtual Int32 GetHashCode();
public Type GetType();
………………………………..
}
}
can be overridden
by derived class
24. 24
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
Finalize() For object removal (garbage collection)
MemberwiseClone() Returns a new object which is member-wise copy
the current object
25. 25
Create System.Object Methods
// ObjTest.cs
using System;
class ObjTest
{
public static void Main (string [ ] args)
{
ObjTest c1 = new ObjTest();
Console.WriteLine("ToString: {0}", c1.ToString());
Console.WriteLine("GetHashCode: {0}", c1.GetHashCode());
Console.WriteLine("GetType: {0}", c1.GetType().BaseType);
// create second object
ObjTest c2 = c1;
object o = c2;
if (o.Equals(c1) && c2.Equals(o))
Console.WriteLine("Same Instance");
}
}
ToString: ObjTest
GetHashCode: 1
GetType: System.Object
Same Instance
26. 26
Overriding System.Object Methods
We can redefine the behavior of virtual methods by overiding
Example ToString(), Equals(), etc.
class Person
{
public Person(string fname, string lname, string ssn, byte a)
{
firstName = fname;
lastName = lname;
SSN = ssn;
age = a;
}
public Person() { }
public string firstName, lastName, SSN;
public byte age;
}
27. 27
Overriding ToString()
To format the string returned by System.Object.ToString()
using System.Text;
class Person
{
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("[FName = {0}", this.firstName);
sb.AppendFormat("LName = {0}", this.lastName);
sb.AppendFormat("SSN = {0}", this.SSN);
sb.AppendFormat("Age = {0}]", this.age);
return sb.ToString();
}
…
}
28. 28
Overriding Equals()
Equals() returns true if and only if the two objects
being compared reference the same object in
memory
We can override this behavior and design when two
objects have the same value (value-based). That is,
when name, SSN, age of two objects are equal, then
return true else return false.
29. 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;
}
…
}
Example
30. 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(); }
31. C# Data Types
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
32. 32
Hierarchy of System Types
Object
Type
MulticastDelegate
Delegate
Exception
Array
String ValueType
(derived one
is
struct type
and not
class)
Boolean
Byte
Char
Decimal
Double
Int16
Int32
Int64
SByte
UInt16
UInt32
UInt64
Void
DateTime
Guid
TimeSpan
Single
Enumerations and Structures
35. 35
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.
36. 36
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!
38. 38
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
39. 39
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);
}
}
40. 40
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);
}
}
}
41. 41
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!
{ …. }
42. 42
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)
{
// Error – no break
case "India":
case "USA":
default:
}
switch(country)
{ // Correct
case "India": HiIndia();
break;
case "USA": HiUSA();
break;
default: break;
}
43. 43
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;
}
44. 44
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
45. 45
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");
}
46. 46
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");
}
47. 47
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
48. 48
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
49. 49
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
50. 50
Example
public class MyClass
{
public static void MyMethod()
{ … }
}
public class StaticMethod
{
public static void Main(string[ ] args)
{
MyClass.MyMethod();
}
}
If MyMethod() is not declared
as static, then
MyClass obj = new MyClass();
obj.MyMethod();
51. 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;
}
53. 53
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
54. 54
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
Program
a, b
r
Called
Program
x, y
ans
out
public void Add(int x, int y, out int ans)
s.Add(a, b, out r);
55. 55
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;
}
static void Main(string[ ] args)
{
int a = 10; int b = 20;
Console.WriteLine("Before Swap => {0} t {1}", a, b);
Ref.Swap(ref a, ref b);
Console.WriteLine("After Swap => {0} t {1}", a, b);
}
}
56. 56
The params method
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
57. 57
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
}
}
58. 58
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); }
}
59. 59
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
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
Calling Program:
Person p = new Person("John", 45);
DisplayObjects(777, p, "Instance of System.String");
Output:
777
John is 45 years old
Instance of System.String
60. 60
Calling Program
// Pass by Value
Console.WriteLine("Passing By Value...........");
Person geetha = new Person("Geetha", 25);
geetha.PrintPerson();
PersonByValue(geetha);
geetha.PrintPerson();
// Pass by Reference
Console.WriteLine("Passing By Reference........");
Person r = new Person("Geetha", 25);
r.PrintPerson();
PersonByRef(ref r);
r.PrintPerson();
Passing By Value...........
Geetha is 25 years old
Geetha is 60 years old
Passing By Reference........
Geetha is 25 years old
Nikki is 90 years old
61. 61
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
62. 62
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;
}
63. 63
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
64. 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( )
Length
To determine no. of elements
Length is a read-only property
GetLowerBound( )
GetUpperBound( )
To determine lower and upper bound
GetValue( )
SetValue( )
Retrieves or sets the value of an array cell, given its
index
Reverse( ) Reverses the contents of one-dimensional array
Sort( ) Sorts a one-dimensional array
65. 65
Calling Program
public static void Main(string[ ] args)
{
int[ ] intArray;
intArray = ReadArray( ); // read the array elements
Console.WriteLine("Array before sorting");
for (int i = 0; i < intArray.Length; i++)
Console.WriteLine(intArray[i]);
intArray = SortArray(intArray); // sort the elements
Console.WriteLine("Array after sorting");
for (int i = 0; i < intArray.Length; i++)
Console.WriteLine(intArray[i]);
}
66. 66
String Manipulations in C#
A string is a sequential collection of Unicode characters, typically used to
represent text, while a String is a sequential collection of System.Char
objects that represents a string.
If it is necessary to modify the actual contents of a string-like object, use the
System.Text.StringBuilder class.
Members of String perform either an ordinal or linguistic operation on a
String.
ordinal: acts on the numeric value of each Char object.
linguistic: acts on the value of the String taking into account culture-specific casing,
sorting, formatting, and parsing rules.
Sort rules determine the alphabetic order of Unicode characters and how
two strings compare to each other.
For example, the Compare method performs a linguistic comparison while the
CompareOrdinal method performs an ordinal comparison.
Consequently, if the current culture is U.S. English, the Compare method
considers 'a' less than 'A' while the CompareOrdinal method considers 'a' greater
than 'A'.
67. 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
68. 68
Meaning of String Methods
String s1 = "a";
String s2 = "A";
int x = String.CompareOrdinal(s1, s2);
int y = String.Compare(s1, s2);
Console.WriteLine("Ordinal");
if (x == 0)
Console.WriteLine("a = A");
else if (x > 0)
Console.WriteLine("a > A");
else
Console.WriteLine("a < A");
Console.WriteLine("Compare");
if (y == 0)
Console.WriteLine("a = A");
else if (y > 0)
Console.WriteLine("a > A");
else
Console.WriteLine("a < A");
Ouput:
Ordinal
a > A
Compare
a < A
69. 69
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();
70. 70
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.
71. 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);
}
}
72. 72
Enumerations in C#
Mapping symbolic names
to numerals
Example - 1
enum Colors
{
Red, // 0
Green, // 1
Blue // 2
}
Example - 2
enum Colors
{
Red = 10, // 10
Green, // 11
Blue // 12
}
The internal type used for
enumeration is System.Int32
Using Enumerations
Colors c;
c = Colors.Blue;
Console.WriteLine(c); // Blue
73. 73
System.Enum Base Class
Format()
Converts a value of an enumerated type to its
string equivalent
GetName()
Retrieves the name for the constant in the
enumeration
GetUnderlyingType()
Returns the type of enumeration
Console.WriteLine(Enum.GetUnderlyingType(typeof
(Colors))); // System.Int32
GetValues()
Gives an array of values of the constants in
enumeration
IsDefined()
To check whether a constant exists in enum
if (Enum.IsDefined(typeof(Colors), "Blue") ….
Parse()
Converts string/value to enum object
Colors CarColor = (Colors)Enum.Parse(typeof(Colors),
"Red");
74. 74
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
75. 75
Structures in C#
Structures can contain constructors (must have
arguments). We can't redefine default constructors
It can implement interfaces
Can have methods – in fact, many!
There is no System.Structure class!
76. 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;
STUDENT SomeOne = new STUDENT(222,"Raghu",90);
}
}
77. 77
Designing Custom Namespaces
System is the .NET's existing
namespace
Using the keyword namespace, we can
define our own namespace
Putting all classes in a single
namespaces may not be a good
practice
Typical namespace organization for a
large project
To use a namespace:
(1) System.Xml.XmlTextReader
tr;
(2) using System.Xml;
XmlTextReader tr;
CompanyName
Server UserInterface
Session IO Desktop WebUI
78. 78
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 { …}
}
79. Alternate Approach
// Square.cs
using System;
namespace MyShapes
{
class Square { … }
}
// Circle.cs
using System;
namespace MyShapes
{
class Circle { … }
}
// Heagon.cs
using System;
namespace MyShapes
{
class Hexagon { … }
}
All the three classes Square, Circle, and
Hexagon are put in the namespace
MyShapes
using System;
using MyShapes;
namespace MyApplication
{
class ShapeDemo
{
…..
Square sq = new Square();
Circle Ci = new Circle();
Heagone he = new Heagon();
…….
}
}
defined in MyShapes namespace
80. 80
Resolving Name clashes in
namespaces
using My3DShapes;
{
public class Square { …}
public class Circle { …}
public class Hexagon { …}
}
using System;
using MyShapes;
usingMy3DShapes;
……..
// Error!
Square Sq = new Square();
…….
The class Square is define in both
the namespaces (MyShapes and
My3DShpaes)
To resolve this name clash, use
My3DShapes. Square Sq =
new
My3DShapes.Square();
Qualify the name of the class with the
appropriate namespace
The default namespace given in VS
IDE is the name of the project
82. 82
Objectives
Basic Class in C#
Visibility
Encapsulation
Accessor (get) and Mutator (set)
Named Property
Inheritance
Sealed classes
Polymorphism
Abstract Class and Method
83. 83
C# Classes
A Class is a custom User Defined Type (UDT)
A Class consists of data (attributes) and functions
(methods)
Example: To model a generic Employee, we can
define an Employee Class
85. 85
Source Code
using System;
namespace Employee
{
public class Employee
{
// private data
private string fullName;
private int empID;
private float currPay;
// Default ctor.
public Employee(){ }
// Custom ctor
public Employee(string fullName, int empID, float currPay)
{
// Assign internal state data. Note use of 'this' keyword
this.fullName = fullName;
this.empID = empID;
this.currPay = currPay;
}
86. 86
Source Code (Contd…)
// Bump the pay for this emp.
public void GiveBonus(float amount)
{currPay += amount;}
// Show the state
public void DisplayStats()
{
Console.WriteLine("Name: {0}", fullName);
Console.WriteLine("Pay: {0}", currPay);
Console.WriteLine("ID: {0}", empID);
}
public static void Main(string[ ] args)
{
Employee e = new Employee("Joe",111,23987.50F);
e.GiveBonus(200);
e.DisplayStats();
}
}
}
87. 87
Method Overloading and 'this'
Overloading of Methods is same as C++. Constructors can be
overloaded.
For method resolution, return type alone is not necessary!
Is the keyword 'this' always necessary?
Yes, if the parameter name and the class member name are
same. Otherwise No!
Static member functions can't use 'this' keyword. Why?
The keyword 'this' can also be used to force one constructor to
call another during the object creation
Ex: public Employee(string fullName) : this(fullName, GetEmpId(),
currPay) { }
88. 88
Basic OOP Concepts
Encapsulation
Hiding unnecessary implementation details
Inheritance
"is-a" and "has-a" relationship
"is-a" means sub-classes or derived classes
"has-a" means containment or delegation
Polymorphism
It is the ability of the language to treat related objects the
same way
When sub-classes override the behavior defined by base a
class, they are essentially redefining how they respond to the
same message
89. 89
Examples
Encapsulation
DBReader f = new DBReader(); // details are hidden
f.Open("@C:foo.mdf");
// process the database file
f.Close();
Inheritance
Polymorphism
is-a Relationship
Object
Shape
Hexagon
has-a Relationship
Car
Radio
Shape
void Draw( )
Hexagon Circle
Draw() Draw()
90. 90
More Details: (1) Encapsulation
The main objective of encapsulation is: the object's
instance should be allowed to access the internal
member data directly. It also provides the integrity of
state data. How to do this?
Using private, public, protected, and protected internal
keywords
To manipulate the private data, C# provides two
methods:
Define traditional accessor and mutator methods
Define a named property
91. 91
Example
Accessor
class Employee
{
private string fullName;
public string GetName() { return fullName; }
…………..
}
Mutator
class Employee
{
private string fullName;
public string SetName(string n)
{ fullName = n; }
…………….
}
92. 92
Class Properties
You can define a named property to avoid using two
different get and set methods
The property is a single named field which wraps the
private data. These property names can then be used
in Main( ).
Ex: Assume EmpID is the name of the property
public static void Main()
{
Employee e = new Employee();
p.EmpID = 111; // set
Console.WriteLine(e.EmpID); // get
}
93. 93
C# get and set Methods
using System;
namespace get_set
{
class MyClass
{
private int a;
public int A // property
{
get // accessor
{
return a;
}
set // mutator
{
a = value;
}
}
}
class Class1
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.A = 20;
Console.WriteLine(obj.A);
}
}
}
get block – accessor
set block – mutator
A – named property
94. 94
Read-Only and Write-Only Properties
The named property A in the previous slide was able to read
and write. How to restrict the access of A as R/W?
For Read-Only: simply define a property without a set block
For write-only: simply define a property without a get block
Ex: public float Pay public float Pay
{ {
get { return currPay; } set { currPay =
value; }
} }
95. 95
static: properties and constructors
The static keyword can be used for properties also
The only difference is that, now these properties are
bound to a class and not to an instance
Ex: Employee.EmpID = 111;
Can a constructor be declared as static?
Yes, but it is strange! Why? Because, constructors are
executed during object creation
Static constructors are used to initialize static data
96. 96
Example – static property
public class Employee
{
private static string companyName;
public static string Company
{
get { return companyName; }
set {companyName = value; }
}
}
public static void Main(string[ ] args)
{
Employee.Company = "Microsoft";
Console.WriteLine("The name is {0}", Employee. Company);
}
97. 97
Example – static constructor
public class Employee
{
private static string companyName;
static Employee()
{ companyName = "Microsoft"; }
}
public static void Main(string[ ] args)
{
// below statement is not needed
// Employee.Company = "Microsoft";
Console.WriteLine("The name is {0}",
Employee.Company);
}
98. 98
Read-Only Fields
Read-Only properties provide data preservation: keyword to be used is:
"readonly"
Ex: public readonly int rofield;
You can't assign any value to the readonly fields, except in a constructor
Ex: void SomeMethod() { rofield =
123; } // Error
Static readonly fields can also be used. It is useful to associate many
constant values bound to a class.
It may be look similar to 'const' declaration. The difference, however, is that
const is resolved at compile-time and static readonly is resolved at run-time.
The other context in which it is valid to pass a readonly field as an out or
ref parameter.
99. 99
More Details: (2) Inheritance
Inheritance facilitates code reuse
Inheritance provides dependency between types
Inheritance comes in two flavors:
"is-a" relationship
"has-a" relationship
Let us start with "is-a" relationship……
Employee
Manager
SalesPerson
100. 100
Manager – Derived Class
using System;
namespace Employee
{
public class Manager : Employee
{
private ulong numberOfOptions;
public ulong NumberOpts
{
get { return numberOfOptions; }
set { numberOfOptions = value; }
}
}
}
101. 101
SalesPerson – Derived Class
using System;
namespace Employee
{
public class SalesPerson : Employee
{
private int numerOfSales;
public int NumbSales
{
get { return numerOfSales; }
set { numerOfSales = value; }
}
}
}
102. 102
Base class and Subclass Constructors
A subclass constructor automatically calls the base
class constructor, by default
Example:
public Manager(string fullName, int empID, float currPay, ulong
numberOfOpts)
: base (fullName, empID, currPay)
{ numberOfOptions = numberOfOpts; }
Refer to: Inheritance project folder for the complete
source code
103. 103
More features of "is-a"
Multiple Inheritance
In C#, a given class can have exactly one direct base class
It is not permitted to have a single type with one or more
base classes
"protected " Keyword
You know that a private member can't be accessed by even
subclasses
"protected " data or methods can be accessed by
subclasses
Sealed Classes
If you want to design a class that can't be inherited, then
use the keyword: "sealed "
A sealed class cannot also be an abstract class. It also
enables certain run-time optimizations
104. 104
Example – Sealed Classes
Add a subclass PTSalesPerson for SalesPerson class
to have part – time sales people.
Since we can't think of more child classes under
PTSalesPerson, we shall seal it
Sealed classes are most useful for designing
standalone classes. Ex: String class in the System
namespace
Example
public sealed PTSalesPerson : SalesPerson
{ ………. }
Employee
Manager
SalesPerson PTSalesPerson
105. 105
Containment/Delegation
or has-a relationship
Let us consider two classes: A Car class and a Radio class
It is odd to think of Radio is a Car! Instead, we can say a Car
has a Radio
Car – is called as Containing Class
Radio – is called as Contained Class
To expose the functionality of the inner class to the outside
world requires delegation
Delegation means adding members to the containing class that
make use of the contained class's functionality (Ex:
theMusicBox.TurnOn(state); )
Refer to: Containment folder for the complete source code
106. 106
More Details: (3) Polymorphism
Polymorphism is the ability for classes to provide different
implementations of methods that are called by the same name.
Polymorphism allows a method of a class to be called without regard to
what specific implementation it provides.
For Example, assume that you have added a new method to Employee
class as:
public void GiveBonus(float amount)
{ currPay += amount; }
This method is common for all objects derived from Employee. However,
our objective is to design this to behave differently for Manager and
SalesPerson.
This means that the subclasses should be able to provide different
interfaces to Employee class
Polymorphism is achieved through " virtual " and " override " keywords
107. 107
Types of Polymorphism
Interface polymorphism - Multiple classes may implement the
same interface, and a single class may implement one or more
interfaces. Interfaces are essentially definitions of how a class
needs to respond. An interface describes the methods, properties,
and events that a class needs to implement.
Inheritance polymorphism - Multiple classes may inherit from a
single base class. By inheriting, a class receives all of the
methods, properties, and events of the base class in the same
implementation as the base class.
Polymorphism through abstract classes - Abstract classes
provide elements of both inheritance and interfaces. An abstract
class is a class that cannot be instantiated itself; it must be
inherited.
108. 108
Base Claass
Example
public class Employee
{
public virtual void GiveBonus(float amount)
{ currPay += amount; }
………
}
public class SalesPerson : Employee
{
public override void GiveBonus(float amount)
{
int salesBonus = 0;
if (numberOfSales > 200)
salesBonus = 1000;
base.GiveBonus(amount + salesBonus);
}
}
You can reuse the base class method by using the keyword base
Alternatively, the subclass can completely redefine without calling the base
class method
109. 109
Abstract Classes
An abstract class cannot be instantiated directly, and it
is a compile-time error to use the new operator on an
abstract class
An abstract class is permitted (but not required) to
contain abstract members
An abstract class cannot be sealed – Why?
Ex: If the Employee class is declared as abstract, the
the following stmt. gives an error:
Employee e = new Employee();
What is the need for an abstract class?
Does it look OK if some one says
"I am an Employee"? or "I am a Sales Person"
110. 110
Example
abstract class A
{
public abstract void F();
}
abstract class B: A
{
public void G() {}
}
class C: B
{
public override void F()
{ // actual implementation of F }
}
The abstract class A introduces an abstract method F.
Class B introduces an additional method G, but since it doesn't provide an
implementation of F, B must also be declared abstract.
Class C overrides F and provides an actual implementation. Since there are no
abstract members in C, C is permitted (but not required) to be non-abstract.
A
B
C
111. 111
Shape Class – Design overview
The subclass Circle does not override Draw(), whereas Hexagon does
Refer to Shapes Project
public abstract class Shape
{
public virtual void Draw()
{ … }
}
public class Circle : Shape
{ … }
public class Hexagon : Shape
{
public override void
Draw()
{ ... }
}
It is more
intelligent to
declare
Draw() as
abstract
Same as
pure
virtual
function of
C++
112. 112
Method Hiding
Method hiding is opposite of Method overriding
Assume that Oval is-a type of Circle. Of course you can define a method
Draw() which overrides Draw() of its parent class and provide its own
versioning.
However, if we want to prevent the Oval class from inheriting any
previous logic, use "new" keyword
public class Oval : Circle
{
public Oval(){base.PetName = "Joe";}
// Hide base class impl if they create an Oval.
new public void Draw()
{
Console.WriteLine("Oval with class versioning");
}
}
new keyword breaks the relationship between base class of
abstract Draw() and the derived class version
113. 113
new Modifier
// The new modifier
using System;
public class MyBaseC
{
public static int x = 55;
public static int y = 22;
}
public class MyDerivedC : MyBaseC
{
new public static int x = 100; // Name hiding
public static void Main( )
{
Console.WriteLine(x); // Display the overlapping value of x:
Console.WriteLine(MyBaseC.x); // Access the hidden value of x:
Console.WriteLine(y); // Display the unhidden member y:
}
}
Output:
100
55
22