You are on page 1of 43

DOTNETTECHNOLOGY 2160711

UNIT-2
The Basics and Console Applications inC#
Prof. Naimish R. Vadodariya
naimish.vadodariya@darshan.ac.in
+91-8866215253

Computer Engineering Darshan Institute of Engineering &Technology


Outline
• Constructor
• Destructor
• Function Overloading
• Operator Overloading
• Modifiers
• Properties
• Indexers

Introduction to ConsoleApplication
Unit – 2 : The Basics and Console Applications in C# 2 Darshan Institute of engineering &Technology
Constructor

Constructor is a special member function of a
class that is executed whenever we create new
objects of that class.

Special method of the class that will be
automatically invoked when an instance of the
class is created is called as constructor.

Constructor will have exact same name as the
class and it does not have any return type even
void.
• Constructors are specially used to initialize data
Unit – 2m
: The
e Bm
asicb edrCosn.soleApplications in C# 3
s an Darshan Institute of engineering &Technology
Types of Constructor

Constructors can be classified as follows.
 Default Constructor

When you do not declare any constructor, the class will call
its default constructor which has a default public access
modifier.

The default constructor is a parameter less constructor
which will be called by a classobject.
 Parameterized Constructor

When an object is declared in a parameterized constructor,
the initial values have to be passed as arguments to the
constructor.

You can also call it as constructor
Unit – 2 : The Basics and Console Applications in C#
4 overloading.
Darshan Institute of engineering &Technology
Example - Constructor
class MainClass
using System; {
p u b l i c s t a t i c void Main()
{
namespace / / C a l l i n g Default Constructor
Square squreobject = new Square(); i n t
Con s tru c t or Area = squreobject.Area();
Console.WriteLine(Area);
/ / C a l l i n g Parametrized Constructor

{ Square MySquare = new Square(10);


i n t myarea = MySquare.Area();
Console.WriteLine(myarea);

class Square }
Console.ReadLine();

}
{ }

p ri v a t e Output :
i n t Side; 1
100
Unit – 2 : The Basics and Console Applications in C# 5 Darshan Institute of engineering &Technology
Example - Constructor
using System; / / co p y constructor
p u b l i c Person(Person person)
namespace Test {
m_PID = person.m_PID;
{ m_FName= person.m_FName;
m_LName= person.m_LName;
p u b l i c class Person m_City = person.m_City;
}
{ }

p r i v a t e i n t m_PID; class Program


{
p r i v a t e s t r i n g m_FName, m_LName, m_City; s t a t i c void M a i n ( s t r i n g [ ] args)
{
p u b l i c Person() Person p1 = new P e r s o n ( ) ; / / T h i s w i l l c a l l
Def ault Constructor
{ Person p2 = new Person("CENRV",
" Va d o d a riya " ); / / T h is w i l l c a l l two parameterized
m_PID = 19929; Constructor
Person p3 = new Person(p2);//This w i l l c a l l Copy
m_FName= "Naimish"; Constructor
}
m_LName= " P a t e l " ; }
}
m_City = " R a j k o t " ;

p u b l i c Person(string f irstName, s t r i n g
lastName)

Unit – 2 : Th{e Basics and Console Applications in C# 6 Darshan Institute of engineering &Technology
Destructor

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 will have exact same name as the
class prefixed with a tilde (~) and it can neither
return a value nor can it take anyparameters.

Destructor can be very useful for releasing
resources before coming out of the program like
closing files, releasing memories etc.
• Aclass can have only one destructor.
Unit – 2 : The Basics and Console Applications in C# 7 Darshan Institute of engineering &Technology
Destructor - Example
using System;
Output :
namespace Destructor

class Example

p u b l i c Example() / / D e f a u l t Constructor

Console.W riteLine("Constructor");

~Example() / / D e s t r u c t o r

Console. W r it eLine( " Dest r uct or" );

Console.ReadKey();

class Program

Unit – 2{ : The Basics and ConsoleApplications in C# 8 Darshan Institute of engineering &Technology


Constructor v/s Destructor
Constructor Destructor
Constructor is used to initialize the Destructor destroys the objects when
Purpose
instance of a class. they are no longer needed.
Constructor is Called when Destructor is called when instance of a
When Called
new instance of a class is class is deleted or released.
created.

Memory Management Constructor allocates the memory. Destructor releases the memory.

Destructor can not have any


Arguments Constructors can have arguments.
arguments.
Overloadin of Destructor is not
Overloading Overloading of constructor ispossible.
g possible.

Constructor has the same name as class Destructor also has the same name as
Name
name. class name but with (~) tiledoperator.

ClassName(Arguments) ~ ClassName()
{ {
Syntex //Body of Constructor //Body of Destructor
} }

Unit – 2 : The Basics and Console Applications in C# 9 Darshan Institute of engineering &Technology
Function (Method) Overloading

Function overloading or (method overloading) is
a programming concept that allows programmers
to define two or more functions with the same
name.

C# also allows us to define multiple functions
with the same name differing in the argument
type and order of arguments. This is termed as
function overloading.

There is no need to use any keyword while
overloading a function or method either in same
Unit – 2clhaesBassicsoanrd CionnsodleAepprliicvatieond
:T s in c
C#lass1.0 Darshan Institute of engineering &Technology
Function Overloading Cont..

In case of function or method overloading,
compiler identifies which overloaded method to
execute based on number of arguments and their
data types during compilation itself.
• Hence method overloading is an
Class example for

compile time polymorphism. Methods or Functions


with same name but
signature
(parameters) is
different

Unit – 2 : The Basics and Console Applications in C# 11 Darshan Institute of engineering &Technology
Example - Function Overloading
class add
Output :
{

p u b l i c i n t sum(int a , i n t b )

return a + b;

p u b l i c i n t sum(int a )

class Pr{ogram
{ return a + a;
p u b l i c s t a t i c void M a i n ( s t r i n g [ ] ar g s)
}
{
} add ad = new a d d ( ) ; i n t
i = ad.sum(2, 3 ) ;
Console.W riteLine("Addtion i s { 0 } " , i ) ;
i n t b = ad.sum(2);
Console.W riteLine("Addtion i s { 0 } " , b ) ;
Console.Read();

}
Unit – 2}: The Basics and Console Applications in C# 12 Darshan Institute of engineering &Technology
Operator Overloading

Each operator has predefined meaning most of them are
given additional meaning through the concept of Operator
Overloading.

‘+’ sign is used for addition
• So,‘+’ can not be used for concatenation?
– Suppose, we have String 1 = Ram & String 2 = Rahim
– Can we concat these two strings using + operator like ‘RamRahim’??

When any operator is overloaded, keep in mind that its
original meaning is not lost.

Unit – 2 : The Basics and Console Applications in C# 13 Darshan Institute of engineering &Technology
Operator Overloading Cont..

Consider an example of user defined data type int
with the operators +, -, * and / provides support
for mathematical operations.

To make operations on a user – defined data type
is difficult asthe operations are built –in.
• An operator can be overloaded by defining a
function to it.
• The function is declared using the operator
keyword.

The operator function must be static.
Unit – 2 : The Basics and Console Applications in C# 14 Darshan Institute of engineering &Technology
Operator Overloading Cont..

For example, to overload the + operator, the
following syntax is defined.

Unit – 2 : The Basics and Console Applications in C# 15 Darshan Institute of engineering &Technology
Operator Overloading Cont..
Operators Description
+, -, !, ~, ++,-- These unary operators take one operand can be overloaded
These binary operators take two operands and can
+, -, *, /, %
be overloaded
==, !=, <, >, <=, >= The comparison operators can be overloaded
The conditional logical operators cannot be overloaded
&&, | | directly and evaluated by using the & and | which can be
overloaded
+=, -=, *=, /==, %== The assignment operators cannot be overloaded
=, ? :, - >, new, sizeof, typeof These operators cannot be overloaded

Unit – 2 : The Basics and Console Applications in C# 16 Darshan Institute of engineering &Technology
Example - Operator Overloading
using System; p u b l i c void ShowResult()
namespace Demo {
Console.WriteLine(a + " , " + b + " , "
{ + c);
class c a l c u l a t i o n Console.ReadLine();
}
{ }
i n t a, b, c;
public c a l c u l a t i on () class Program
{
{ s t a t i c void M a i n ( s t r i n g [ ] args)
a = b = c = 0; {
c a l c u l a t i o n i = new c a l c u l a t i o n ( 1 0 , 20, 3 0 ) ;
}
i++;
public c a l c u l a t i o n ( i n t x , i n t y , i n t z) i.ShowResult();
Console.ReadLine();
{
}
a = x; }
b = y; }
c = z;

}
Output :
p u b l i c s t a t i c c a l c u l a t i o n operator
+ + ( ca l cu l at i o n op1)
{
op1. a++;
op1. b++;
op1.c++;

Unit – 2 : The Bar esitcusr annodp1C;onsoleApplications in C# 17 Darshan Institute of engineering &Technology


Example - Operator Overloading
using System; class Program
{
s t a t i c void M a i n ( s t r i n g [ ] args)
namespace Test {
{ Distance d1 = new Dis t a n ce () ;
Distance d2 = new Dis t a n ce () ;
class Distance d1.Values = 10;
{ d2.Values = 20;
Distance d3 = d1 + d2;
p u b l i c i n t Values;
Console.WriteLine("Sum i s { 0 } " ,
d3.Values);
p u b l i c s t a t i c Distance operator +(Distance Console.Read();
d1, Distance d2) }
}
{ }
Distance d = new D i s t a n c e ( ) ; }
d.Values = d1.Values + d2.Values;
return d;

Output :}

Unit – 2 : The Basics and Console Applications in C# 18 Darshan Institute of engineering &Technology
Modifiers or Specifiers
 Access modifiers defines the scope of a class member. A class member
can be variable or function.
 Access modifiers are keywords used to specify the declared accessibility
of a member or atype.
 Why to use accessmodifiers?

Access modifiers are an integral part of object-oriented
programming.

They support the concept of encapsulation, which promotes the idea
of hiding functionality.

Access modifiers allow you to define who does or doesn't have
access for certain features.

Unit – 2 : The Basics and Console Applications in C# 19 Darshan Institute of engineering &Technology
Modifiers or Specifiers
 In C# Modifiers can be divided in five categories.

Public Access Specifier

Private Access Specifier

Protected AccessSpecifier

Internal AccessSpecifier

Protected Internal AccessSpecifier

Unit – 2 : The Basics and Console Applications in C# 20 Darshan Institute of engineering &Technology
Public Modifier

Public is the most common access specifier in C#.

It can be access from anywhere, that meansthere
is no restriction on accessibility.
• The scope of the accessibility is inside class
as well asoutside.
• The public keyword is used for it.


Accessibility:
– Can be accessed by objects of the class
Unit – 2 : TheBasics and Console Applications in C# 21 Darshan Institute of engineering &Technology
using System;

namespace Demo

{
Example - Public Modifier
class Access
Output :
{

p u b l i c i n t num1;

class Program

s t a t i c void M a i n ( s t r i n g [ ] args)

Access ob1 = new Access();

/ / D i r e c t access t o p u b l i c members

ob1.num1 = 100;

Console.WriteLine("Number one value i n


main { 0 } " , ob1.num1);

Console.ReadLine();

}
Unit – 2 : The Basics and Console Applications in C# 22 Darshan Institute of engineering &Technology
Private Modifier

Private members are accessible only within the
body or scope of the class or the structure in
which they are declared.

The private members cannot be accessed outside
the class and it is the least permissive access
level.
• The private keyword is used for it.


Accessibility:
Unit – 2
– Cannot be accessed by object
: The Basics and Console Applications in C# 23 Darshan Institute of engineering &Technology
namespace Demo

{ Example - Private Modifier


class Access

p u b l i c i n t num1;

p r i v a t e i n t num2;

class Program

s t a t i c void M a i n ( s t r i n g [ ] args)

Access ob1 = new Access();

/ / D i r e c t access t o p u b l i c members

ob1.num1 = 100;

//Access t o p r i v a t e member i s not permitted

ob1.num2 = 10;

Console.WriteLine("Number one value i n main { 0 } " , ob1.num1);

Console.ReadLine();

Unit – 2 : The
}
Basics and Console Applications in C# 24 Darshan Institute of engineering &Technology
Protected - Modifier

The protected keyword is also part of the
protected internal and private protected access
modifiers.

The scope of accessibility is limited within the
class or struct and the class derived (Inherited )
from this class.

A protected member of a base class is accessible
in a derived class only if the access takes place
through the derived classtype.
• The protected keyword is used for it.
Unit – 2 : The Basics and Console Applications in C# 25 Darshan Institute of engineering &Technology
Example - Protected Modifier
using System;

namespace Test

class access

/ / Integer Variable declared as protected

protected i n t age;

p u b l i c void p r i n t ( )

Console.W riteLine("\nMy Age i s " + age);

class Program

s t a t i c void M a i n ( s t r i n g [ ] args)

Unit – 2 : The Bacacseiscssaacnd=CnoewnsaoclceesAsp()p;licationsinC# 26 Darshan Institute of engineering &Technology


Internal Modifier

The internal access specifier hides its member
variables and methods from other classes and
objects, that is resides in othernamespace.

The variable or classes that are declared with
internal can be access by any member within
application.

We can declare a class as internal or its member
as internal.
• Internal members are accessible only within the
same assembly.
Unit – 2 : The Basics and Console Applications in C# 27 Darshan Institute of engineering &Technology
Example - Internal Modifier
using System;
Output :

namespace F irs t_Prg

class access

/ / Integer Variable declared as i n t e r n a l

i n t e r n a l i n t age;

p u b l i c void p r i n t ( )

Console.W riteLine("\nMy Age i s " + age);

class Program

s t a t i c void M a i n ( s t r i n g [ ] args)

Unit – 2 :aTccheessBaascic=snaenwdaCccoenssso()le; Applications in C# 28 Darshan Institute of engineering &Technology


Protected Internal Modifier

The protected internal accessibility means
protected OR internal, not protected AND
internal.

In other words, a protected internal member is
accessible from any class in the same assembly,
including derived classes.

The protected internal accessspecifier allows its
members to be accessed in derived class,
containing class or classes within same
application.
However, t his access s2p
9 ecifier
DarsranrInestiltuyte ou
Un•it – 2 : The Basics and Console Applications in C#
ha f ens
gie
ned
eringi&
nTechC
no#
logy
Example – Protected Internal
using System;
Modifier Output :

namespace Firs t_Prg

class access

/ / S t r i n g Variable declared as protected i n t e r n a l

protected i n t e r n a l s t r i n g name;

p u b l i c void p r i n t ( )

Console.W riteLine("\nMy name i s " + name);

class Program

s t a t i c void M a i n ( s t r i n g [ ] args)

{
Unit – 2 : The Bacacseiscssaacnd=CnoewnsaoclceesAsp()p;licationsinC# 30 Darshan Institute of engineering &Technology
Default Access

A default access level is used if no access modifier
is specified in a member declaration.
• The following list defines the default access
modifier
C#Types for Description
certain C#types:
enum The default and only access modifier supported is public.
Class The default access for a class is private.
It may be explicitly defined using any of theaccess modifiers.
Interface The default and only access modifier supported is public.
Struct The default access is private with public and internal supported
as well.
Interface and enumeration members are always public and no access modifiers are
allowed.

Unit – 2 : The Basics and Console Applications in C# 31 Darshan Institute of engineering &Technology
Properties

In C#, properties are nothing but natural
extension of data fields.
• They are usually known as 'smart fields' in C#
community.
• We know that data encapsulation and hiding are
the two fundamental characteristics of any object
oriented programming language.
• In C#, data encapsulation is possible through
either classes or structures.

Usually inside a class, we declare a data field as
Unit – 2 : The Basics and Console Applications in C# 32 Darshan Institute of engineering &Technology
Properties Cont..

Properties are special kind of class member, In
properties we use predefined Set and Get
method.

They use assessors through which we can read,
written or change the values of the private
fields.

We cannot access these fields from outside the
class , but we can accessing these private fields
through properties.

Unit – 2 : The Basics and Console Applications in C# 33 Darshan Institute of engineering &Technology
Properties Cont..

A property is a combination of variable and
a method.
• The get method is used to return property value
to the user.
Public <return type> <PropertyName>
{
• The set
get method is used to assign a new valu
{
e to
the property.
}
r e t u r n <var>;

set
• Syntax {
<var> = va l u e ;
}
}

Unit – 2 : The Basics and Console Applications in C# 34 Darshan Institute of engineering &Technology
Example - Properties
class Example class Program
{ {
s t a t i c void M a i n ( s t r i n g [ ] args)
p r i v a t e i n t number;
{
p u b l i c i n t Number
Example example = new Example();
{ / / set { }
example.Number = 5 ;
get
/ / get { }
{ Consol e. Wr i t eLi ne( exampl e. Number ) ;
r e t u r n number; Console.Read();

} }
}
set

{
Output :
number = va l u e ;

}
5
}
Unit – 2 : The Basics and Console Applications in C# 35 Darshan Institute of engineering &Technology
Indexers

Indexer is a new concept introduced by C#.

An Indexer is a special type of property that
allows a class or structure to be accessed the
same way asarray for its internal collection.
• In short, Indexer Concept is object act as an
array.
• It is same as property except that it defined with
this keyword with square bracket and
parameters.

It can be used for overloading a [] operator (Indexers
Unit – 2 : The Basics and Console Applications in C# 36 Darshan Institute of engineering &Technology
Indexers Cont..

Unit – 2 : The Basics and Console Applications in C# 37 Darshan Institute of engineering &Technology
Example - Indexers
class sample class Program
{
{
s t a t i c void M a i n ( s t r i n g [ ] args)
p r i v a t e s t r i n g [ ] name = new s t r i n g [ 3 ] ;
{
sample s = new sample();
s [ 0 ] = "Darshan";
public s tr i n g t h i s [ i n t index]
s[1] = "Institute";
{ s [ 2 ] = "Of Engg. &Tech."; f o r
( i n t i = 0 ; i <= 2 ; i + + )
get
{
{
C o n s o l e .W ri te L i n e ( s [ i ]) ;

i f (index < 0 | | index >= name.Length) }


Console.ReadKey();
{
}
return n u l l ; }
Output :
}
Darshan
else I n s t i t ute
{ Of Engg. & Tech.
r e t u r n name[index];

Unit – 2 : The B}asics and Console Applications in C# 38 Darshan Institute of engineering &Technology
Properties v/s Indexers
Properties Indexers
Properties don't require this keyword Indexers are created with this keyword
Properties are identified by their names Indexers are identified by signature
Properties are accessed by their names Indexers are accessed using indexes
Properties are also known as the smart fields Indexers are also known as smartarrays
A get accessor of a property has no Indexers in C# must have atleast one
parameters & A set accessor of a property parameter & it also supports more than one
contains the implicit valueparameter. different types of parameters

Syntax : Syntax :
<access_modifier> <return_type> <access_modifier> <return type> this
<property_name> [argument list]
{ {
get { } get { }
set { } set { }
} }

Unit – 2 : The Basics and Console Applications in C# 39 Darshan Institute of engineering &Technology
Introduction to ConsoleApplication

A console application is an application that runs
in a console window same asa C,C++etc.
• It doesn’t have any graphical user interface (GUI).
console applications will have character based
interface.

To work with console applications in .NET,
Console class is available that is within the
namespace System, which is the root namespace.

Unit – 2 : The Basics and Console Applications in C# 40 Darshan Institute of Engineering & Technology
To create and run aconsole
• Start Visual Studaiop.plication
• On the menu bar, choose FileNewProject.
• The New Project dialog box opens.

Expand Installed, expand Templates,
expand Visual C#, and then choose Console
Application.

In the Name box, specify a name for your project,
and give location then choose the OKbutton.
• The new project appears in Solution Explorer.
Un•it – 2 : The Basics and Console Applications in C# 41 Darshan Institute of Engineering & Technology
To create and run a consoleapplication

Replace the contents of Program.cs with the
f/o/lAoHwelilnogWocrodl d!ep.

Unit – 2 : The Basics and Console Applications in C# 42 Darshan Institute of Engineering & Technology
Thank you

You might also like