Chapter 3
C# Language Fundamentals
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
Anatomy of a simple c# program
// [Link] using System; class HelloClass { public static int Main(string[ ] args) { [Link]("Hello World"); return 0; } }
3
Anatomy of a simple c# program
Contain Main() method Public members accessible from other types Static members scoped at class level ( not object level) (string[] args) command line arguments Console class [Link]() C# not support to create global functions & global points of data
4
Variations of Main() method
// [Link] using System; class HelloClass { public static void Main(string[ ] args) { // . } } // [Link] using System; class HelloClass { public static void Main() { // . } }
Variations of Main() method
// [Link] using System; class HelloClass { public static int Main() { // . } }
Main() method based on 2 questions Do you need to process any user-specified command-line parameters? Do you want to return a value to the systen when Main() has completed.
6
Command Line Parameters
// [Link] using System; class HelloClass { public static int Main(string[ ] args) { [Link]("Command Line parameters"); for (int x = 0; x < [Link]; x++) // foreach (string s in args) [Link]("Args: {0}", args[x]); return 0; } }
7
Command Line Parameters
Length is the property of [Link] [ C# arrays actually alias the [Link] type] foreach statement can be used in place of for statement // when using foreach no need to check the size of the array public static int Main(string[ ] args) { foreach (string s in args) [Link]("Args: {0}", s); .. } }
8
Command Line Parameters
Also access command-line arguments using static GetCommandLineArgs() method of the [Link] type Return value is array of strings First index identifies - current directory containing the application itself Remaining elements- individual command- line arguments .. // Get arguments using [Link] string[] theArgs=[Link](); [Link](Pwth of this app is: {0}", theArgs[0]); s); ..
9
The [Link] class
Obtain number of details regarding the operating system currently hosting .NET application using various static members. Some propeties of [Link] Property Meaning Current Directory Display current directory GetLogicalDrives get drives of the m/c Version Execute version of the .NET MachineName name of the current m/c NewLine gets newline symbol for current environement ProcessorCount retrns no. of processors on current m/c SystemDirectory returns full path of system directory UserName returns name of the entity that stated appl 10
Creating Objects
Works almost same as C++ "new" is the de facto standard to create an object instance Example ( illegal ) Correct version
HelloClass c1; [Link](); HelloClass c1 = new HelloClass(); [Link]();
C# object variables are references to the objects in memory and not the actual objects Garbage collection is taken care by .NET
11
CONSTRUCTORS
Enables an object to initialize itself when it is created Same as the class name C# class automatically provided with free default constructor C# also provides additional constructors They do not specify a return type, not even void.
12
EXAMPLE
([Link])
class Point { public Point() { [Link]("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
Program Entry Point
[Link]("Out: {0}\t{1}", p1.x, p1.y); [Link]("Out: {0}\t{1}", p2.x, p2.y);
} }
Overloaded CONSTRUCTORS
Used when objects are required to perform similar tasks but using different i/p parameters Process of polymorphism Create an overloaded constructor - provide several different constructor definition with different parameter lists Example:
14
Example
using System; class Room { public double length; public double breadth; public Room (double x, double y) // constuctor1 { length =x; breadth = y; }
public Room (double x) // constructor 2
length = breadth = x;
}
15
Static Members
Static members a member that is common to all objects accessed without using a particular object. i.e. , the member belongs to the class rather than the objects created from the class. Use keyword static. static int count; static int max (int x, int y); Static variables & static methods are referred as class variables & class methods
16
Static Members example
using System; class mathoperation { public static float mul(float x, float y) { return x*y; } public static float divide(float x, float y) { return x/y; } } Class mathapplication { public static void Main() { float a = [Link](4.0F, 5.0F); float a = [Link](a, 2.0F); [Link](b= , +b); } } Note: static methods are called using class names. No objects are have been created for use
17
Static Members
Static methods have several restrictions
They can only call other static methods They can only access static data They cannot refer this or base in any way
18
Static Constructors
Is called before any object of the class is created Usually used to do any work that needs to be done once Used to assign initial values to static data members Declare by static keyword Eg: Class abc { static abc() // no parameters { } } No access modifies on static constructors A class can have only one static constructor
19
Static Classes
Class defined using static keyword When it is defined static, object users cannot create an instance ( i.e. no use of new keyword), & it can contain only static members & fields. static class UtilityClass { public static void PrintTime() { [Link]([Link]()); } public static void PrintDate() { [Link]([Link]()); } } static void Main(string[] args) { [Link](); UtilityClass u = new UtilityClass(); // Compiler error! 20 ...
Copy Constructors
Copy constructor creates an object by copying variables C# does not provide a copy constructor, so must provide it ourselves to the class Eg: Pass an Item object to the Item constructor so that the new Item object has the same values as the old one Public Item (Item item) { code = [Link]; price = [Link]; } Copy constructor is invoked by initializing an object of type Item & passing it the object to be copied Item item2 = new Item(item1); 21 Now, item2 is a copy of item1
Destructors
It is opposite to a constructor, Is called when object is no more required Same as class name & preceded by a tilde(~) , No return type Eg: Class Fun { ~Fun() { .. } } Wont have arguments C# uses a garbage collector, running on a separate thread, to execute all destructors on exit [so does not support delete keywor The process of calling a destructor when an object is reclaimed by 22 the garbage collector is called finalization.
Default Values
The member variables of class types are automatically set to an appropriate default value. the rules are simple: bool types are set to false. Numeric data is set to 0 (or 0.0 in the case of floating-point data types). string types are set to null. char types are set to '\0'. Reference types are set to null.
23
Default Values
Public variables/members are 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 (within the method) must assign an initial value before use them.
public static void Main (string [ ] args) { int x; [Link](x); // Error }
24
Variable initialization
C# allows you to assign a types member data to an initial value at the time of declaration // This technique is useful when you don't want to accept default values class Test { public int myInt = 9; public string myStr = "My initial value."; .. }
25
Defining a constant Data
C# offers the const keyword to define variables with a fixed, unalterable value. any attempt to alter it results in a compiler error. the const keyword cannot be used to qualify parameters or return values, and is reserved for the creation of local or instance-level data. value assigned to a constant variable must be known at compile time, and therefore a constant member cannot be assigned to an object reference
26
Example
class ConstData { public const string BestNbaTeam = "Timberwolves"; public const double SimplePI = 3.14; public const bool Truth = true; public const bool Falsity = !Truth; }
27
Establishing Member Visibility
Members of a given class or structure must specify their visibility level. C# Accessibility Keywords
28
Access Specifiers
public void MyMethod() { } private void MyMethod() { } protected void MyMethod() { } internal void MyMethod() { }
Accessible anywhere Accessible only from the class where defined Accessible from its own class and its descendent 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
29
Establishing Type Visibility
Types (classes, interfaces, structures, enumerations, and delegates) can also take accessibility modifiers Only public & internal public - accessed from other types in the current assembly as well as external assemblies. Eg: public class MyClass{} Internal - used only by the assembly in which it is defined. Eg: internal class MyHelperClass{} Types are internal by default in C#.
30
BASIC INPUT & OUTPUT
[Link] Class Write(), WriteLine(), Read(), and ReadLine()
Example (Read and Write a string):
// [Link] using System; class BasicRW { public static void Main (string [ ] args) {
string s; [Link]("Enter a string: "); s = [Link](); [Link]("String: {0}", s);
}
}
31
Basic IO
// [Link] 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"; [Link]("Int: {0}", theInt); [Link]("Float: {0}", theFloat); [Link]("String: {0}", theStr); // array of objects object[ ] obj = {"BIT", 20, 20.2}; [Link]("String: {0}\n Int: {1}\n Float: {2}\n", obj); } }
.NET String Formatting
1. 2. 3. 4. 5. 6. 7. C or c D or d E or e F or f G or g N or n X or x Currency ($) Decimal Exponential Fixed point General Numerical Hexadecimal
Example // [Link] using System; class Format { public static void Main (string [ ] args) { [Link]("C Format: {0:c}", 9999); [Link]("D Format: {0:d}", 9999); [Link]("E Format: {0:e}", 9999); [Link]("F Format: {0:f}", 9999); [Link]("G Format: {0:g}", 9999); [Link]("N Format: {0:n}", 9999); [Link]("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
33
C# Iteration Constructs
for loop foreach-in loop while loop do-while loop
34
The for Loop
C# for Loop is same as C, C++, Java, etc Example
for (int i = 0; i < 10; i++) [Link](i);
You can use "goto", "break", "continue", etc like other languages
35
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) { [Link](s); } } }
36
The while and do/while Loop
class WhileTest { public static void Main() { int n=1; while(n<=10) { if (n%2==0) { n++; } else { [Link]( +n); n++; } } }
37
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 ([Link]) { . }
Error!
38
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) { // Error no break case "India": case "USA": default: } { // Correct case "India": HiIndia(); break; case "USA": HiUSA(); break; default: break; }
39
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; }
40
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
41
Example - is
public void DisplayObject(object obj) { if (obj is int) [Link]("The object is of type integer"); else [Link]("It is not int"); }
42
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) [Link](); else [Link]("Not a Dog"); }
43
Example - typeof
Instance Level
MyClass m = new MyClass(); [Link]([Link]());
Output
[Link]
Class Level
Type myType = typeof(MyClass); [Link](myType);
Output
[Link]
44
More on as eprator
The as operator is similar to a cast operation; however, if the conversion is not possible, as returns null instead of raising an exception i.e. it is equal to :expression is type ? (type)expression : (type)null as operator only performs reference conversions and boxing conversions.
45
More Example - as
class MainClass { static void Main() { object[] objArray = new object[4]; objArray[2] = "hello"; objArray[3] = 123; objArray[4] = 123.4; objArray[5] = null; for (int i = 0; i < [Link]; ++i) { string s = objArray[i] as string; [Link]("{0}:", i); if (s != null) [Link]("'" + s + "'"); else [Link]("not a string"); } } }
Output: 0:'hello 1:not a string
2:not a string
3:not a string
46
More on typeof operator
Used to obtain the [Link] object for a type. A typeof expression takes the following form: [Link] type = typeof(int); To obtain the run-time type of an expression, use the .NET Framework method GetType : int i = 0; [Link] type = [Link](); Types with more then one type parameter must have the appropriate number of commas in the specification. The typeof operator cannot be overloaded.
47
More Example - typeof
public class SampleClass { public int sampleMember; public void SampleMethod() {} static void Main() { Type t = typeof(SampleClass); // Alternatively, you could use // SampleClass obj = new SampleClass(); // Type t = [Link](); [Link]("Methods:"); MethodInfo[] methodInfo = [Link](); foreach (MethodInfo mInfo in methodInfo) [Link]([Link]()); [Link]("Members:"); MemberInfo[] memberInfo = [Link](); foreach (MemberInfo mInfo in memberInfo) [Link]([Link]()); } }
Output: Methods: Void SampleMethod() [Link] GetType() [Link] ToString() Members: Void SampleMethod() [Link] GetType() [Link] ToString() Int32 sampleMember
48
Parameter Passing Methods
Default out ref params Value parameter Output parameter (called member) Same as pass-by-reference Variable number of parameters within a single parameter
49
Parameter Passing by value
If a parameter is not marked with a parameter modifier, it is assumed to be passed by value Passing parameters by value The called method receives a copy of the original data.
50
Parameter Passing - out
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
out
Called Program x, y ans
[Link](a, b, out r);
public void Add(int x, int y, out int ans)
51
The out modifier
using System;
class outclass { public static void Fill(out int a, out string, out bool c) { a = 9; b = your string; c = true; static void Main(string[ ] args) { int i; string str; bool b; Fill(out i, out str, out b); [Link](Int is :{0}, i); [Link](Int is :{0}, str); [Link](Int is :{0}, b); } }
52
The ref modifier
Difference b/w out & ref modifier is out parameters do not need to be initialized before they passed to method but ref needs initialization
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; [Link]("Before Swap => {0} \t {1}", a, b); [Link](ref a, ref b); [Link]("After Swap => {0} \t {1}", a, b); } }
53
The params modifier
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
54
Example
using System; class Params { public static void DispArrInts(string msg, params int[ ] list) { [Link](msg); for (int i = 0; i < [Link]; i++) [Link](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 } }
55
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() { [Link]("{0} is {1} years old", name, age); } }
56
pass any object
public static void DisplayObjects(params object[ ] list) { for (int i = 0; i < [Link]; i++) { if (list[i] is Person) ((Person)list[i]).PrintPerson(); Output: else John is 45 years old Instance of [Link] [Link](list[i]); } [Link](); }
Calling Program: Person p = new Person("John", 45); DisplayObjects(777, p, "Instance of [Link]");
57
Value and Reference Types
.NET types may be value type or reference type Primitive types are always value types including structures & enumerations 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
58
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 }
59
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 . }
60
Reference 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
61
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 deep copy, we must use ICloneable interface Example: [Link]
62
Example
// [Link] // This is a Reference type because it is a class
InnerRef valWithRef = new InnerRef("Initial Value"); [Link] = 666; valWithRef
structData = 666 refType
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; public int structData;
"I am NEW" "Initial Value"
x=
// ref type // value type
valWithRef2
structData = 777 refType
public InnerRef(string s) { refType = new TheRefType(s); structData = 9; } }
InnerRef valWithRef2 = valWithRef; [Link].x = "I am NEW"; [Link] = 777
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 [Link] = 60; // will not change the state of p p = new Person("Nikki", 90); }
64
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 [Link] = 60; // p will point to a new object p = new Person("Nikki", 90); }
65
Calling Program
// Pass by Value [Link]("Passing By Value..........."); Person geetha = new Person("Geetha", 25); [Link](); PersonByValue(geetha); [Link]();
Passing By Value........... Geetha is 25 years old Geetha is 60 years old
// Pass by Reference [Link]("Passing By Reference........"); Person r = new Person("Geetha", 25); [Link](); Passing By Reference........ Geetha is 25 years old PersonByRef(ref r); Nikki is 90 years old [Link]();
66
Difference b/w Value Types & Reference Types
Questions Where is this type allocated? How is a variable represented? Value Type Reference type Allocated on the stack. On the heap Value type variables are local copies Reference type variables are pointing to the memory occupied by the allocated instance. Can derive from any other type, as long as that type is not 67 sealed
What is the base type? Must derive from [Link].
Can this type function as a base to other types? What is the default parameter passing behavior? Can I define constructors for this type?
No. Value types are always sealed and cannot be extended. Variables are passed by value.
Yes. If the type is not sealed, it may function as a base to other types. Variables are passed by reference
When do variables of this type die?
Yes, but the default Yes constructor is reserved (i.e., custom constructors must all have arguments). When they fall out of When the managed the defining scope. heap is garbage collected. 68
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
69
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();
Objects Shape
Shape Temprect = rect;
Shape
Shape Newrect = new Shape();
70
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 [Link]() public static void Main() why static? At run time Main() call be invoked without any object variable of the enclosing class
71
Example
public class MyClass { public static void MyMethod() {} } public class StaticMethod { public static void Main(string[ ] args) { [Link](); } }
If MyMethod() is not declared as static, then MyClass obj = new MyClass(); [Link]();
72
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.
73
UnBoxing
Converting the value in an object reference (held in heap) into the corresponding value type (stack) Only unbox the variable that has previously been boxed Example: object objAge; int Age = (int) objAge; // OK string str = (string) objAge; // Wrong!
The type contained in the box is int and not string!
74
Enumerations in C#
Mapping symbolic names to numerals
Example - 1 enum Colors
{ Red, Green, Blue // 0 // 1 // 2
The internal type used for enumeration is System.Int32 Valid types: byte, sbyte, short, ushort, int, uint, long, ulong Eg: enum pos:byte { off, on}
Using Enumerations Colors c; c = [Link]; [Link](c); // Blue
Example - 2 enum Colors
{
Red = 10, Green, Blue // 10 // 11 // 12
75
Pgm illustrate use of enum
Using System; Class area { public enum Shspe { circle, square } Public void Sreashape(int x, Shape shape) { double area; switch(shape) { case [Link]: area=[Link]*x*x; [Link](circle area = +area); break; case [Link]: area=x*x; [Link](Square area = +area); break; default: [Link](Invalid input); break; }}}
76
Contd.
Class Enumtest { public static void main() { area a1 = new area(); [Link](15, [Link]); [Link](15, [Link]); [Link](15, ([Link]) 1); [Link](15, ([Link]) 10); } }
77
[Link] Base Class
Format() Converts a value of an enumerated type to its string equivalent according to the specified format
GetName()
Retrieves the name for the constant in the enumeration Returns the type of enumeration
(Colors))); // System.Int32
GetUnderlyingType() [Link]([Link](typeof
GetValues()
IsDefined() Parse()
Gives an array of values of the constants in enumeration To check whether a constant exists in enum
if ([Link](typeof(Colors), "Blue") .
Converts string/value to enum object
Colors CarColor = (Colors)[Link](typeof(Colors), "Red");
78
Example [enumeration]
Array obj = [Link](typeof(Colors)); foreach(Colors x in obj) { [Link]([Link]()); [Link]("int = {0}", [Link](typeof(Colors), x, "D")); } Output
Red int = 0 Blue int = 1 Green int = 2
79
[Link]
Every C# data type is derived from the base class called [Link]
class HelloClass { .... } // implicitly derive [Link] is same as class HelloClass : [Link] { ....} // explicitly deriving
80
Example
Instance level members are declared using virtual keyword 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();
.. } }
81
Core Members of [Link]
Equals() Returns true only if the items being compared refer to the exact same item in memory
GetHashCode()
GetType() ToString() Finalize()
Returns an integer that identifies a specific object instance
Returns [Link] [ describes current item] Returns <[Link] name> in string format For object removal (garbage collection)
MemberwiseClone()
Returns a new object which is member-wise copy of the current object
82
Example
// [Link] using System; class ObjTest { public static void Main (string [ ] args) { ObjTest c1 = new ObjTest();
ToString: ObjTest GetHashCode: 1 GetType: [Link] Same Instance
[Link]("ToString: {0}", [Link]()); [Link]("GetHashCode: {0}", [Link]()); [Link]("GetType: {0}", [Link]().BaseType); // create second object ObjTest c2 = c1; object o = c2; if ([Link](c1) && [Link](o)) [Link]("Same Instance"); } }
83
Overriding [Link] 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; }
84
Overriding ToString()
To format the string returned by [Link]()
using [Link];
class Person { public override string ToString() { StringBuilder sb = new StringBuilder(); [Link]("[FName = {0}", [Link]); [Link]("LName = {0}", [Link]); [Link]("SSN = {0}", [Link]); [Link]("Age = {0}]", [Link]); return [Link](); } }
85
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.
86
Example
class Person { public override bool Equals(object o) { Person temp = (Person) o; if ([Link] == [Link] && [Link] == [Link] && [Link] == [Link] && [Link] == [Link]) 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 [Link] 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: [Link]
public override int GetHashCode()
{ return [Link](); }
C# Data Types
C# Alias
sbyte
byte short ushort int uint long ulong char float
System Type
[Link]
[Link] System.Int16 System.UInt16 System.Int32 System.UInt32 System.UInt64 System.UInt64 [Link] [Link]
Range
-128 to 127
0 to 255 -32768 to 32767 0 to 65535 -2,147,438,648 to +2,147,438,647 0 to 4,294,967,295 -9,223,372,036,854,775,808 to +9,.. 0 to 18,446,744,073,709,551,615 U10000 to U1FFFF 1.510-45 to 3.41038
double bool
decimal string object
[Link] [Link]
[Link] [Link] [Link]
5.010-324 to 1.710308 true or false
100 to 1028 Limited by system memory Anything at all
Hierarchy of System Types
Object Type String Array Exception Delegate ValueType (derived one is struct type and not class) Boolean Byte Char UInt16 UInt32 UInt64 Void DateTime Guid TimeSpan Single
90
Decimal
Double Int16 Int32 Int64
MulticastDelegate
SByte
Enumerations and Structures
Contd..
All value types permitted to create a system type using the new keyword. It sets default value to the variable. Eg: bool b1=new bool(); // b1 = false bool b2=false; Integer data type properties [Link] [Link] Eg: static void Main(string[] args) { System.UInt16 myuint=30000; [Link](Max value:{0}, [Link]); [Link](Max value:{0}, [Link]);
}
91
Contd
Double
[Link] [Link] [Link] [Link]
Members of [Link]
Valid assignment is true or false. Cant assign values like (-1,0,1) [Link] [Link]
Members of [Link]
[Link]('K') [Link]('a') or [Link]("100", 1) [Link]("Hi BIT", 2) [Link](',')
92
Contd
Parsing values from String data
Parsing technique is used to convert textual data into a numerical value Eg: static vaoid Main(string[] args) { bool mybool = [Link](true); [Link](value of mybool: {0}, mybool); int myint = [Link](8); [Link](value of myint: {0}, myint); .. }
93
Contd
[Link] and [Link]
DateTime type represents specific date & time value Static void Main() {.. DateTime dt=new DateTime(2004, 10, 17) [Link](The day of {0} is {1}, [Link], [Link]); dt. = [Link](2) . }
94
Contd
TimeSpan structure allows to define & transform units of time using various members. static void Main(string[] args) {.. TimeSpan ts=new TimeSpan(4,30,0); [Link](ts); [Link]([Link](new TimeSpan(0,15,0))); . }
95
The [Link] Data Type
Member Length Contains() Format() Insert() Remove() Replace() Substring() ToUpper() Meaning Returns length of the current string Determine if the current string object contains a specific string Format a string literal Contains newly inserted data Character removed or replaced
Returns a string that represents a substring Create a copy of string in upper or lower case 96
Basic string operations
Example: static void Main(string[] args) { string s= this is taking short time; [Link](s contains me?:{0},[Link](me)); [Link]([Link](., !); [Link]([Link](0, Hai)); } Equality operator (= =) used to compare the value with string objects. [Link]() used to concatenate existing string with new string.
97
Escape characters
Character \ \ \\ \a \n ]r \t Meaning Single quote Doubl quote Insert backslash Beep New Line Carriage return Horizontal tab
98
Eg:String s3 Hello \t there \t again; [Link](s3); Or [Link](C:\\myapp\ \bin\\debug);
Verbatim Strings
@ prefixed string literals notation termed as verbatim string Using verbatim string Disable the process of literals escap characters [Link](@C:\myapp\bin\debug); Preserve white space for strings the flow over multiple lines String mystring= @ This is a very very long string; [Link](mystring); Insert a double quote by doubling tokel [Link](@ this is verbatim string);
99
[Link]
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 [Link]! [Link] provides members like Append, Formet, Insert & Remove
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 stringlike object, use the [Link] class.
100
Example
using System; using [Link]; class MainClass { public static void Main() { StringBuilder myBuffer = new StringBuilder("Buffer"); [Link](Capacity of the string:{0}, [Link]); [Link]( " is created"); [Link](Capacity of the string:{0}, [Link]); [Link](myBuffer);
}
}
101
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--) [Link](items[i]); } private static string[ ] items = new string[5]; private static int top = -1; }
Stack Class.
class StaticMethod { public static void Main(string[] args) { [Link]("Stack Contents:"); [Link]("BIT"); [Link]("GAT"); [Link](); [Link]("Item Popped=> " + [Link]()); [Link]("Stack Contents:"); [Link](); } }
Arrays in C#
C# arrays are derived from [Link] base class Memory for arrays is allocated in heap Arrays always have a lower bound of zero Example
Int [ ] counter; // array declaration string [ ] strArray = new string[10]; // string array int [ ] intArray = new int [10]; // integer array Person[ ] Staff = new Person[2]; // object array strAarray[0] = "BIT"; // assign some value int [ ] Age = new int[3] {25, 45, 30}; // array initialization
104
Arrays in C#
Assign an array object to another eg: int [ ] a ={1,2,3}; int [ ] b; b=a; Array can also hold reference type elements but they contain only references to the elements & not the actual values.
105
Arrays as Parameters ( & return values)
Pass a parameter & receive it as a member return value Eg: static void PrintArray(int[ ] myInts) { for(int I =0; i<=[Link];i++) [Link](Item {0} is {1}, I, myInts[i]); } static string[ ] GetstringArray( ) { string [ ] str1={A , B, C}; return str1; } static void Main(string[ ] args) { int[ ] ages = {20, 22, 23, 0}; PrintArray(ages); string[ ] str=SetstringArray(); foreach (string s in str) [Link](s); }
106
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 < [Link]; i++) myJaggedArr[i] = new int[i + 7]; Note that, 1st row will have 7 columns and 2nd row will have 8 columns 107
[Link] Base Class
BinarySearch( ) Clear( ) CopyTo( ) GetEnumerator( ) Finds a given item Sets range of elements to 0/null Copy source to Destination array Returns the IEnumerator interface
GetLength( ) Length
GetLowerBound( ) GetUpperBound( ) GetValue( ) SetValue( ) Reverse( ) Sort( )
To determine no. of elements Length is a read-only property
To determine lower and upper bound Retrieves or sets the value of an array cell, given its index Reverses the contents of one-dimensional array Sorts a one-dimensional array
Example
Using System; Class sortReverse { public static void Main(string[ ] args) { int[ ] x= {30, 10, 80, 90,20}; [Link]("Array before sorting"); foreach(int I in x) [Link]( +i); [Link]();; [Link](x); [Link](x); [Link]("Array after sorting"); foreach(int I in x) [Link]( +i); [Link]();; } }
109
Example
public static int[ ] ReadArray( ) // reads the elements of the array { int[ ] arr = new int[5]; for (int i = 0; i < [Link]; i++) arr[i] = [Link] - i; return arr; } public static int[ ] SortArray(int[ ] a) { [Link](a); // sorts an array return a; }
110
Calling Program
public static void Main(string[ ] args) { int[ ] intArray; intArray = ReadArray( ); // read the array elements [Link]("Array before sorting"); for (int i = 0; i < [Link]; i++) [Link](intArray[i]); intArray = SortArray(intArray); // sort the elements [Link]("Array after sorting"); for (int i = 0; i < [Link]; i++) [Link](intArray[i]); }
111
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 [Link] objects that represents a string. If it is necessary to modify the actual contents of a string-like object, use the [Link] 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'.
112
Strings
For string comparisons, use
Compare, CompareOrdinal, CompareTo(), Equals, EndsWith, and StartsWith Use IndexOf, IndexOfAny, LastIndexOf, and LastIndexOfAny Copy and CopyTo Substring and Split
To obtain the index of the substring or unicode, use
To copy a string a substring, use To create one or more strings, use To change the case, use
ToLower and ToUpper
Insert, Replace, Remove, PadLeft, PadRight, Trim, TrimEnd, and TrimStart
To modify all or part of the string, use
Meaning of String Methods
String s1 = "a"; String s2 = "A"; int x = [Link](s1, s2); int y = [Link](s1, s2); [Link]("Ordinal"); if (x == 0) [Link]("a = A"); else if (x > 0) [Link]("a > A"); else [Link]("a < A"); [Link]("Compare"); if (y == 0) [Link]("a = A"); else if (y > 0) [Link]("a > A"); else [Link]("a < A"); Ouput: Ordinal a>A Compare a<A
114
More String Methods
CompareTo() int x = [Link](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 ); Example: s = [Link]();
115
ToLower() - Returns a copy of this String in lowercase
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 [Link] class!
116
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; [Link] = 111; [Link] = "Geetha"; [Link] = 77; STUDENT SomeOne = new STUDENT(222,"Raghu",90); }
(Un)Boxing custom structures
To convert a structure variable into an object reference use boxing Eg: STUDENT s1= new STUDENT( 333, Anu, 80); object sbox=s1; Unboxing: Eg: public static void Main unboxs1(object o) { STUDENT temp=(STUDENT) o; [Link]([Link]+ is got Distinction); }
unboxs1(sbox); // calling logic
118
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) [Link] tr; (2) using [Link];
XmlTextReader tr;
119
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:
// [Link] using MyShapes; {
public class Square { } public class Circle { } public class Hexagon { }
}
120
Alternate Approach
// [Link] using System; namespace MyShapes { class Square { } } // [Link] using System; namespace MyShapes { class Circle { } } // [Link] 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
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 [Link]();
Qualify the name of the class with the appropriate namespace The default namespace given in VS IDE is the name of the project
122
Defining Namespace Aliases
Aliases - An alternative approach to resolve namespace clashes
using system; using MyShapes; using My3DShapes; using A=[Link];
Namespace MyaApp { class ShapeTester { Public static void Main() { [Link] h=new [Link](); [Link] c = new [Link]() A h2=new a(); // creating an object using alias }}}
123
Neated Namespaces
Eg: to create a higher level namespace that contains exisiting My3DShapes namespace, update the previous codes as follows: Usinf System; namespaceNest { Namespace My3DShapes; { class Square { } class Circle { } class Hexagon { } }} Or Using System; Namespace Nest.My3DShapes { class Square { } class Circle { } class Hexagon { } }}
124
End of
Chapter 3