You are on page 1of 64

CHAPTER TWO

Object-Oriented Fundamentals In C#
Language Fundamentals
• A C# program consists of the following parts
– Namespace declaration
– Namespace declaration
– A class
– Class methods
– Class attributes
– A Main method
– Statements and Expressions
– Comments
• Let us look at a simple code that prints the words "Hello World":
– First start new project as follows and write the following program:
– Click on start button all program Microsoft visual studio 2010 
Microsoft visual studio 2010 select visual C #  New Project
select visual c # select consol application(give name, location and
solution name)  finally click on ok button.
Cont…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// my first program in C#
System.Console.Out.WriteLine("Hello World");
Console.ReadKey();

}
}
}
Let us look at the various parts of the given program:
1. The first line of the program using System; -
– the using keyword is used to include the System namespace in the program.
– A program generally has multiple using statements.
– System is a namespace, which is a scheme that provides a way to group similar classes.
– For instance, we use the console class, which is a part of the system namespace
2. The next line has the namespace declaration.
– A namespace is a collection of classes. The ConsoleApplication1 namespace contains the
class Program.
– It is used to organize classes
– It is designed for providing a way to keep one set of names separate from other. The
class names declared in one namespace does not conflict with the same class name
declared in another.
3. The next line has a class declaration,
– The class contains the data and method definitions that your program uses.
– Classes generally contain multiple methods.
– Methods define the behavior of the class. However, this class has only one method
Main.
Cont…
4. The next line defines the Main method, which is the entry point for
all C# programs.
– The Main method states what the class does when executed.
5. System.Console.Out.WriteLine("Hello World");
– System is a namespace
– Console define the attributes of a collection of similar “Console” objects
– Out is an object that represents the screen. The out object was created and
endowed with the method WriteLine (). Not all object have the WriteLine ()
method.
– The WriteLine () method prints a line of output on the screen. Where as
Write() method outputs one or more values on the screen without a new
character (this means any subsequent output will be printed in the same
line).
6. The last line Console.ReadKey();
– It is for the VS.NET Users. This makes the program wait for a key press and it
prevents the screen from running and closing quickly when the program is
launched from Visual Studio .NET.
Cont…
• It is worth to note the following points:
– C# is case sensitive.
– All statements and expression must end with a
semicolon (;).
– The program execution starts at the Main method.
– Unlike Java, program file name could be different
from the class name.
Comments
• In large programs it becomes difficult to remember why certain
steps were included and the role of certain variables and methods
• Program comments are nonexecuting statements that you add to
document a program
• Comments is a text that is put somewhere in the code for a human
to read, that the computer/ compiler ignores
• You can also comment out various statements in a program to
debug and observe the effects of the program with the statement
or statements commented out
• You should uses comment to describe what you are doing.
• Write a good comments is a part of writing a good code .
• There are three types of comments in C#:
– Single Line comments(// comment )
– Multiple line comments /Block comments ( /* comment */)
– XML-documentation /tags comments(/// xml tag)
Example
Compiling and Executing a Program
• In C# programming using Visual Studio .NET it is possible to
compiling and executing a program from the command line or
using Visual Studio IDE
• C# programs can also be written using the Visual Studio IDE
(instead of a text editor). This approach offers many
advantages including:
– Some of the code you need is already created for you
– The code is displayed in color, so you can more easily identify parts of
your program
– If error messages appear when you compile your program, you can
double-click on an error message and the cursor will move to the line
of code that contains the error
– Other debugging tools are available
Variables
• A data item is classified as either constant or variable
• Constant data items cannot vary
• Variable data items can hold different values at different points of time
• During the execution of a program, data is temporally stored in memory.
• A variable is the name given to a memory location holding a particular
type of data.
• So, each variable has associated with it’s a data type and value.
• All data items in a C# program have a data type
• Data type describes the format and size of a piece of data
• C# provides 14 basic or intrinsic types
• The most commonly used data types are: int, double, char, string, and
bool
• Each C# intrinsic type is an alias, or other name for, a class in the System
namespace
Variable Declaration
• It includes:
1. The data type that the variable will store
2. An identifier that is the variable’s name (start by a letter or underscore followed
by any of the combination of letter, number or underscore )
3. An optional assignment operator and assigned value when you want a variable to
contain an initial value
4. An ending semicolon
• The general syntax to declare a variable is:
Data_Type Variable_Name;
• E.g. double myage;
int i;
char sex;
string name
• Declaring of variables of the same type be separated by commas.
• In C# (like other modern languages), you must declare variables before using
them.
• E.g. int x, y;
double myage =25.5,yourage =19.75;
Constant Variables or Symbols
• Constants are variables whose values, once defined, can not be
changed by the program.
• Constant variables are declared using the const keyword, like:
const double PI = 3.142;
• Constant variables must be initialized as they are declared. It is a
syntax error to write:
const int MARKS;
• It is conventional to use capital letters when naming constant
variables.
• After declaration, to use the declared variable you must initialize it
using assignment operator.
• General syntax : Variable_Name= value;
• E.g. int myage;// declaration
myage =25; //initialization
or int myage =25;
Using the Integral Data Types
• In C#, there are nine integral data types:
byte (8+), sbyte (8), short (16), ushort (16+), int (32),
uint (32+), long (64), ulong (64+), and char (16)
• char is used for characters like ‘A’ or ‘b’, while the
other eight are used to store whole numbers
• You use variables of type int to store integers
• When you assign a value to a numeric variable, you
do not type any commas:
– int cost = 1000; // NOT int cost = 1,000;
Operators in C#
Arithmetic Operators
• Several common arithmetic operators are allowed in C#.
Operand Description Examples
+ Add 45+2: the result is 47
- Subtract 45-2: the result is 43
* Multiply 45*2: the result is 90
Divide 45/2: the result is 22( not 22.5)
% Remainder or modulo 45%2: the result is 41
• When you divide two integers (using the division operator or the modulus operator),
the result is ALWAYS an integer
• Operator precedence refers to the order in which parts of a mathematical expression
are evaluated
Compound assignment operators
Operand Description Examples
+= Add and assign the result i+=2: means i=i+2;
-= Subtract and assign the result i-=2: means i=i-2;
*= Multiply and assign the result i*=2: means i=i*2;
/= Divide and assign the result i/=2: means i=i/2;
%= Remainder/ modulo and assign the result i%=2: means i=i%2;
 
Cont…
Increment/Decrement Operators: (++) and (--)
• The auto increment (++) and auto decrement (--) operators provide a convenient
way of, respectively, adding and subtracting 1 from a numeric variable.
• E.g.:
– if x was 10 and if x++ is executed then x will automatically changed to 11.
• Prefix and Postfix:
– The prefix type is written before the variable. whereas the postfix type appears after the
variable name.
• Eg. ++ myAge  prefix; myAge ++  postfix
• Prefix and postfix operators cannot be used at once on a single variable:
• The prefix operator is evaluated before the assignment, and the postfix operator is
evaluated after the assignment.
• E.g.
int k = 5;
(auto increment prefix) y= ++k + 10; //gives 16 for y
(auto increment postfix) y= k++ + 10; //gives 15 for y
(auto decrement prefix) y= --k + 10; //gives 14 for y
(auto decrement postfix) y= k-- + 10; //gives 15 for y
Cont…
Relational Operators
• Relational operators are used for comparison purposes in conditional statements. Common
relational operators in C# are:
Operand Description
== Equality check
!= Un-equality check
>  Greater than
<  Less than
>= Greater than or equal to
<= Less than or equal to

Logical Operators (!, &&, ||)


• Logical negation (!) is a unary operator, which negates the logical value of its operand. If its
operand is non zero, it produces 0, and if it is 0 it produce 1.
• Logical AND (&&) produces 0 if one or both of its operands evaluate to 0 otherwise it produces
1.
• Logical OR (||) produces 0 if both of its operands evaluate to 0 otherwise, it produces 1.
E.g.: !20 //gives 0
10 && 5 //gives 1
10 || 5.5 //gives 1
10 && 0 // gives 0
Cont…
Conditional Operator (?:)
• The conditional operator takes three operands. It has the general
form:
Syntax:
operand1 ? operand2 : operand3;
• First operand1 is a relational expression and will be evaluated.
If the result of the evaluation is non zero (which means TRUE),
then operand2 will be the final result. Otherwise, operand3 is
the final result.
E.g.: General Example
Z=(X<Y? X : Y)
This expression means that if X is less than Y the value of X
will be assigned to Z otherwise (if X>=Y) the value of Y will be
assigned to Z.
• E.g.:
(7 = = 5 ? 4: 3) returns 3 since 7 is not equal to 5
Using the char Data Type
• The char data type is used to hold a single character (‘A’,’b’,’9’)
• A number can be a character only if it is enclosed in a single
quotation mark (char aChar = 9; is illegal)
• You can store any character in a char variable, including
escape sequences
• Characters in C# are represented in Unicode
• There are certain characters in C# when they are proceeded
by a back slash they will have special meaning
Using the string Data Type
• In C# the string data type holds a series of
characters
• Although you can use the == comparison
operator with strings that are assigned literal
values, you CANNOT use it with strings created
through other methods
• C# recommends that you use the Equals() and
Compare() methods to compare strings
• A string is considered greater than another
string when it is greater lexically
• E.g. 1 Program that compares two strings using ==
Cont…
E.g. 2 Program that compares two strings using
Equals() and Compares()
Accepting Console Input
• A program that allows user input is an
interactive program
• The Console.ReadLine() method accepts user
input from the keyboard
• This method accepts a user’s input as a string
• You must use a Convert() method to convert
the input string to the type required
Example
Methods
• A method is a code block that contains a series of statements. A program
causes the statements to be executed by calling the method and specifying
any required method arguments.
• A method is a group of statements that together perform a task.
• Every C# program has at least one class with a method named Main. The
Main method is the entry point for every C# application and it is called by
the common language runtime (CLR) when the program is started.
• Methods are extremely useful because they allow you to separate your
logic into different units. You can pass information to methods, have it
perform one or more statements, and retrieve a return value.
• A method is a series of statements that carry out a task
• A method can be invoked or called by other methods
• Method names are always followed by a set of parentheses
• To use a method, you need to:
– Define the method
– Call the method
Method Definition
• In C#, a method must include:
– A method declaration(method header)
• access modifiers/ Access Specifier
• Return type
• Method name
• Parameter list within a parentheses
– An opening curly brace
– A method body
– A closing brace
Cont…
• The general syntax is:
Access _Specifier Return_Type Method_Name(Parameter List)
{
Statements;
//Method Body
}
Cont…
• Following are the various elements of a method:
1. Access Specifier: This determines the visibility of a variable or
a method from another class.
• It is optional and it can be public, protected, and private
– Private:-if the method Specifier/modified is private can be accessed only within
the class
– Protected:-can be accessed by own class and its derived classes
– Public :-can be accessed out side the class also
• If an access modifier for a method is not declared, the method becomes
private by default
• Members of a class are either static members or instance members.
Generally speaking, it is useful to think of static members as belonging
to classes and instance members as belonging to objects (instances of
classes).
Static Method
• When a field, method, property, event, operator, or constructor
declaration includes a static modifier, it declares a static member. In
addition, a constant or type declaration implicitly declares a static
member. Static members have the following characteristics:
Cont…
– When a method declaration includes a static modifier, that method is said
to be a static method.
– A static method does not operate on a specific instance, and it is a
compile-time error to refer to this in a static method.
– A static field identifies exactly one storage location. No matter how many
instances of a class are created, there is only ever one copy of a static
field.
Instance Methods
• When a field, method, property, event, indexer, constructor, or
destructor declaration does not include a static modifier, it
declares an instance member. (An instance member is sometimes
called a non-static member.) Instance members have the
following characteristics:
– When no static modifier is present, the method is said to be an instance
method.
– Instance method operates on a specific instance given instance of the
class and this instance can be accessed at this.
– Every instance of a class contains a separate set of all instance fields of the
class.
Example
• When a method is referenced in a member-access of the form E.M, if M is
a static method, E must denote a type containing M, and if M is an
instance method, E must denote an instance of a type containing M.
• The following example illustrates the rules for accessing static and instance
members:
Cont…
2. Return type:
• A method may return a value.
• The return type is the data type of the value the method returns.
• If the method returns a value, use the basic data type such as int,
double, char, string and etc.
• If the method is not returning any values, then the return type is
void.
• If the method returns a value, it is must to include return keyword
followed by a returned value at the end of the method body.
3. Method name:
• Method name is a unique identifier and it is case sensitive.
• It cannot be same as any other identifier declared in the class.
• To give the method name using identifier rule, that means it start
by a letter or underscore and either followed by a letter or a
number or underscore or a combination of all of them.
Cont…
4. Parameter list:
• Set of zero or more argument passed into a method
containing its type and argument.
• Enclosed between parentheses, the parameters are used to
pass and receive data from a method.
• The parameter list refers to the type, order, and number of
the parameters of a method.
• Parameters are optional; that is, a method may contain no
parameters.
• Each and every argument must be declared with its
respected data type
5. Method body:
• This contains the set of instructions needed to complete the
required activity.
• It starts by opening curly brace (“{”) and ends with
ending/closing curly brace (“}”).
Example

1. Write a method with no 2. Write a method with no


argument and no return value argument and having a
public void welcome()
return value
{
public int Age()
Console.WriteLine("Wel come");
{
Console.WriteLine("Enjoy the program");
} int age = 23;
return age;
}
3. Write a method with argument 4. Write a method with
and no return value argument and having a
public void sum(int x, int y, int z) return value
{ double product(double num1,double num2)
int s ; {
s = x + y + z; double pro = num1 * num2;
Console.WriteLine("Sum={0}",s); return pro;
}
}
Calling Method in C#
• The simplest way to call a method is to call it by using the name
of the method. This is the most general way in which the
methods are called and is the most widely used one as well.
• Another way is to call a public method from some other class by
using the instance of the class. This technique is used only in
some particular cases where a public method is being used.
• If the method can not return a value the general syntax to call a
method is as follows:
method_name(argument list);
• Otherwise, use the following general syntax
Data_type var_name=method_name(argument list);
Note: the data type of the variable must be similar with the
return type of the method.
Type of parameter argument
1. A formal parameter is a parameter in the method declaration
2. An actual parameter refers to an argument within a method call
• E.g. void example(int x, double y)
– x and y are formal parameters
example(a,b);
– a and b are actual parameters
• Another important concept is about the methods with
parameters. Whenever a method with parameters is called, the
parameters must also be passed to the method. The parameters
can be passed in C# by using methods like value parameters,
reference parameters and output parameters.
Cont…
• In C#, you can write methods with four kinds of
formal parameters listed within the parentheses in
the method header
– Value parameters
– Reference parameters
– Output parameters
– Parameter arrays
Value parameters
 When you use a value parameter in a method header, you
indicate the parameter’s type and name, and the method
receives a copy of the value passed to it
Using ref and out Parameters Within Methods
• Both the reference and output parameters have memory
addresses that are passed to a method, allowing it to alter the
original variables
• When you use a reference parameter to a method, the
parameter must be assigned a value before you use it in the
method call
• When you use an output parameter, it does not contain an
original value
• Both reference and output parameters act as aliases, or other
names, for the same memory location
• The keyword ref is used to indicate a reference parameter
• The keyword out is used to indicate an output parameter
Example
using System; using System;

namespace ConsoleApplication10 namespace ConsoleApplication10


{ {
class Program class Program
{ {
static void Main(string[] args) static void Main(string[] args)
{ {
int a, b; int a, b;
Console.WriteLine("enter the 1st number"); sum(out a, out b);
a = Convert.ToInt32(Console.ReadLine()); }
Console.WriteLine("enter the 2nd number"); static void sum(out int x, out int y)
b = Convert.ToInt32(Console.ReadLine()); {
sum(ref a, ref b); Console.WriteLine("enter the 1st number");
} x = Convert.ToInt32(Console.ReadLine());
static void sum(ref int x, ref int y) Console.WriteLine("enter the 2nd number");
{ y = Convert.ToInt32(Console.ReadLine());
int s = x + y; int s = x + y;
Console.WriteLine("sum={0}", s); Console.WriteLine("sum={0}", s);
} }
} }
} }
Cont..
• In the preceding code:
– The modifier ref precedes the variable in both the method
call and the method header
– The passed and received variables occupy the same
memory location
– The passed variable was assigned a value
– Unlike the reference parameter, the output parameter
does not need a value assigned to it (before it is used in a
method call)
– The output parameter is convenient when the passed
variable doesn’t have a value yet
– The output parameter gets its value from the method, and
these values persist back to the calling program
Overloading Methods

• Overloading involves using one term to indicate diverse meanings


• When you overload a C# method, you write multiple methods
with a shared name
• The compiler understands the meaning based on the arguments
you use with the method
• By overloading methods, you run the risk of creating an
ambiguous situation
• An ambiguous situation is one in which the compiler cannot
determine which method to use
• The compiler usually distinguishes between overloaded methods
by the argument lists, but this is NOT always possible
Avoiding Ambiguous Methods

• If only one method exists, there is no chance of an ambiguous situation


• This code would work fine even if your arguments were both of type int
Avoiding Ambiguous Methods

• What happens when another version of the same method is added?


• An ambiguous situation does not exist because the compiler can
determine the appropriate method
Avoiding Ambiguous Methods

• A more complicated and potentially ambiguous situation arises when the


compiler cannot determine which of several versions of a method to use
• An ambiguous situation arises because there is no exact match for the
method call
• An overloaded method is not ambiguous on its own—it become
ambiguous only if you create an ambiguous situation
Class
• There are two distinct types of classes created in C#:
– Classes that contain a Main() method
– Classes from which you instantiate objects
• Everything is considered an object in the object-oriented approach
• Object-oriented programmers recognize “is-a relationships”
• The use of objects provides a better understanding of the idea that
is being programmed
• The data components of a class are called the instance variables
of that class
• Class object attributes are called fields
• The contents of a class object’s instance variables are also known
as its state
• In addition to attributes, class objects also have methods
associated with them
Creating a Class from Which Objects Can Be
Instantiated
• A class header or class definition contains three
parts:
– An optional access modifier
– The keyword class
– Any legal identifier you choose for the name of your class
Access modifier
• Private and protected classes have limited uses
• When you declare a class using a namespace, you
can only declare it to be public or internal
• Class access is internal by default
Creating Instance Variables and Methods
• Instance variables are created using the same syntax
used to declare other variables
• The allowable field modifiers are new, public,
protected, internal, private, static, readonly, and volatile
• Identifying a field as private means that no other class
can access the field’s value, and only methods of the
same class will be allowed to set, get, or otherwise use
the field
• Using private fields within classes is an example of
information hiding
• Although most fields are private, most class methods
are public
Creating Instance Variables and Methods

• In the following code, the variable idNumber is private, yet remains


accessible to outside classes through the GetId() method
• Methods used with object instantiations are called instance methods
Creating Instance Variables and Methods

• The following cods creates a method that is a counterpart to the


GetID() method, called SetId()
• The SetId() method does not return any value, rather, it is used to
assign a value in the class
Declaring Objects
• Declaring a class does not create any actual objects
• A two step process creates an object that is an instance of a class:
– Supply a type and an identifier
– Allocate computer memory for the object
• Declaring an object notifies the compiler of the identifier and the
type, but it does not allocate memory
• To allocate the needed memory for an object, use the new operator
• For example:
Employee myAssistant = new Employee();
• The value being assigned to myAssistant is a memory address at
which it will be located
• Any class created can be referred to as a reference type, while the
predefined types are called value types
• The method called after the new keyword is called the constructor
method
Compiling and Running a Program That
Instantiates Class Objects
• When you create an application that uses multiple class
definitions, the class definitions can be stored in either a single file
or each can be placed in its own file
• Storing all class definitions in one file shortens development time
and simplifies the compilation process
• Using separate files for each class definition provides a more
organized and manageable technique, and it allows for easier
reusability
• Most classes you create will have multiple methods and fields,
which can become difficult to track in large programs
• It is a good idea to arrange fields and methods in a logical order:
– Alphabetically
– By “Sets” and “Gets”
– Pairing of “Sets” and “Gets”
Organizing Your Classes

• In addition to organizing fields and methods, comments


should also be used
Using Public Fields and Private Methods
• The private fields/public method arrangement ensures that
data will be used and changed only in ways provided in your
methods
• Although it is easier to declare fields as public, doing so is
considered poor object-oriented programming design
• Data should always be hidden when possible and access
should be controlled by well-designed methods
Using Public Fields and Private Methods

• Poorly designed Desk class and program that instantiates a Desk


Using Public Fields and Private Methods

• The Carpet class


Using Public Fields and Private Methods

• Occasionally, there are instances where a data field should be


declared as public
• A data field may be declared public if all objects of a class
contain the same value for that data field
• The preceding example (fig 4-12) declared a public const field
• A named constant within a class is always static
Understanding the this Reference
• When instances of a class are created, the resulting objects
require separate memory locations in the computer
• In the following code, each object of Book would at least
require separate memory locations for title, numPages, and
Price
Understanding the this Reference

• Unlike the class fields that are unique to each instance, the
methods of the class are shared
• Although the methods are shared, there must be a difference
between two method calls (from different objects), because
each returns a different value (based on their unique fields)
• When a method is called, you automatically pass a reference
to the memory of the object into the method
• The implicitly passed reference is the this reference
Understanding the this Reference

• Book class methods explicitly using the this reference


Understanding Constructor Methods

• A constructor method is a method that establishes an object


• Every class created is automatically supplied with a public
constructor method with no parameters
• Any constructor method you write must have the same name
as its class, and constructor methods cannot have a return
type
Passing Parameters to Constructors

• You can create a constructor that sets the same value for all
objects instantiated. The program can eventually call the
method of the object to set the value. However, this might
not always be the most efficient technique.
Passing Parameters to Constructors

• In this code, the constructor receives an argument and


initializes the object with the appropriate information
Overloading Constructors

• C# automatically provides a default constructor


• However if you create your own constructor, the
automatically provided default constructor is not available
• C# constructor methods, like other methods, can be
overloaded
Understanding Destructor Methods

• A destructor method contains the actions you require when


an instance of a class is destroyed
• To explicitly declare a destructor method, use an identifier
that consists of a tilde(~) followed by the class name
• Destructors cannot receive parameters and therefore cannot
be overloaded
• A class can have at most one destructor
Understanding Destructor Methods

• Employee class with destructor method


Understanding Destructor Methods

• Destructor methods are automatically called when an object


goes out of scope
• You cannot explicitly call a destructor
• The last object created is the first object destroyed

You might also like