C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II...

28
C# Programming - Unit II Class Fundamentals A class is a template that defines the form of an object. It specifies both the data and the code that will operate on that data. C# uses a class specification to construct objects. Objects are instances of a class. A class is created by use of the keyword class. Here is the general form of a simple class definition that contains only instance variables and methods: Syntax class classname { // declare instance variables access type var1; access type var2; // ... access type varN; // declare methods access ret-type method1(parameters) { // body of method } access ret-type method2(parameters) { // body of method } // ... access ret-type methodN(parameters) { // body of method } }

Transcript of C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II...

Page 1: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

C# Programming - Unit – II

Class Fundamentals

A class is a template that defines the form of an object. It specifies both the data and the code

that will operate on that data. C# uses a class specification to construct objects. Objects are

instances of a class.

A class is created by use of the keyword class. Here is the general form of a simple class

definition that contains only instance variables and methods:

Syntax

class classname {

// declare instance variables

access type var1;

access type var2;

// ...

access type varN;

// declare methods

access ret-type method1(parameters) {

// body of method

}

access ret-type method2(parameters) {

// body of method

}

// ...

access ret-type methodN(parameters) {

// body of method

}

}

Page 2: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Example

using System;

namespace BoxApplication

{

class Box

{

public double length; // Length of a box

public double breadth; // Breadth of a box

public double height; // Height of a box

}

class Boxtester

{

static void Main(string[] args)

{

Box Box1 = new Box(); // Declare Box1 of type Box

Box Box2 = new Box(); // Declare Box2 of type Box

double volume = 0.0; // Store the volume of a box here

Box1.height = 5.0;

Box1.length = 6.0;

Box1.breadth = 7.0;

// box 2 specification

Box2.height = 10.0;

Box2.length = 12.0;

Box2.breadth = 13.0;

// volume of box 1

Page 3: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

volume = Box1.height * Box1.length * Box1.breadth;

Console.WriteLine("Volume of Box1 : {0}", volume);

// volume of box 2

volume = Box2.height * Box2.length * Box2.breadth;

Console.WriteLine("Volume of Box2 : {0}", volume);

Console.ReadKey();

}

}

}

How Objects Are Created

In the preceding programs, the following line was used to declare an object of type Building:

Building house = new Building();

This declaration performs three functions. First, it declares a variable called house of the class

type Building. This variable is not, itself, an object. Instead, it is simply a variable that can refer

to an object. Second, the declaration creates an actual, physical copy of the object.

Reference Variables and Assignment

In an assignment operation, reference variables act differently than do variables of a value type,

such as int. When you assign one value type variable to another, the situation is straightforward.

The variable on the left receives a copy of the value of the variable on the right. When you assign

one object reference variable to another, the situation is a bit more complicated because the

assignment causes the reference variable on the left to refer to the same object to which the

reference variable on the right refers. The object, itself, is not copied. The effect of this

difference can cause some counterintuitive results. For example, consider the following

fragment:

Page 4: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Building house1 = new Building();

Building house2 = house1;

house1.Area = 2600;

Console.WriteLine(house1.Area);

Console.WriteLine(house2.Area);

display the same value: 2600.

Although house1 and house2 both refer to the same object, they are not linked in any other way.

For example, a subsequent assignment to house2 simply changes what object house2 refers to.

For example:

Building house1 = new Building();

Building house2 = house1;

Building house3 = new Building();

house2 = house3; // now house2 and house3 refer to the same object.

C# Constructors

A class constructor is a special member function of a class that is executed whenever we create

new objects of that class.

A constructor has exactly the same name as that of the class and it does not have any return type.

Following example explains the concept of constructor:

Rules:

1. Class name and method name should be same

2. It has not return type

3. It is should be declared inside public.

Types

1. Default constructor

2. Parameterized constructor

using System;

namespace LineApplication

{

Page 5: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

class Line

{

private double length; // Length of a line

public Line()

{

Console.WriteLine("Object is being created");

}

public void setLength( double len )

{

length = len;

}

public double getLength()

{

return length;

}

static void Main(string[] args)

{

Line line = new Line();

// set line length

line.setLength(6.0);

Console.WriteLine("Length of line : {0}", line.getLength());

Console.ReadKey();

}

}

}

Page 6: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Output

Object is being created

Length of line : 6

A default constructor

A default constructor does not have any parameter but if you need, a constructor can have

parameters. Such constructors are called parameterized constructors. This technique helps you to

assign initial value to an object at the time of its creation as shown in the following example:

using System;

namespace LineApplication

{

class Line

{

private double length; // Length of a line

public Line(double len) //Parameterized constructor

{

Console.WriteLine("Object is being created, length = {0}", len);

length = len;

}

public void setLength( double len )

{

length = len;

}

public double getLength()

{

Page 7: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

return length;

}

static void Main(string[] args)

{

Line line = new Line(10.0);

Console.WriteLine("Length of line : {0}", line.getLength());

// set line length

line.setLength(6.0);

Console.WriteLine("Length of line : {0}", line.getLength());

Console.ReadKey();

}

}

}

Output

Object is being created, length = 10

Length of line : 10

C# Destructors

A destructor is a special member function of a class that is executed whenever an object of its

class goes out of scope. A destructor has exactly the same name as that of the class with a

prefixed tilde (~) and it can neither return a value nor can it take any parameters.

using System;

namespace LineApplication

{

class Line

{

private double length; // Length of a line

Page 8: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

public Line() // constructor

{

Console.WriteLine("Object is being created");

}

~Line() //destructor

{

Console.WriteLine("Object is being deleted");

}

public void setLength( double len )

{

length = len;

}

public double getLength()

{

return length;

}

static void Main(string[] args)

{

Line line = new Line();

// set line length

line.setLength(6.0);

Console.WriteLine("Length of line : {0}", line.getLength());

}

}

}

Page 9: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Output

Object is being created

Length of line : 6

Object is being deleted

new Operator

Class-name is the name of the class that is being instantiated. The class name followed by

parentheses specifies the constructor for the class. If a class does not define its own constructor,

new will use the default constructor supplied by C#. Thus, new can be used to create an object of

any class type.

new class-name(arg-list)

Using new with Value Types

There is no need to explicitly allocate this memory using new. Conversely, a reference variable

stores a reference to an object. The memory to hold this object must be allocated dynamically,

during execution.

Not making the fundamental types, such int or char, into reference types greatly improves your

program’s performance. When using a reference type, there is a layer of indirection that adds

overhead to each object access. This layer of indirection is avoided by a value type.

Example

using System;

class newValue {

static void Main() {

int i = new int(); // initialize i to zero

Console.WriteLine("The value of i is: " + i);

}

}

Page 10: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

The this Keyword

When a method is called, it is automatically passed a reference to the invoking object (that is, the

object on which the method is called). This reference is called this.

using System;

class Rect {

public int Width;

public int Height;

public Rect(int w, int h) {

this.Width = w;

this.Height = h;

}

public int Area() {

return this.Width * this.Height;

}

}

class UseRect {

static void Main() {

Rect r1 = new Rect(4, 5);

Rect r2 = new Rect(7, 9);

Console.WriteLine("Area of r1: " + r1.Area());

Console.WriteLine("Area of r2: " + r2.Area());

}

}

Page 11: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Arrays

An array stores a fixed-size sequential collection of elements of the same type. An array is used

to store a collection of data, but it is often more useful to think of an array as a collection of

variables of the same type stored at contiguous memory locations.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you

declare one array variable such as numbers and use numbers[0], numbers[1], and ...,

numbers[99] to represent individual variables. A specific element in an array is accessed by an

index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first

element and the highest address to the last element.

Declaring Arrays

To declare an array in C#, you can use the following syntax:

datatype[] arrayName;

where,

datatype is used to specify the type of elements in the array.

[ ] specifies the rank of the array. The rank specifies the size of the array.

arrayName specifies the name of the array.

Example

double[] balance;

Initializing an Array

Declaring an array does not initialize the array in the memory. When the array variable is

initialized, you can assign values to the array.

Array is a reference type, so you need to use the new keyword to create an instance of the array.

For example,

double[] balance = new double[10];

Page 12: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Assigning Values to an Array

You can assign values to individual array elements, by using the index number, like:

double[] balance = new double[10];

balance[0] = 4500.0;

You can assign values to the array at the time of declaration as shown:

double[] balance = { 2340.0, 4523.69, 3421.0};

You can also create and initialize an array as shown:

int [] marks = new int[5] { 99, 98, 92, 97, 95};

You may also omit the size of the array as shown:

int [] marks = new int[] { 99, 98, 92, 97, 95};

You can copy an array variable into another target array variable. In such case, both the target

and source point to the same memory location:

int [] marks = new int[] { 99, 98, 92, 97, 95};

int[] score = marks;

When you create an array, C# compiler implicitly initializes each array element to a default value

depending on the array type. For example, for an int array all elements are initialized to 0.

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the

element within square brackets after the name of the array. For example,

double salary = balance[9];

Example

using System;

namespace ArrayApplication

{

class MyArray

{

Page 13: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

static void Main(string[] args)

{

int [] n = new int[10]; /* n is an array of 10 integers */

int i,j;

/* initialize elements of array n */

for ( i = 0; i < 10; i++ )

{

n[ i ] = i + 100;

}

/* output each array element's value */

for (j = 0; j < 10; j++ )

{

Console.WriteLine("Element[{0}] = {1}", j, n[j]);

}

Console.ReadKey();

}

}

}

Output

Element[0] = 100

Element[1] = 101

Element[2] = 102

Element[3] = 103

Element[4] = 104

Element[5] = 105

Page 14: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Element[6] = 106

Element[7] = 107

Element[8] = 108

Element[9] = 109

Multidimensional Arrays

C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array.

You can declare a 2-dimensional array of strings as:

string [,] names;

or, a 3-dimensional array of int variables as:

int [ , , ] m;

Two-Dimensional Arrays

The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional

array is a list of one-dimensional arrays.

A 2-dimensional array can be thought of as a table, which has x number of rows and y number of

columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns:

Page 15: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Initializing Two-Dimensional Arrays

Multidimensional arrays may be initialized by specifying bracketed values for each row. The

following array is with 3 rows and each row has 4 columns.

int [,] a = int [3,4] = {

{0, 1, 2, 3} , /* initializers for row indexed by 0 */

{4, 5, 6, 7} , /* initializers for row indexed by 1 */

{8, 9, 10, 11} /* initializers for row indexed by 2 */

};

Accessing Two-Dimensional Array Elements

An element in 2-dimensional array is accessed by using the subscripts.That is, row index and

column index of the array. For example,

int val = a[2,3];

Example

using System;

namespace ArrayApplication

{

class MyArray

{

static void Main(string[] args)

{

/* an array with 5 rows and 2 columns*/

int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };

Page 16: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

int i, j;

/* output each array element's value */

for (i = 0; i < 5; i++)

{

for (j = 0; j < 2; j++)

{

Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);

}

}

Console.ReadKey();

}

}

}

Output

a[0,0]: 0

a[0,1]: 0

a[1,0]: 1

a[1,1]: 2

a[2,0]: 2

a[2,1]: 4

a[3,0]: 3

a[3,1]: 6

a[4,0]: 4

a[4,1]: 8

Page 17: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Jagged Arrays

A Jagged array is an array of arrays. You can declare a jagged array named scores of type int as:

int [][] scores;

Declaring an array, does not create the array in memory. To create the above array:

int[][] scores = new int[5][];

for (int i = 0; i < scores.Length; i++)

{

scores[i] = new int[4];

}

You can initialize a jagged array as:

int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};

Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers and

scores[1] is an array of 4 integers.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Jaggedarray

{

class Program

{

static void Main(string[] args)

{

int[][] jarr = new int[3][];

Page 18: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

int s = 0;

for (int i = 0; i < 3; i++)

{

Console.WriteLine("Enter the Size of the Array" +(i + 1));

int n = int.Parse(Console.ReadLine());

jarr[i] = new int[n];

Console.WriteLine("Enter the Values of Array " +(i + 1));

for (int j = 0; j < n; j++)

{

jarr[i][j] = int.Parse(Console.ReadLine());

s = s + jarr[i][j];

}

n = n + 0;

}

Console.WriteLine("Sum= " + s);

Console.ReadLine();

}

}

}

Output

Page 19: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Assigning Array References

As with other objects, when you assign one array reference variable to another, you are simply

making both variables refer to the same array. You are neither causing a copy of the array to be

created, nor are you causing the contents of one array to be copied to the other.

Example

// Assigning array reference variables.

using System;

class AssignARef

{

static void Main()

{

int i;

int[] nums1 = new int[10];

int[] nums2 = new int[10];

for(i=0; i < 10; i++) nums1[i] = i;

for(i=0; i < 10; i++) nums2[i] = -i;

Console.Write("Here is nums1: ");

for(i=0; i < 10; i++)

Console.Write(nums1[i] + " ");

Console.WriteLine();

Console.Write("Here is nums2: ");

for(i=0; i < 10; i++)

Console.Write(nums2[i] + " ");

Console.WriteLine();

nums2 = nums1; // now nums2 refers to nums1

Console.Write("Here is nums2 after assignment: ");

Page 20: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

for(i=0; i < 10; i++)

Console.Write(nums2[i] + " ");

Console.WriteLine();

// Next, operate on nums1 array through nums2.

nums2[3] = 99;

Console.Write("Here is nums1 after change through nums2: ");

for(i=0; i < 10; i++)

Console.Write(nums1[i] + " ");

Console.WriteLine();

}

}

Output

Here is nums1: 0 1 2 3 4 5 6 7 8 9

Here is nums2: 0 -1 -2 -3 -4 -5 -6 -7 -8 -9

Here is nums2 after assignment: 0 1 2 3 4 5 6 7 8 9

Here is nums1 after change through nums2: 0 1 2 99 4 5 6 7 8 9

Using the Length Property

Length property that contains the number of elements that an array can hold. Thus, each array

provides a means by which its length can be determined.

using System;

class LengthDemo {

static void Main() {

int[] nums = new int[10];

Console.WriteLine("Length of nums is " + nums.Length);

// Use Length to initialize nums.

Page 21: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

for(int i=0; i < nums.Length; i++)

nums[i] = i * i;

// Now use Length to display nums.

Console.Write("Here is nums: ");

for(int i=0; i < nums.Length; i++)

Console.Write(nums[i] + " ");

Console.WriteLine();

}

}

This program displays the following output:

Length of nums is 10

Here is nums: 0 1 4 9 16 25 36 49 64 81

Implicitly Typed Arrays

An implicitly typed array is declared using the keyword var, but you do not follow var with [ ].

Furthermore, the array must be initialized because it is the type of the initializers that determine

the element type of the array. All of the initializers must be of the same or compatible type. Here

is an example of an implicitly typed array:

var vals = new[] { 1, 2, 3, 4, 5 };

Here is another example. It creates a two-dimensional array of double:

var vals = new[,] { {1.1, 2.2}, {3.3, 4.4},{ 5.5, 6.6} };

// Demonstrate an implicitly typed jagged array.

using System;

class Jagged {

static void Main() {

var jagged = new[] {

new[] { 1, 2, 3, 4 },

Page 22: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

new[] { 9, 8, 7 },

new[] { 11, 12, 13, 14, 15 }

};

for(int j = 0; j < jagged.Length; j++) {

for(int i=0; i < jagged[j].Length; i++)

Console.Write(jagged[j][i] + " ");

Console.WriteLine();

}

}

}

Example

1 2 3 4

9 8 7

11 12 13 14 15

The foreach Loop

The foreach loop is used to cycle through the elements of a collection. A collection is a group of

objects. C# defines several types of collections, of which one is an array. The general form of

foreach is shown here:

foreach(type loopvar in collection) statement;

Example

// Use the foreach loop.

using System;

class ForeachDemo {

static void Main() {

int sum = 0;

int[] nums = new int[10];

Page 23: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

// Give nums some values.

for(int i = 0; i < 10; i++)

nums[i] = i;

// Use foreach to display and sum the values.

foreach(int x in nums) {

Console.WriteLine("Value is: " + x);

sum += x;

}

Console.WriteLine("Summation: " + sum);

}

}

Output

Value is: 0

Value is: 1

Value is: 2

Value is: 3

Value is: 4

Value is: 5

Value is: 6

Value is: 7

Value is: 8

Value is: 9

Summation: 45

Page 24: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Strings

In C#, you can use strings as array of characters. However, more common practice is to use the

string keyword to declare a string variable. The string keyword is an alias for theSystem.String

class.

Creating a String Object

You can create string object using one of the following methods:

By assigning a string literal to a String variable

By using a String class constructor

By using the string concatenation operator (+)

By retrieving a property or calling a method that returns a string

By calling a formatting method to convert a value or an object to its string representation

Example

using System;

namespace StringApplication

{

class Program

{

static void Main(string[] args)

{

//from string literal and string concatenation

string fname, lname;

fname = "Rowan";

lname = "Atkinson";

string fullname = fname + lname;

Console.WriteLine("Full Name: {0}", fullname);

//by using string constructor

char[] letters = { 'H', 'e', 'l', 'l','o' };

Page 25: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

string greetings = new string(letters);

Console.WriteLine("Greetings: {0}", greetings);

//methods returning string

string[] sarray = { "Hello", "From", "Tutorials", "Point" };

string message = String.Join(" ", sarray);

Console.WriteLine("Message: {0}", message);

//formatting method to convert a value

DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);

string chat = String.Format("Message sent at {0:t} on {0:D}",

waiting);

Console.WriteLine("Message: {0}", chat);

Console.ReadKey() ;

}

}

}

Output

Full Name: Rowan Atkinson

Greetings: Hello

Message: Hello From Tutorials Point

Message: Message sent at 5:58 PM on Wednesday, October 10, 2012

Page 26: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

Methods of the String Class

Comparing Strings:

using System;

namespace StringApplication

{

class StringProg

{

static void Main(string[] args)

{

string str1 = "This is test";

string str2 = "This is text";

if (String.Compare(str1, str2) == 0)

{

Console.WriteLine(str1 + " and " + str2 + " are equal.");

}

Page 27: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

else

{

Console.WriteLine(str1 + " and " + str2 + " are not equal.");

}

Console.ReadKey() ;

}

}

}

Getting a Substring:

using System;

namespace StringApplication

{

class StringProg

{

static void Main(string[] args)

{

string str = "Last night I dreamt of San Pedro";

Console.WriteLine(str);

string substr = str.Substring(23);

Console.WriteLine(substr);

}

Console.ReadKey() ;

}

}

Joining Strings:

Page 28: C# Programming - Unit II Class Fundamentals Syntax · 2019-04-19 · C# Programming - Unit – II Class Fundamentals A class is a template that defines the form of an object. It specifies

using System;

namespace StringApplication

{

class StringProg

{

static void Main(string[] args)

{

string[] starray = new string[]{"Down the way nights are dark",

"And the sun shines daily on the mountain top",

"I took a trip on a sailing ship",

"And when I reached Jamaica",

"I made a stop"};

string str = String.Join("\n", starray);

Console.WriteLine(str);

}

Console.ReadKey() ;

}

}