Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Shriram Institute of Information Technology, Paniv

Unit – III
Objects and Types
Class –
A class combines the fields and methods (member function which defines actions) into a single unit. A
class is a way to bind data and its associated function together. A class is a template for an object and an object
is an instance of a class. C# is a true object-oriented language & therefore the underlying structure of all c#
programs is classes. A class provides a definition for dynamically created instances of the class, also known
as objects. Classes support inheritance and polymorphism, mechanisms whereby derived classes can extend and
specialize base classes.
➢ Declaration of Class -
A class declaration consists of a class header and body. The class header includes attributes, modifiers,
and the class keyword. The class body encapsulates the members of the class, which are the data members and
member functions. A class is a user-defined data type with a template that serves to define its properties.
Classes are declared by using the class keyword.

Syntax:-

class classname

[Variable declaration;]

[Methods declaration;]

}
Here, class is a keyword and classname is any valid c# identifier. Everything inside the square brackets is
optional.

A c# class may include many more items, such as properties, indexers, constructors, destructors and operators.

➢ Creating Object -
Object is instance of class. An object in c# is essentially a block of memory that contains space to store
all the instance variables. Creating an object is also referred to as instantiating an object.

Objects in c# are created using new operator. A new operator creates objects of the specified class and
returns a reference to that object.

Syntax -
<Class_name> <object_name>;

<object_name>=new <class_name>();

Prof. Honrao Charushila Prakash (1 )


Shriram Institute of Information Technology, Paniv

OR

<class_name> <object_name> = new <class_name> ();

Here is an example of creating an object of type Rectangle.


Rectangle rect; //declare
rect = new Rectangle (); //instantiate
Here first statement declares a variable to hold the object reference (address) and the second one
actually assigns the reference to the variable. The variable rect is now an object of the Rectangle class.
The new operator allocates memory dynamically and assigns reference of this location to
variable of type class.
Both statements can be combined into one as:-
Rectangle rect = new Rectangle ();
The object rect does not contains the value for the Rectangle object; it contains only the
reference (i.e. address) to the object.
The method Rectangle () is the default constructor of the class.

Action Statement Result

Declare Rectangle rect; Null rect

Declare rect = new Rectangle (); rect

Rectangle
Object

Fig.:- Creating objects references.

Each object has its own copy of the instance variable of its class. This means that any changes to the
variables of one object have no effect on the variable of another.

We can also assign an object to an object, like the following-


Rectangle r1 = new Rectangle ();

Rectangle r2 = r1;

Prof. Honrao Charushila Prakash (2 )


Shriram Institute of Information Technology, Paniv

r1

Rectangle
r2 Object

Here, both r1 and r2 refer to the same object. Any changes made to one object will be reflected in the
other objects.
➢ Accessing class member –
Each object contains its own set of variables. We should assign values to these variables in order to use
them in program. All variables must be assigned values before they are used.
Since we can’t access the instance variables & methods outside the class directly to do this we must use
the concerned object & the dot (.) operator.

Syntax:
objectname.variablename;

objectname.methodname (parameter list);

Here objectname is the name of the object, variablename is the name of the instance variable inside the
object that we wish to access, methodname is the method that we wish to call & parameter list is the comma
separated list of actual values that must match in type & number with the parameter list of the methodname
declared in the class.

Example:-

Rectangle rect1= new Rectangle ();

rect1.getdata (15, 10);

Program –
using System;
namespace ClassObject
{
class Sample
{
public int a, b;
public void getdata(int x, int y)
{
a = x;
b = y;
}

Prof. Honrao Charushila Prakash (3 )


Shriram Institute of Information Technology, Paniv

public void display()


{
int c = a + b;
Console.WriteLine("Addition is: " + c);
}
}
class Program
{
static void Main(string[] args)
{
int n, m;
Console.Write("Enter First Number: ");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Second Number: ");
m = Convert.ToInt32(Console.ReadLine());
Sample s = new Sample();
s.getdata(n, m);
s.display();
Console.ReadLine();
}
}
}

Output -
Enter First Number: 5
Enter Second Number: 20
Addition is: 25

Class Member –
Classes have members that represent their data and behavior. A class's members include all the members
declared in the class. The fields and methods (member function which defines actions) inside classes are
referred class members.
1) Fields - Variables inside the class are called as field and that you can access them by creating an object of
the class, and by using the dot syntax (.)
Syntax –
Objectname.field;
Example –
Sample s=New Sample();
s.num;
Program –
using System;
namespace ClassObject
{

Prof. Honrao Charushila Prakash (4 )


Shriram Institute of Information Technology, Paniv

class Book
{
public int a = 10;
public string str = "Visual Programming";
};

class Program
{
static void Main(string[] args)
{
Book b = new Book();
Console.WriteLine("Book Id: "+b.a);
Console.WriteLine("Book Name: "+b.str);
Console.ReadLine();
}
}
}

Output –

Book Id: 10
Book Name: Visual Programming

2) Methods –
Methods define the actions that a class can perform. Methods can take parameters that provide input
data, and can return output data through parameters. Methods can also return a value directly, without using a
parameter.
Program –
using System;
namespace Passtech
{
class sample
{
public int square(int a)
{
return a * a;
}
public void show()
{
Console.WriteLine("Welcome in Method member of class");
}
}
class Program
{

static void Main(string[] args)


{
int n,result;

Prof. Honrao Charushila Prakash (5 )


Shriram Institute of Information Technology, Paniv

Console.Write("Enter Number: ");


n = Convert.ToInt32(Console.ReadLine());
sample s = new sample();
s.show();
result = s.square(n);
Console.WriteLine("Square is: " + result);
Console.ReadLine();
}
}
}

Output –
Enter Number: 5
Welcome in Method member of class
Square is: 25

Read only Field –


➢ Readonly fields prevent fields from being change. This means, the value of readonly fields cannot be
modified after they are been initialized.

➢ Readonly keyword is different from the const keyword. A const field can only be initialized at the
declaration time of the field. A readonly field can be initialized either at the declaration or in a
constructor.
➢ Readonly field is commonly used when user wants initialize value to field at run time in constructor.

➢ Readonly fields are declared with the readonly keyword.

➢ The value of readonly keyword set at declaration or in constructor of its containing class.

➢ An attempt to set its value from any other location causes a compilation error.

➢ Readonly field’s value can’t be changed, except during construction at run time.

➢ Readonly fields can be static or instance values.

Syntax –

<Access_specifier> readonly <data type> variable_name=value;

Example -

using System;
namespace readonlyExample
{

class Program

Prof. Honrao Charushila Prakash (6 )


Shriram Institute of Information Technology, Paniv

{
public readonly int a = 10;
public readonly int b;
public int c;
public Program()
{
b = 20;
}
public Program(int x, int y,int z)
{
a = x;
b = y;
c = z;
}

static void Main(string[] args)


{
Program p = new Program(5,4,6);
Console.WriteLine("a = {0} b = {1} c = {2}", p.a, p.b,p.c);
Program p1 = new Program();
p1.c = 50;
Console.WriteLine("a = {0} b = {1} c = {2}", p1.a, p1.b,p1.c);
Console.ReadLine();
}
}
}

Output -
a=5 b=4 c=6

a = 10 b = 20 c = 50

Properties -
➢ Properties are special member of a class provides an easy way to read or write the value of private data
member.

➢ Fields are data member of a class. Properties are extension to field & can be accessed using the same
syntax.

➢ Fields are by default private and hence inaccessible outside the class.

➢ Some or all of these data member can be accessed from outside the class with the help of special method
called properties. So poperties are also called as ‘smart field’.

➢ Unlike fields, properties do not denote storage location. Instead, properties have accessors that specify
the statements to be executed when their values are read or written.

Prof. Honrao Charushila Prakash (7 )


Shriram Institute of Information Technology, Paniv

Syntax –

Public <propertyType> <propertyName>

get

return fieldname;

set

fieldname = value;
}

}
Where,
➢ Properties has two access specifier
a) get: - The get accessors retrives data member values.

b) set: - The set accessors sets the value of a property and is similar to a method that return void. The
set accessor automatically receives a parameter called value, that contains the value being assigned
to the property.
Example –

using System;

namespace readonlyExample
{
class smaple
{
private int num;

public int Anum


{
get
{
return num;
}
set
{
if (num >= 0)
{
num = value;
}

Prof. Honrao Charushila Prakash (8 )


Shriram Institute of Information Technology, Paniv

}
}
}
class Program
{
static void Main(string[] args)
{
smaple s = new smaple();
s.Anum = 100;
int a = s.Anum;
Console.WriteLine("Value is: "+a);
Console.ReadLine();
}
}
}

Output –

Value is: 100

➢ Features of properties:-

1. Property do not have same name as that of underlying data member.

2. If only get is specified, then the property becomes a read only property.

3. If only set is specified, then the property becomes a write only property.

4. If both are specified, then the property is read/write property.

5. Property are not variable and therefore can’t be passed as ref & out parameter.

6. Properties can be static or instance property.


Indexer –
➢ Indexer are location indicator and are used to access class objects, just like accessing elements in an
array. They are usefull in cases where a class is a container for other objects.
➢ Indexers takes an index arguments and looks like an array.
➢ Indexers are declared using the name this.
➢ The indexers are usually known as ‘smart array’.
➢ Defining C# indexer is much like defining a properties, except that their accessors take parameters.
➢ We can say that an indexer is a member that enables an object to be indexed in the same way as an
array.
➢ Indexers have two accessors:-
a) get:-
The get accessor retives array elements of specified index position.
b) set:-
The set accessor sets the value at specified index position in an array.

Prof. Honrao Charushila Prakash (9 )


Shriram Institute of Information Technology, Paniv

➢ Indexers are instance member of a class.


➢ Indexers are never static in C#.
➢ One class can hve only one indexer.
➢ The return type can be any valid C# types.
➢ Indexer in C# must have at least one parameter, else the compiler will generate a compilation error.
➢ Indexer allow us to use a class as an array and enable an object to access the array elements of class.

Syntax:-
Public type this [int index]
{
get
{
Return collection_name [index];
}
Set
{
Collection_name [index] = value;
}
}
The this keyword shows that, the object is of the current class.
Example –
using System;
namespace EgIndexer
{
class Sample
{
private string[] str=new string[3];

public string this[int index]


{
get
{
return str[index];
}
set
{
str[index] = value;
}
}
}
class Program
{
static void Main(string[] args)

Prof. Honrao Charushila Prakash (10 )


Shriram Institute of Information Technology, Paniv

{
Sample s = new Sample();
s[0] = "CPP";
s[1] = "DS";
s[2] = "VP";
Console.WriteLine("String are: ");
Console.WriteLine(s[0]);
Console.WriteLine(s[1]);
Console.WriteLine(s[2]);
Console.ReadLine();
}
}
}

Output -

String are:

CPP

DS

VP
Comparison of Indexer and Properties –

Properties Indexer

1. Properties are declared by giving a unique name. Indexers are declared without giving a name.

2. Properties are identified by the names While indexers are identified by the signatures.

Properties can be declared as a static or an Indexers are always declared as instance member,
3.
instance member. never as static member.

Properties are invoked through a described Indexers are invoked using an index of the created
4.
name. object.

A property does not needs this keyword in their


5. Indexers need this keyword in their keyword.
creation.

A get accessor of a property does not have any A get accessor of a property contains the list of
6.
parameters. same proper parameters as indexers.
A set accessor of an indexer has the same
A set accessor of a property contains the
7. formal parameter list as the indexer, in
implicit value parameter
addition to the value parameter.

Prof. Honrao Charushila Prakash (11 )


Shriram Institute of Information Technology, Paniv

The Object Class –

The Object class is the base class for all the classes in .Net Framework. It is present in
the System namespace. In C#, the .NET Base Class Library (BCL) has a language-specific alias which is
Object class with the fully qualified name as System.Object. Every class in C# is directly or indirectly derived
from the Object class. If a Class does not extend any other class then it is the direct child class of Object class
and if extends other class then it is an indirectly derived. Therefore the Object class methods are available to all
C# classes. Hence Object class acts as a root of the inheritance hierarchy in any C# Program. The main purpose
of the Object class is to provide the low-level services to derived classes.

There are two types in C# i.e Reference types and Value types.

Here, you can see the Object class at the top of the type hierarchy. Class 1 and Class 2 are the reference
types. Class 1 is directly inheriting the Object class while Class 2 is indirectly inheriting by using Class 1.
Struct1 is value type that implicitly inheriting the Object class through the System.ValueType type.

Example -
using System;

namespace readonlyExample
{
class Program
{
static void Main(string[] args)
{
Object obj1 = new Object();
int i = 10;
Type t1 = i.GetType();

Prof. Honrao Charushila Prakash (12 )


Shriram Institute of Information Technology, Paniv

Console.WriteLine("For Integer type: ");


Console.WriteLine(t1.BaseType);
Console.WriteLine(t1.Name);
Console.WriteLine(t1.FullName);
Console.WriteLine(t1.Namespace);
Console.ReadLine();
}
}
}

Output –
For Integer type:
System.ValueType
Int32
System.Int32
System

Object Method –
All the types in .NET are represented as objects and are derived from the Object class. The
Object class has following methods:
1) GetType() – It return the type of object at runtime.
2) Equals() – This method is used to compare two object instances. It return true if both object instance are
equal otherwise it return false.
3) ToString() – It used to convert an object instance to string type.
4) Finalize() - Allows an object to try to free resources and perform other cleanup operations before it is
reclaimed by garbage collection.
5) GetHashCode() - Return the hash code associated with the invoking object.
6) Equal(object obj1, object obj2) – to determine whether obj1 is the same as obj2.

Example –
using System;
namespace readonlyExample
{
class Program
{
static void Main(string[] args)
{
string s1 = "Visual";
String s2 = "Visual";

Prof. Honrao Charushila Prakash (13 )


Shriram Institute of Information Technology, Paniv

Console.WriteLine(Object.Equals(s1, s2));
Console.ReadLine();
}
}
}

Output -
True
Or
Example (GetHashCode) –
using System;
namespace readonlyExample
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine("Hash Code is: "+p.GetHashCode());
Console.ReadLine();
}
}
}

Output -
Hash Code is: 22008501

ToString() Method –
ToString() method is the major formatting method in the .NET Framework. It converts an object
to its string representation so that it is suitable for display.
➢ The default Object.ToString() method –
The default implementation of the ToString() method returns the fully qualified name of the type
of the Object, as the following example shows.
Example –
using System;

Prof. Honrao Charushila Prakash (14 )


Shriram Institute of Information Technology, Paniv

namespace readonlyExample
{

class Program
{
static void Main(string[] args)
{
Object obj = new Object();
Console.WriteLine(obj.ToString());
Console.ReadLine();
}
}
}

Output -
System.Object

Or Use Object class –


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace readonlyExample
{
public class Object1
{
}
class Program
{
static void Main(string[] args)
{
Object1 obj = new Object1();
Console.WriteLine(obj.ToString());
Console.ReadLine();
}
}
}

Output –
readonlyExample.Object1
(Here readonlyExample is namespace name of program)

Prof. Honrao Charushila Prakash (15 )

You might also like