Вы находитесь на странице: 1из 53

Implementing OOP in C#

Objective

In this session, you will learn to:


What is C# Explain features of the object-oriented methodology Describe the phases of the object-oriented methodology Define classes in C# Declare variables Write and execute C# programs

What is C#
C# is an object-oriented programming language developed by Microsoft. That intends to be a simple, modern, and generalpurpose programming language for application development.

Object-Oriented Methodology

Object orientation is a software development methodology that is based on modeling a real-world system. An object oriented program consists of classes and objects.
Let us understand the termsclass and objects

Object-Oriented Methodology
Class Car

BMW

SUV

Mercedes

Objects

The Foundation of Object Orientation


An object means a material thing that is capable of being presented to the senses. An object has the following characteristics: It has a state It may display behavior It has a unique identity Objects interact with other objects through messages. Let us understand these concepts.

The Foundation of Object Orientation


An object means a material thing that is capable of being presented to the senses. An object has the following characteristics: It has a state It may display behavior It has a unique identity Objects interact with other objects through messages. Let us understand these concepts.

The Foundation of Object Orientation


Car positioned at one place defines its State

Movement of car defines its Behavior

Car number XX 4C 4546 shows the Identity of the car

The Foundation of Object Orientation (Contd.)

Car is flashing the lights to pass the message to the other car

Introducing C# (Contd.)
C#, also known as C-Sharp, is a programming language introduced by Microsoft. C# is specially designed to work with the Microsofts .NET platform.

Let us understand the structure of a C# program.

Classes in C#
Consider the following code example, which defines a class:
public class HelloWorld {

public static void Main(string[] args) {


System.Console.WriteLine("Hello, World! \n");

}
}

Classes in C# (Contd.)
public class HelloWorld { public static void Main(string[] args) {

System.Console.WriteLine("Hello, World! \n");


} }

The class Keyword Is used to declare a class

Classes in C# (Contd.)
public class HelloWorld { public static void Main(string[] args) {

System.Console.WriteLine("Hello, World! \n");


} }

The class Name Is used as an identifier for a class

Classes in C# (Contd.)
public class HelloWorld { public static void Main(string[] args) {

System.Console.WriteLine("Hello, World! \n");


} }

The Main() Function Is the entry point of an application Is used to create objects and invoke member functions

Classes in C# (Contd.)
public class HelloWorld { public static void Main(string[] args) {

System.Console.WriteLine("Hello, \n");
} }

System.Console.WriteLine() Displays the enclosed text on the screen World!

Classes in C# (Contd.)
public class Helloworld { public static void Main(string[] args) {

System.Console.WriteLine("Hello, World! \n");


} }

The Escape Character Displays New line character. Other special characters can also be displayed such as \t, \b and \r

Value Type Variable


Values can be stored in variables by two methods which are: by value and by reference Value types store the supplied value directly in the memory whereas reference types store a reference to the memory where the actual value is located.

Overview of CTS
Establishes a Framework that enables cross-language integrations, type safety, and high performance code execution.

Provides an Object Oriented Model that supports the complete implementation of many programming languages.
Define set of rules that languages must follow, which helps ensures that object written in different languages can interact with each other.

Overview of CTS

CTS supports both value and reference types

Type

Value Type

Reference Type

Comparing Value and Reference Types

Value types:

Reference types:

Directly contain their data Each has its own copy of data Operations on one cannot affect another

Store references to their data (known as objects) Two reference variables can reference same object Operations on one can affect another

Declaring Variables
A variable is a location in the memory that has a name and contains a value. A variable is associated with a data type that defines the type of data that can be stored in a variable.

Declaring and Initializing Variables


You can declare and initialize variables by using the following syntax:
<data_type> <variable_name>=<value>;

Declaring and Initializing Variables (Contd.)


Consider the following example of declaring and initializing a variable:
int class_rank=2;

Data Types in C# Represents the kind of data stored in a variable C# provides you with various built-in data types, such as: char int float double bool string

Data Types in C# (Contd.)

string

Name = Peter

float
int char

Marks = 83.56
Age = 23 Vowel = a

Data Types in C# (Contd.)


Consider the following example of declaring and initializing a variable:
int class_rank=2;

Data types in C# The following types of data types are supported by C#: Value types
int NumNum; Num=5; 5

Memory allocated Variable declared and Initialized

Memory Allocation in Value Type

Declaring and Initializing Variables


Consider the following example of declaring and initializing a variable:
int class_rank=2;

Data types in C# The following types of data types are supported by C#: Reference types
string Str=Hello; Address H 0 E 1 Str L 2 L 3 O 4

Memory Allocation of the String Type Variable

Declaring and Initializing Variables (Contd.)


Consider the following example of declaring and initializing a variable:
int class_rank=2;

Naming variables in C# The following rules are used for naming variables in C#: Must begin with a letter or an underscore Should not contain any embedded spaces or symbols Must be unique Can have any number of characters Keywords cannot be used as variable names

Declaring and Initializing Variables (Contd.)


Consider the following example of declaring and initializing a variable:
int class_rank=2;

Examples and non-examples of Naming Variables


Name #Score Age 2Strank

Family_Size
Gender

Declaring and Initializing Variables (Contd.)


Consider the following example of declaring and initializing a variable:
int class_rank=2;

Initializing Variables in C# Specifies the value that needs to be stored in a variable. The value could be an integer, a decimal, or a character.

Converting Data Types


Implicit Data Type Conversion Explicit Data Type Conversion

Implicit Data Type Conversion


To Convert int to long:
using System; class Test { static void Main( ) { int intValue = 123; long longValue = intValue; Console.WriteLine("(long) {0} = {1}", intValue, longValue); } }

Implicit conversions cannot fail


May lose precision, but not magnitude

Explicit Data Type Conversion


using System; class To do explicit conversions, use a cast expression: Test { static void Main( ) { long longValue = Int64.MaxValue; int intValue = (int) longValue; Console.WriteLine("(int) {0} = {1}", longValue, intValue); } }

Creating a Sample C# Program


A C# program can be written by using an editor like Notepad. Consider the following code, which declares a class Customer and also creates an object custObj of the same class:
using System; class Customer { //Member variables string Name; int age; //Member functions void AcceptDetails()

The using keyword is used to include the namespaces in the program. Comments are used to explain the code and are represented by // symbols. Member variables are used to store the data for a class. Member functions are declared inside the class that are used to perform a specific task.

Creating a Sample C# Program (Contd.)


{ Console.WriteLine("Enter the Name of Customer"); Name = Console.ReadLine(); Console.WriteLine("Enter the Age of customer"); age = Convert.ToInt32(Console.ReadLine()); } public void DisplayDetails() { Console.WriteLine("The Name of Customer is:{0}", Name); Console.WriteLine(Age is :{0}", age); }

Creating a Sample C# Program (Contd.)


//Class used to instantiate the Car class class ExecuteClass { public static void Main(string[] args) { Customer custObj = new Customer(); custObj.AcceptDetails(); custObj.DisplayDetails(); } }

The Execute class is used as a class from where the Car class can be instantiated.

Compiling and Executing C# Program


After writing the program in a Notepad, you need to compile and execute it to get the desired output. The compiler converts the source code that you write into the machine code, which the computer can understand. The following steps are needed to compile and execute a C# program.
1. 2. Save the code written in the Notepad with an extension .cs. To compile the code, you need to go to the Visual Studio 2005 Command Prompt window. Select StartAll ProgramsMicrosoft Visual Studio 2005Visual Studio ToolsVisual Studio 2005 Command Prompt. The Visual Studio 2005 Command Prompt window is displayed to compile the program. In the Visual Studio 2005 Command Prompt window, move to the location where the programs file is saved.

3.

Compiling and Executing C# Program (Contd.)


4. 5. Compile the program file by using the following command:
csc ExecuteClass.cs

To execute the code, type the following in the command prompt:


ExecuteClass.exe

Using Operators
Applications use operators to process the data entered by a user. Operators in C# can be classified as follows:
Arithmetic operators Arithmetic Assignment operators Unary operators Comparison operators Logical operators

Arithmetic Operators
Arithmetic operators are the symbols that are used to perform arithmetic operations on variables. The following table describes the commonly used arithmetic operators.

Operator +

Description Used to add two numbers X=Y+Z;

Example

If Y is equal to 20 and Z is equal to 2, X will have the value 22. Used to subtract two numbers X=Y-Z; If Y is equal to 20 and Z is equal to 2, X will have the value 18. * Used to multiply two numbers X=Y*Z; If Y is equal to 20 and Z is equal to 2, X will have the value 40. / Used to divide one number by another X=Y/Z; If Y is equal to 21 and Z is equal to 2, X will have the value 10. But, if Y is equal to 21.0 and Z is equal to 2, X will have the value 10.5. % Used to divide two numbers and return the remainder X=Y%Z; If Y is equal to 21 and Z is equal to 2, X will contain the value 1.

Arithmetic Assignment Operators


Arithmetic assignment operators are used to perform arithmetic operations to assign a value to an operand. The following table lists the usage and describes the commonly used assignment operators.

Operator = += X = 5; X+=Y;

Usage

Description Stores the value 5 in the variable X. Same as: X = X + Y;

-=

X-=Y;

Same as: X = X - Y;

*=

X*=Y;

Same as: X = X * Y;

/=

X/=Y;

Same as: X = X / Y;

%=

X%=Y;

Same as:
X = X % Y;

Unary Operators
Unary operators are used to increment or decrement the value of an operand by 1. The following table explains the usage of the increment and decrement operators.

Operator ++ ++Operand;

Usage

Description Used to increment the value of an operand by 1 Y = ++X;

Example

(Preincrement operator) Or, Operand++; (Postincrement operator)

If the initial value of X is 5, after the execution of the preceding statement, values of both X and Y will be 6. Y = X++; If the initial value of X is 5, after the execution of the preceding statement, value of X will be 6 and the value of Y will be 5.

--

--Operand; (Predecrement operator)

Used to decrement the value of an operand

Y = --X; If the initial value of X is 5, after the execution of the

Or,
Operand--; (Postdecrement)

by 1

preceding statement, values of X and Y will be 4.


Y = X--; If the initial value of X is 5, after the execution of the preceding statement, value of X will be 4 and the value of Y will be 5.

Comparison Operators
Comparison operators are used to compare two values and perform an action on the basis of the result of that comparison. The following table explains the usage of commonly used comparison operators.

Operator

Usage

Description

Example (In the following examples, the value of X is assumed to be 20 and the value of Y is assumed to be 25)

<

expression1 < expression2

Used to check whether expression1 is less than expression2

bool Result; Result = X < Y; Result will have the value true.

>

expression1 > expression2

Used to check whether expression1 is greater than expression2

bool Result; Result = X > Y; Result will have the value false.

<=

expression1 <= expression2

Used to check whether expression1 is less than or equal to expression2

bool Result; Result = X <= Y; Result will have the value true.

>=

expression1 >= expression2

Used to check whether expression1 is greater than or equal to expression2

bool Result; Result = X >= Y; Result will have the value false.

Comparison Operators (Contd.)

Operator

Usage

Description

Example (In the following examples, the value of X is assumed to be 20 and the value of Y is assumed to be 25)

==

expression1 == expression2

Used to check whether expression1 is equal to expression2

bool Result; Result = X == Y; Result will have the value false.

!=

expression1 != expression2

Used to check whether expression1 is not equal to expression2

bool Result; Result = X != Y;

Result will have the value true.

Logical Operators
Logical operators are used to evaluate expressions and return a Boolean value. The following table explains the usage of logical operators.

Operator &&

Usage expression1 && expression2

Description Returns true if both expression1 and expression2 are true. bool Result; string str1, str2; str1 = Korea; str2 = France;

Example

Result= ((str1==Korea) && (str2==France)) Console.WriteLine (Result .ToString()); The message displays True because str1 has the value Korea and str2 has the value France. ! ! expression Returns true if the expression is false. bool Result int x; x = 20; Result=(!( x == 10)) Console.WriteLine(Result.ToString()); The message displays True because the expression used returns true.

Logical Operators (Contd.)

Operator

Usage

Description

Example

||

expression1 || expression2

Returns true if either expression1 or expression2 or both of them are true.

bool Result string str1, str2; str1 = Korea; str2 = England; Result= ((str1==Korea) || (str2== France)) Console.WriteLine (Result .ToString()); The message displays True if either str1 has the value Korea or str2 has the value France.

expression1 ^

Returns true if either

bool Result;

expression2

expression1 or expression2 is
true. It returns false if both expression1 and expression2 are true or if both expression1 and expression2 are false.

string str1, str2;


str1 = Korea; str2= France; Result = (str1== Korea) ^ (str2== France); Console.WriteLine (Result .ToString()); The message False is displayed because both the expressions are true.

Вам также может понравиться