Professional Documents
Culture Documents
Unit - 3 VP-1
Unit - 3 VP-1
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>();
OR
Rectangle
Object
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.
Rectangle r2 = r1;
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;
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:-
Program –
using System;
namespace ClassObject
{
class Sample
{
public int a, b;
public void getdata(int x, int y)
{
a = x;
b = y;
}
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
{
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
{
Output –
Enter Number: 5
Welcome in Method member of class
Square is: 25
➢ 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.
➢ 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.
Syntax –
Example -
using System;
namespace readonlyExample
{
class Program
{
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;
}
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.
Syntax –
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;
}
}
}
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 –
➢ Features of properties:-
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.
5. Property are not variable and therefore can’t be passed as ref & out parameter.
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];
{
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 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.
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();
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";
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;
namespace readonlyExample
{
class Program
{
static void Main(string[] args)
{
Object obj = new Object();
Console.WriteLine(obj.ToString());
Console.ReadLine();
}
}
}
Output -
System.Object
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)