Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
2 views133 pages

Unit2-Lecture-1 (9 Files Merged)

The document provides an overview of basic C# class structure, including the use of the 'using' keyword, the Main() method as the entry point, and the importance of constructors and variable initialization. It explains the differences between value types and reference types, as well as the core members of the System.Object class that all C# types derive from. Additionally, it covers input and output operations using the Console class and the significance of default assignments and variable scope.

Uploaded by

thompsondjalok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views133 pages

Unit2-Lecture-1 (9 Files Merged)

The document provides an overview of basic C# class structure, including the use of the 'using' keyword, the Main() method as the entry point, and the importance of constructors and variable initialization. It explains the differences between value types and reference types, as well as the core members of the System.Object class that all C# types derive from. Additionally, it covers input and output operations using the Console class and the significance of default assignments and variable scope.

Uploaded by

thompsondjalok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 133

C# and .

NET

School of Computer Science and Engineering


UNIT 2 – Lecture 1
The Anatomy of Basic C# Class
BASIC C# CLASS
The using keyword has two major uses:
// Hello.cs using Directive Creates an alias for a namespace
using System; or imports types defined in other namespaces.
using Statement Defines a scope at the end of
class HelloClass which an object will be disposed.
{
public static int Main(string[ ] args)
{
Console.WriteLine("Hello World");
Console.ReadLine();
return 0;
}
}

3
BASIC C# CLASS
• C# demands that all the program logic is contained within a type
definition(class, interface, structure, enumerate, delegate).
• In C# global functions or global data cannot be created.
• Every executable C# application must contain a class defining a Main()
method, which is used to signify the entry point of the application.
• The signature of Main() is adorned with the public and static keywords.
Public members are accessible from other types, while static members are
scoped at class level and can thus be invoked without the need to first
create a new class instance.
• C# is the case sensitive programming language.

4
BASIC C# CLASS
• Main() method has a single parameter, which takes the array of strings.
This parameter May contain any number of incoming command line
arguments.
• You make use of console class, which is defined within the System
namespace.
• The WriteLine() method of console class, writes a text string to the
standard output
• The ReadLine() reads a line from standard input until new line character.
• The int Main() method returns 0 (Success) before exiting.

5
BASIC C# CLASS - VARIATIONS
// Hello1.cs // Hello2.cs
using System; using System;
class HelloClass class HelloClass
{ {
public static void Main(string[ ] args) public static void Main()
{ {
// ………. // ………….
} }
} }

public static void Main(string[] args) { }


public static void Main() { }
public static int Main() { }
public static int Main(string[] args){}
6
COMMAND LINE PARAMETERS
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 x in args)
Console.WriteLine("Args: {0}", args[x]);
return 0;
}
}

7
COMMAND LINE PARAMETERS
• You are also able to access command line arguments using the static
GetCommandLineArgs() method of System.Environment type.
• The return value of this method is array of strings.
• The first index identifies the current directory containing the application itself, while the
remaining elements in the array contain the individual command line arguments.
public static int Main(string[] args)
{
...
string[] arguments = Environment.GetCommandLineArgs();
Console.WriteLine(“Path of the App is {0}”,arguments[0]);
...
}

8
CONSTRUCTORS
1. Every C# class is automatically provided with a free default constructor.
2. The default constructor ensures that all data members are set to an appropriate default
value.
3. Classes provide additional constructors called parameterized or custom constructors.
4. Works almost same as C++
5. "new" is the de facto standard to create an object instance
6. Example ( illegal ) Correct version
HelloClass c1; HelloClass c1 = new HelloClass();
c1.SayHi(); c1.SayHi();
7. C# object variables are references to the objects in memory and not the actual objects
8. Garbage collection is taken care by .NET
9
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; Program
} Entry Point
class PointApp
{
public static void Main(string[ ] args)
{ Place Holder
Point p1 = new Point(); // default constructor called
Point p2;
p2 = new Point(10, 20); // arg constructor called
Console.WriteLine("Out: {0}\t{1}", p1.x, p1.y);
//Console.WriteLine("Out: {0}\t{1}", p2.x, p2.y);
Console.WriteLine("Out: “ + p2.x “and “+ p2.y);//other way
}
}
10
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
}

11
COMPOSITION OF A C# APPLICATION
1. While it is perfectly legal to have the static Main() method in the same class, that defines
object description, it may seem a bit strange that the static Main() method creates an
instance of the very class in which it was defined:
class HelloApp
{
...
public static int Main(string[] args)
{
HelloApp c1 = new HelloApp();
...
}
}
2. A more natural design would be to factor the HelloClass type into two distinct classes:
HelloClass and HelloApp.
3. In OO parlance, this is termed the "separation of concerns."

12
THANK YOU
C# and .NET

School of Computer Science and Engineering


UNIT 2 – Lecture 2
D e f a u l t a s s i g n m e n t a n d Va r i a b l e S c o p e
DEFAULT ASSIGNMENT AND VARIABLE SCOPE
• The member variables of class types are automatically set to appropriate default values.
✓ bool types are set to false.
✓ Numeric data is set to 0.
✓ string types are set to null.
✓ char types are set to ‘\0’.
✓ References are set to null.

Class Test
{
Public int myint; //set to 0
Public string mystring; //set to null
Public bool mybool; //set to false
Public object myobj; //set to null
}

3
DEFAULT ASSIGNMENT AND VARIABLE SCOPE
• When you define a local variable within a local scope, you must assign an initial value
before you use them, as they do not receive a default assignment.

Explicit
Static void Main(string[] args) Initialization of
Local Variables
{
Int localint=0;
Console.WriteLine(“{0}”, localint);
}

4
C# MEMBER INITIALIZATION SYNTAX
1. Class types tend to have numerous member variables.
2. A class may define various custom constructors to initialize members.
3. This is particularly necessary if you do not wish to accept the default values assigned to
your state data.
4. For example, if you wish to ensure that an integer member variable always begins life with
the value of 9, you could write:
// This is OK, but redundant...
class Test
{
private int myInt;
Test() { myInt = 9; }
Test(string someStringParam)
{ myInt = 9; }
Test(bool someBoolParam)
{ myInt = 9; }
...
}
5
C# MEMBER INITIALIZATION SYNTAX
1. An alternative would be to define a private helper function for your class type that is called
by each constructor.
2. While this will reduce the amount of repeat assignment code, you are now stuck with the
following redundancy:
// This is still rather redundant...
class Test
{
private int myInt;
Test() { InitData(); }
Test(string someStringParam)
{ InitData(); }
Test(bool someBoolParam)
{ InitData(); }
private void InitData()
{ myInt = 9; }
...
}
6
C# MEMBER INITIALIZATION SYNTAX
1. C# allows you to assign a type's member data to an initial value at the time of declaration.
2. Notice in the following code that member initialization may be used with internal object
references as well as numerical data types:

// This technique is useful when you don't want to accept default values
// and would rather not write the same initialization code in each
// constructor.
class Test
{
private int myInt = 9;
private string myStr = "My initial value.";
...
}

7
C# and .NET

School of Computer Science and Engineering


UNIT 2 – Lecture 3
Basic Input and Output with the Console Class
BASIC INPUT & OUTPUT
1. The Console type defines a set of methods to capture input and output, all of which are
defined as static and therefore called at the class level. System.Console Class
2. Write(), WriteLine(), Read(), and ReadLine()
3. Example (Read and Write a string):
using System;
class BasicRW
{
public static void Main (string [ ] args)
{
string s;int p=10;
Console.Write("Enter a string: ");
s = Console.ReadLine();
Console.WriteLine("String: {0} “,s);
}
}
3
BASIC IO…
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 = “REVA";

Console.WriteLine("Int: {0} {1}", theInt,theFloat);


Console.WriteLine("Float: {0}", theFloat);
Console.WriteLine("String: {0}", theStr);

// array of objects
object[ ] obj = {“REVA", 20, 20.2};
Console.WriteLine("String: {0}\n Int: {1}\n Float: {2}\n", obj);
}
}
4
.NET STRING FORMATTING
1. C or c Currency ($) Example
2. D or d Decimal using System;
3. E or e Exponential class Format
{
4. F or f Fixed point
public static void Main (string [ ] args)
5. G or g General
{
6. N or n Numerical Console.WriteLine("C Format: {0:c}", 9999);
7. X or x Hexadecimal Console.WriteLine("D Format: {0:d}", 9999);
Console.WriteLine("E Format: {0:e}", 9999);
C Format: $9,999.00 Console.WriteLine("F Format: {0:f}", 9999);
D Format: 9999 Console.WriteLine("G Format: {0:g}", 9999);
E Format: 9.999000e+003 Console.WriteLine("N Format: {0:n}", 9999);
F Format: 9999.00 Console.WriteLine("X Format: {0:x}", 9999);
G Format: 9999 }
N Format: 9,999.00 }
X Format: 270f

5
VALUE AND REFERENCE TYPES
1. .NET types may be value type or reference type
2. Primitive types are always value types including structures as well as
enumerations
3. These types are allocated on the stack. Outside the scope, these variables
will be popped out.
4. However, classes are not value type but reference based
5. 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
}
6
VALUE AND REFERENCE TYPES
1. 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
….
}
7
VALUE AND REFERENCE TYPES
1. All structures are implicitly derived from a class named System.ValueType.
2. The purpose of System.ValueType is to override the virtual methods
defined by System.Object

8
VALUE AND REFERENCE TYPES
1. Class types are always reference types
2. These are allocated on the garbage-collected heap
3. Assignment of reference types will reference the same object
4. Example:
class Foo
{
public int x, y;
}
5. Now the statement Foo f2 = f1; has a reference to the object f1 and
any changes made for f2 will change f1
9
VALUE TYPES CONTAINING REFERENCE TYPES
1. When a value type contains other reference type, assignment results only
"reference copy"
2. You have two independent structures, each one pointing to the same
object in memory – "shallow copy"
3. For a more deeper copy, we must use ICloneable interface

10
EXAMPLE:
// 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;
}
}

11
VALUE TYPES VS REFERENCE TYPES

12
THANK YOU
C# and .NET

School of Computer Science and Engineering


UNIT 2 – Lecture 4
The Master Node: System.Object
SYSTEM.OBJECT
1. Every C# data type is derived from the base class called System.Object

class HelloClass
{ .... }
is same as
class HelloClass : System.Object
{ ....}

3
SYSTEM.OBJECT
1. The Object class defines a common set of members supported by every type in the .NET
universe.
2. System.Object defines a set of instance level and class level static members.
3. Some of the instance level members are declared using the virtual keyword and can
therefore be overridden by a derived class.

4
CORE MEMBERS OF SYSTEM.OBJECT
Returns true only if the items being compared refer to the exact
Equals()
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

5
CREATE SYSTEM.OBJECT
METHODS
using System;
class ObjTest
{
ToString: ObjTest
public static void Main (string [ ] args)
GetHashCode: 1
{
ObjTest c1 = new ObjTest(); GetType: System.Object
Same Instance
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");
}
}

6
OVERRIDING SOME DEFAULT BEHAVIOURS OF
SYSTEM.OBJECT
Overriding is the process of redefining the behaviour of an inherited virtual member in a
derived class.
// Remember! All classes implicitly derive from System.Object.
class Person
{
public Person(string fname, string lname, string ssn, byte a)
{
firstName = fname;
lastName = lname;
SSN = ssn;
age = a;
}
public Person(){}
// The state of a person.
public string firstName;
public string lastName;
public string SSN;
public byte age;
}
7
OVERRIDING SYSTEM.OBJECT.TOSTRING()
• Overriding the ToString() method provides a way to get a snapshot of an object’s current
state. This can be helpful during the debugging process.
// Need to reference this namespace to access StringBuilder type.
using System.Text;
class Person
{
// Overriding System.Object.ToString().
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("[FirstName= {0}", this.firstName);
sb.AppendFormat(" LastName= {0}", this.lastName);
sb.AppendFormat(" SSN= {0}", this.SSN);
sb.AppendFormat(" Age= {0}]", this.age);
return sb.ToString();
}
...
}
8
OVERRIDING SYSTEM.OBJECT.EQUALS()
• Equals() return true only if the two references being compared are pointing to the same
object on the heap.
• You can override the Equals(), if you are more interested if the two objects have the
same state data.
class Person
{
public override bool Equals(object o)
{
Person temp = (Person)o; // Does the object o have the same values?
if(temp.firstName == this.firstName && temp.lastName == this.lastName &&
temp.SSN == this.SSN && temp.age == this.age)
return true;
else
return false;
}
...
}

9
OVERRIDING SYSTEM.OBJECT.GETHASHCODE()
• When you override the Equals() method, best practise states that you should
also override System.Object.GetHashCode().
• The role of GetHashCode() is to return a numerical value that identifies an
object based on its internal state data.
• Overriding this method is only useful if you intend to store a custom type within
a hash-based collection such as System.Collections.Hashtable.
• Due to the fact that System.Object has no clue about the state data of derived
types, you should override this member for any type you wish to store in
Hashtable.
• There are many algorithms that can be used to create a hash code.
• In the simplest case, an object's hash value will be generated by taking its state
data into consideration and building a unique numerical identifier for the type.

10
OVERRIDING SYSTEM.OBJECT.GETHASHCODE()
• For our purposes, let's assume that the hash code of the string representing an
individual's SSN is unique enough.
• System.String has a very solid implementation of GetHashCode().
• Therefore, if you have a string member that should be unique among objects
(such as an SSN), this is an elegant solution:

// Return a hash code based on the person's SSN.


public override int GetHashCode()
{
return SSN.GetHashCode();
}

11
THE SYSTEM DATA TYPES (AND C# ALIASES)
1. Every intrinsic C# data type is actually an alias to an existing type defined
in the System namespace.
2. Specifically, each C# data type aliases a well-defined structure type in the
System namespace

12
THE SYSTEM DATA TYPES (AND C# ALIASES)
C# Alias CLS ? System Type Range
sbyte No System.SByte -128 to 127
byte Yes System.Byte 0 to 255
short Yes System.Int16 -32768 to 32767
ushort No System.UInt16 0 to 65535
int Yes System.Int32 -2,147,438,648 to +2,147,438,647
uint No System.UInt32 0 to 4,294,967,295
long Yes System.UInt64 -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
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
13
HIERARCHY OF SYSTEM TYPES
Object Boolean
UInt16
Byte
Type UInt32
Char
String ValueType UInt64
(derived one Decimal
is Void
Array
struct type Double
and not DateTime
Exception Int16
class)
Guid
Delegate Int32
TimeSpan
Int64
Single
MulticastDelegate SByte

Enumerations and Structures


14
THANK YOU
C# and .NET

School of Computer Science and Engineering


UNIT 2 – Lecture 5
C o n v e r t i n g B e t w e e n Va l u e T y p e s a n d
R e f e r e n c e Ty p e s : B o x i n g a n d U n b o x i n g
BOXING AND UNBOXING
Boxing: Boxing can be formally defined as the process of explicitly converting a value type into a
corresponding reference type by storing the variable in a System.Object. When you box a value, the
CLR allocates a new object on the heap and copies the value type’s value (in this case, 25) into that
instance. What is returned to us is a reference to the newly allocated object.
1. Explicitly converting a value type into a corresponding reference type
2. Example: int Age = 25;
object objAge = Age;
1. No need for any wrapper class like Java
2. C# automatically boxes variables whenever needed.
3. For example, when a value type is passed to a method requiring an object,
then boxing is done automatically.

3
UNBOXING
The opposite operation is also permitted through unboxing. Unboxing is the
process of converting the value held in the object reference back into a
corresponding value type on the stack. The unboxing operation begins by verifying
that the receiving data type is equivalent to the boxed type, and if so, it copies the
value back into a local stack-based variable.
1. Converting the value in an object reference (held in heap) into the
corresponding value type (stack)
2. Example:
object objAge;
int Age = (int) objAge; // OK
string str = (string) objAge; // Wrong!
3. The type contained in the box is int and not string!
4
EXAMPLES
short s = 25;
object objShort = s;
// Illegal unboxing.
static void Main(string[] args)
{
...
try
{
// The type contained in the box is NOT a int, but a short!
int i = (int)objShort;
}
catch(InvalidCastException e)
{
Console.WriteLine("OOPS!\n{0} ", e.ToString());
}
}

5
EXAMPLES

static void BoxAndUnboxInts()


{
// Box ints into ArrayList.
ArrayList myInts = new ArrayList();
myInts.Add(88);
myInts.Add(3.33);
myInts.Add(false);
// Unbox first item from ArrayList.
int firstItem = (int)myInts[0];
Console.WriteLine("First item is {0}", firstItem);
}

6
C# ITERATION CONSTRUCTS
• for loop
• foreach-in loop
• while loop
• do-while loop

7
THE FOR LOOP
1. C# for Loop is same as C, C++, Java, etc
2. Example
for (int i = 0; i < 10; i++)
Console.WriteLine(i);
3. You can use "goto", "break", "continue", etc like other languages

8
THE FOREACH/IN LOOP
using System;
class ForEach
{
public static void Main(string[] args)
{
string[ ] Names = new string [ ] {"Arvind ", "Geetha ", "Madhu ", "Priya "};

foreach (string s in Names)


{
Console.WriteLine(s);

}
}

9
THE WHILE LOOP
class FileRead
{
public static void Main(string[] args)
{
try
{
StreamReader strReader = File.OpenText("d:\\in.dat");
string strLine = null;
while ((strLine=strReader.ReadLine( )) != null)
{
Console.WriteLine(strLine);
}
strReader.Close();
}
catch (FileNotFoundException e)
{
Console.WriteLine(e.Message);
}
}
}
10
THE DO/WHILE LOOP
static void Main(string[] args)
{
string userIsDone = "";
do
{
Console.WriteLine("In do/while loop");
Console.Write("Are you done? [yes] [no]: ");
userIsDone = Console.ReadLine();
}while(userIsDone.ToLower() != "yes"); // Note the semicolon!
}

11
PRACTICE PROGRAM
Write a program that takes three points (x1, y1), (x2, y2) and (x3, y3) from the user and the program will
check whether or not all the three points fall on one straight line.((1, 1), (1, 4), (1, 5) Collinear

public class pointApp using System;


{ public class point
public static void Main() {
{ public double x, y;
point p1=new point(1,5); public point(double a, double b)
point p2=new point(2,5); {
point p3=new point(4,6); x=a;
y=b;
double d1= Math.Sqrt(Math.Pow((p1.x-p2.x),2)+Math.Pow((p1.y-p2.y),2)); }
double d2= Math.Sqrt(Math.Pow((p2.x-p3.x),2)+Math.Pow((p2.y-p3.y),2)); }
double d3= Math.Sqrt(Math.Pow((p1.x-p3.x),2)+Math.Pow((p1.y-p3.y),2));
if (d3!=(d1+d2))
Console.WriteLine(“NO”);
else
Console.WriteLine("yes");
Console.ReadLine();
}
} 12
THANK YOU
C# and .NET

School of Computer Science and Engineering


UNIT 2 – Lecture 6
C# Controls Flow Constructs
C# CONTROLS FLOW CONSTRUCTS
1. if, if-else Statements
2. Relational operators like ==, !=, <, >, <=, >=, etc are all allowed in C#
3. Conditional operators like &&, ||, ! are also allowed in C#
4. Beware of the difference between int and bool in C#

3
THE SWITCH STATEMENT
1. Same as C, C++, etc. with some restrictions
2. Every case should have a break statement to avoid fall through (this
includes default case also)
3. Example
switch(country)
switch(country) { // Correct
{ case "India": HiIndia();
// Error – no break break;
case "India": case "USA": HiUSA();
case "USA": break;
default: default: break;
} }

4
GOTO STATEMENT
1. goto label;
2. Explicit fall-through in a switch statement can be achieved by using goto
statement
3. Example: switch(country)
{
case "India": HiIndia();
goto case "USA";
case "USA": HiUSA();
break;
default: break;
}

5
C# OPERATORS
1. All operators that you have used in C and C++ can also be used in C#
2. Example: +, -, *, /, %, ?:, ->, etc
3. Special operators in C# are : typeof, is and as
4. The is operator is used to verify at runtime whether an object is compatible
with a given type
5. The as operator is used to downcast between types
6. The typeof operator is used to represent runtime type information of a class

6
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");
}

7
EXAMPLE - AS
1. Using as, you can convert types without raising an exception
2. In casting, if the cast fails an InvalidCastException is raised
3. 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");
}

8
C# OPERATORS

9
THANK YOU
C# and .NET

School of Computer Science and Engineering


UNIT 2 – Lecture 7
Defining Custom Class Methods
CLASS METHODS
1. Every method you implement must be a member of a class or struct
(global methods are not allowed in C#).
2. A method exists to allow the type to perform a unit of work.
3. Custom methods may or may not take parameters, may or may not
return values (of any intrinsic or user defined types).
4. Also, custom methods may be declared nonstatic (instance-level) or
static (class-level) entities.

3
METHOD ACCESS SPECIFIERS
1. public void MyMethod() { } » Accessible anywhere
2. private void MyMethod() { } » Accessible only from the class where defined
3. protected void MyMethod() { } » Accessible from its own class and its descendent
4. internal void MyMethod() { } » Accessible within the same Assembly
5. void MyMethod() { } » private by default
6. protected internal void MyMethod() { }
» Access is limited to the current assembly or types derived from the containing class

4
STATIC METHODS
1. What does 'static' method mean?
2. Methods marked as 'static' may be called from class level
3. 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()
4. public static void Main() – why static?
5. At run time Main() call be invoked without any object variable of the
enclosing class
6. If we are accessing the static variables and methods inside the same class,
we can directly access them without using the class name.

5
EXAMPLE

public class MyClass


{
public static void MyMethod()
{…}
}
public class StaticMethod
{
If MyMethod() is not declared as
public static void Main(string[ ] args) static, then
{
MyClass obj = new MyClass();
MyClass.MyMethod(); obj.MyMethod();
}
}

6
STATIC DATA
• Static data is allocated once and shared among all object instances of the same
type

class SavingsAccount
{
public double currBalance;
public static double currInterestRate = 0.04;
public SavingsAccount(double balance)
{ currBalance = balance;}
}

7
STATIC DATA
• Create three instances of SavingsAccount:

static void Main(string[] args)


{
// Each SavingsAccount object maintains a copy of the currBalance field.

SavingsAccount s1 = new SavingsAccount(50);


SavingsAccount s2 = new SavingsAccount(100);
SavingsAccount s3 = new SavingsAccount(10000.75);
}

8
STATIC DATA
• The in-memory data allocation would look something like:

9
STATIC CONSTRUCTOR
• If you were to assign the value to a piece of static data within an instance-level
constructor, then the value is reset each time you create a new object!
• C# allows you to define static constructors to assign an initial value to static data.
• A given class or structure may define only one static constructor.
• A static constructor executes exactly one time, regardless of how many objects of
the type are created.
• A static constructor does not take an access modifier and cannot take
parameters.
• The static constructor runs first, then the non-parameterized constructor, then the
parameterized constructor.

10
STATIC CONSTRUCTOR

class SavingsAccount
{
...
// Static constructor.
static SavingsAccount()
{
Console.WriteLine("In static ctor!");
currInterestRate = 0.04;
}
}

11
STATIC CONSTRUCTOR public static void Main()
{
// Here Both Static and instance
class G1 {
// constructors are invoked for
// first instance
static G1()
G1 obj = new G1(1);
{
Console.WriteLine("Example of Static Constructor");
Console.WriteLine(obj.g1_detail("Sunil", "CSE"));
}
public G1(int j)
// Here only instance constructor
{
// will be invoked
Console.WriteLine("Instance Constructor " + j);
G1 ob = new G1(2);
}
Console.WriteLine(ob.g1_detail("Sweta", "ECE"));
public string g1_detail(string name, string branch)
}
{
} Example of Static Constructor
return "Name: " + name + " Branch: " + branch;
} Instance Constructor 1
Name: Sunil Branch: CSE
Output:
Instance Constructor 2
Name: Sweta Branch: ECE

12
STATIC CLASSES
• When a class has been defined as static, it is not creatable using the new
keyword, and it contains only static members and fields.

// Static classes can only contain static members and constant


// fields.
static class UtilityClass
{
public static void PrintTime()
{ Console.WriteLine(DateTime.Now.ToShortTimeString()); }
public static void PrintDate()
{ Console.WriteLine(DateTime.Today.ToShortDateString()); }
}

13
STATIC CLASSES

public static class Calculator


class Program
{
{
private static int _resultStorage = 0;
static void Main(string[] args)
{
public static string Type = "Arithmetic";
var result = Calculator.Sum(10, 25); // calling static method
Calculator.Store(result);
public static int Sum(int num1, int num2)
{
var calcType = Calculator.Type; // accessing static variable
return num1 + num2;
Calculator.Type = "Scientific"; // assign value to static variable
}
}
}
public static void Store(int result)
{
_resultStorage = result;
}
}

14
STATIC CLASSES
using System; output

static class Test {


static int a = 5; error CS0723: Cannot declare a variable of static type 'Test'
static void display() { error CS0712: Cannot create an instance of the static class

Console.WriteLine("Static method");
}

static void Main(string[] args) {

// creating object of Test


Test t1 = new Test();
Console.WriteLine(a);
display();
}
}

15
THANK YOU
C# and .NET

School of Computer Science and Engineering


UNIT 2 – Lecture 8
Methods Parameter Modifiers
METHODS PARAMETER MODIFIERS
• C# provides a set of parameter modifiers that control how arguments are
sent into a given method.
• Default » Value parameter (pass-by-value)
• in » New in C# 7.2, the in modifier indicates that a ref parameter
is read-only by the called method.
• out » Output parameter is assigned by called method (pass-by-
reference)
• ref » pass-by-reference
• params » Variable number of parameters within a single parameter.
Method can have only one params parameter and it
should be the last parameter

3
THE DEFAULT PARAMETER PASSING BEHAVIOUR
• The default method pass-by-value, a copy of the variable is passed into the
function
public static int Add(int x, int y)
{
int ans = x + y;
// Caller will not see these modifications.
x = 10000;
y = 88888;
return ans;
}
static void Main(string[] args)
{
int x = 9, y = 10;
Console.WriteLine("Before call: X: {0}, Y: {1}", x, y);
Console.WriteLine("Answer is: {0}", Add(x, y));
Console.WriteLine("After call: X: {0}, Y: {1}", x, y);
}
4
THE OUT MODIFIER
• 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)

5
USING THE IN MODIFIER
The in modifier passes a value by reference (for both value and reference types) and prevents the called
method from modifying the values.
static int AddReadOnly(in int x,in int y)
{
//Error CS8331 Cannot assign to variable 'in int' because it is a readonly
variable
//x = 10000;
//y = 88888;
int ans = x + y;
return ans;
}
6
THE OUT MODIFIER
• Calling a method with output parameter requires the use of out
modifier.
public static void Add(int x, int y, out int ans)
{
ans = x + y;
}
static void Main(string[] args)
{
// No need to assign local output variables.
int ans;
Add(90, 90, out ans);
Console.WriteLine("90 + 90 = {0} ", ans);
}

WAP to find area and circumference of circle using OUT modifier

7
THE OUT MODIFIER
WAP to find area and circumference of circle using OUT modifier
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter radious for circle");
double radius = double.Parse(Console.ReadLine());
double circumference = CalculateCircle(radius, out double area);
WriteLine($"Circle's circumference is {circumference}");
WriteLine($"Circle's Area is {area}");
ReadKey();
}
static double CalculateCircle(double radious, out double area)
{
area = Math.PI * Math.Pow(radius, 2);
double circumference = 2 * Math.PI * radius;
return circumference;
}
}
8
THE REF MODIFIER
1. The reference parameters are necessary when you wish to allow a method
to operate on various data points declared in the caller’s scope.
2. The distinction between output and reference parameters are
• Output parameters do not need to be initialized before they are passed to
the method. The method must assign output parameters before exiting.
• Reference parameters must be initialized before they are passed to the
method. You are passing a reference to an existing variable. If you don’t
assign it to an initial value, that would be equivalent to operating on an
unassigned local variable.

9
THE REF MODIFIER
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);
}
}

10
THE PARAMS MODIFIER
1. To achieve variable number of parameters in a Method declaration
2. The params parameter must be a single dimensional array (else you get an
error)
3. You can define any object in the parameter list

11
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]);
}
public 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
}
}

12
GENERIC USE OF PARAMS
• Instead of using only an integer list for the params parameter, we can
use an object
public class Person
{
private string name;
private byte age;
public Person(string n, byte a)
{
name = n;
age = a;
}
public void PrintPerson()
{ Console.WriteLine("{0} is {1} years old", name, age); }
}

13
PASS ANY OBJECT
public static void DisplayObjects(params object[ ] list)
{
for (int i = 0; i < list.Length; i++)
{
Output:
if (list[i] is Person) 777
((Person)list[i]).PrintPerson(); John is 45 years old
else Instance of System.String

Console.WriteLine(list[i]);
}
Console.WriteLine();
}
Calling Program:
Person p = new Person("John", 45);
DisplayObjects(777, p, "Instance of System.String");

14
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
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);
}
15
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);
}

16
CALLING PROGRAM
// Pass by Value
Console.WriteLine("Passing By Value...........");
Person geetha = new Person("Geetha", 25);
geetha.PrintPerson(); Passing By Value...........
Geetha is 25 years old
PersonByValue(geetha); Geetha is 60 years old
geetha.PrintPerson();

// 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();

17
ARRAY MANIPULATION IN C#
• Arrays are reference type and derive from a common base class System.Array
• Memory for arrays is allocated in heap and .NET arrays have a lower bound of
zero.
• Example
1. string [ ] strArray = new string[10]; // string array
2. int [ ] intArray = new int [10]; // integer array
3. Person[ ] Staff = new Person[2]; // object array
4. strAarray[0] = “REVA"; // assign some value
5. int [ ] Age = new int[3] {25, 45, 30}; // array initialization
6. int[] n3 = { 20, 22, 23, 0 }; // array initialization

18
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;
}

19
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]);
}
20
MULTIDIMENSIONAL ARRAYS
• Rectangular Array
1. int[ , ] myMatrix; // declare a rectangular array
2. int[ , ] myMatrix = new int[2, 2] { { 1, 2 }, { 3, 4 } }; // initialize
3. myMatrix[1,2] = 45; // access a cell
• Jagged Array
1. int[ ][ ] myJaggedArr = new int[2][ ]; // 2 rows and variable columns
2. 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

21
MULTIDIMENSIONAL ARRAYS
static void Main(string[] args)
{
int[][] myJagArray = new int[5][];
for (int i = 0; i < myJagArray.Length; i++)
myJagArray[i] = new int[i + 7];
Console.Write(“***** A jagged MD array *****\n\n” );
for(int i = 0; i < 5; i++){
Console.Write("Length of row {0} is {1} :\t", i, myJagArray[i].Length);
for(int j = 0; j < myJagArray[i].Length; j++)
Console.Write(myJagArray[i][j] + " ");
Console.WriteLine();
}
}
22
MULTIDIMENSIONAL ARRAYS

23
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 index
SetValue( )
Reverse( ) Reverses the contents of one-dimensional array
Sort( ) Sorts a one-dimensional array

24
SYSTEM.ARRAY BASE CLASS: ENUMERATOR EXAPMLE
GetEnumerator() −This method returns an enumerator that iterates through a collection.

public class SamplesArray {


public static void Main() { OUTPUT:
String[] myArr = new String[10]; The Array contains the following values:
myArr[0] = "The"; [0] The
myArr[1] = "quick"; [1] quick
myArr[2] = "brown"; [2] brown
myArr[3] = "fox"; [3] fox
myArr[4] = "jumps"; [4] jumps
myArr[5] = "over"; [5] over
myArr[6] = "the"; [6] the
myArr[7] = "lazy"; [7] lazy
myArr[8] = "dog"; [8] dog
int i = 0;
System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
Console.WriteLine( "The Array contains the following values:" );
while (( myEnumerator.MoveNext() ) && ( myEnumerator.Current != null ))
Console.WriteLine( "[{0}] {1}", i++, myEnumerator.Current );
}}

25
THANK YOU
C# and .NET

School of Computer Science and Engineering


UNIT 2 – Lecture 9
String Manipulation in C#
STRING MANIPULATIONS IN C#
• A string is a sequential collection of Unicode characters, typically used to
represent text.
• String class 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,

3
STRING MANIPULATIONS IN C#
• 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(97)' greater than ‘A(65)'.

4
STRING MANIPULATIONS IN C#
• 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

5
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

6
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();

7
MORE STRING METHODS
CompareTo method is an instance method of string class. It compares a value (either a string or on
object) with a string instance
1. public class StringExample
Return 2. {
Meaning
value 3. public static void Main(string[] args)
Less than The first string precedes the 4. {
0 second string in the sort order. 5. string s1 = "hello";
6. string s2 = "hello";
0 Both strings are equal in value.
7. string s3 = "csharp";
Geater The first string follows the 8. Console.WriteLine(s1.CompareTo(s2));
than 0 second string in the sort order. 9. Console.WriteLine(s2.CompareTo(s3));
10. }
11. }

Output:
0
1

8
SYSTEM.TEXT.STRINGBUILDER

1. Like Java, C# strings are immutable(unmodifiable). This means, strings


can not be modified once established
2. 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
3. It is not efficient, sometimes, to work on copies of strings – solution?
Use StringBuilder from System.Text!

9
EXAMPLE
class StringDemo {
public static void concat1(String s1) Output:
{String st = “University"; Using String Class: REVA
s1 = String.Concat(s1, st); Using StringBuilder Class: REVAUniversity
}
public static void concat2(StringBuilder s2)
StringBuilder is used to represent
{s2.Append(“University");
a mutable string of characters. Mutable
}
means the string which can be changed.
public static void Main(String[] args)
It will not create a new modified
{
instance of the current string object but
String s1 = “REVA";
do the modifications in the existing
concat1(s1); // s1 is not changed
string object.
Console.WriteLine("Using String Class: " + s1);
String objects are immutable but
StringBuilder s2 = new StringBuilder(“REVA");
StringBuilder is the mutable string type.
concat2(s2); // s2 is changed
Console.WriteLine("Using StringBuilder Class: " + s2);
}}

10
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);
}
}
11
ENUMERATIONS IN C#
• It is a user-defined value type used • The internal type used for
• to represent a list of named integer constants.
enumeration is System.Int32
• Mapping symbolic names to numerals
• 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
}
12
ENUMERATIONS IN C#
• Enumerations do not necessarily need to follow a enum Colors
sequential order. {
Red = 10,
Green = 15,
Blue = 20
}

• If you want to set the underlying storage value of enum Colors : byte
Colors to be a byte rather than an int, you would do {
it as follows Red = 10,
Green = 15,
• C# enumerations can be defined in a similar Blue = 20
manner for any of the numerical types (byte, sbyte, }
short, ushort, int, uint, long, or ulong).

13
THE SYSTEM.ENUM BASE CLASS
.NET enumerations is that they implicitly derive from System.Enum.

Format() Converts a value of an enumerated type to its string equivalent


GetName() Retrieves the name for the constant in the enumeration
Returns the type of enumeration
GetUnderlyingType()
Console.WriteLine(Enum.GetUnderlyingType(typeof (Colors))); // System.Int32
GetValues() Gives an array of values of the constants in enumeration
To check whether a constant exists in enum
IsDefined()
if (Enum.IsDefined(typeof(Colors), "Blue") ….
Converts string/value to enum object
Parse()
Colors CarColor = (Colors)Enum.Parse(typeof(Colors), "Red");

14
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

15
UNDERSTANDING C# NULLABLE TYPES

// Compiler errors!
// Value types cannot be set to null!
bool myBool = null;
int myInt = null;

C# supports the concept of nullable data types. Simply put, a nullable type can
represent all the values of its underlying type, plus the value null. Thus, if you
declare a nullable bool, it could be assigned a value from the set {true, false, null}.

16
UNDERSTANDING C# NULLABLE TYPES

static void LocalNullableVariables()


{
// Define some local nullable variables.
int? nullableInt = 10;
double? nullableDouble = 3.14;
bool? nullableBool = null;
char? nullableChar = 'a';
int?[] arrayOfNullableInts = new int?[10];
}
17
UNDERSTANDING TUPLES
Tuples are lightweight data structures that contain multiple fields.

(string, int, string) values = ("a", 5, "c");


var values = ("a", 5, "c");

Console.WriteLine($"First item: {values.Item1}");


Console.WriteLine($"Second item: {values.Item2}");
Console.WriteLine($"Third item: {values.Item3}");

18
UNDERSTANDING TUPLES
Specific names can also be added to each property in the tuple on either the right side or the left side of
the statement. While it is not a compiler error to assign names on both sides of the statement, if you do,
the right side will be ignored, and only the left-side names are used.
(string FirstLetter, int TheNumber, string SecondLetter) valuesWithNames = ("a", 5, "c");
var valuesWithNames = (FirstLetter: "a", TheNumber: 5, SecondLetter: "c");

Console.WriteLine($"First item: {valuesWithNames.FirstLetter}");


Console.WriteLine($"Second item: {valuesWithNames.TheNumber}");
Console.WriteLine($"Third item: {valuesWithNames.SecondLetter}");
//Using the item notation still works!
Console.WriteLine($"First item: {valuesWithNames.Item1}");
Console.WriteLine($"Second item: {valuesWithNames.Item2}");
Console.WriteLine($"Third item: {valuesWithNames.Item3}");

19
THANK YOU

You might also like