SlideShare a Scribd company logo
1 of 61
Fundamental
Programming with
C#
C# Syntax
• Like C/C++ and Java
Identifiers
Identifiers (Cont.)
• Consist of Unicode characters
• Can begin with a letter or an underscore
• Cannot a keywords
  • eg. int, string, double, …
Capitalization Styles
• Pascal case, eg. MyValue
• Camel case, eg. myValueNumber
• Uppercase, eg. UI
Keywords
Literals
Operators
Punctuators
Statements
There are different kinds of statement in C#:
• A code block
• Declaration statements
• Expression statements
• Selection statements
• Iteration statements
• Control statements
Comments
Types
Every piece of data in C# must have a type. This is a key
part of C# being a strongly typed programming
language. The C# compiler and runtime both use the
type of each data item to reduce some kinds of
programming problems.


There are two kinds of types in C#: value types and
reference types. The distinction between the two causes
programmers new to object-oriented programming a lot
of confusion.
Value Types
Value-type variables directly contain their data—that is to
say that the content of a value-type variable is its value. The
following statement assigns a value of 25 to a variable
called myInt. The type of the variable myInt is int, which is a
value type.
Value Types (Cont.)
Reference Types
Reference types come in two parts—an object and the reference to that
object. Here is a statement that creates a reference-type object:
StringBuilder myObject = new StringBuilder("Adam");
The StringBuilder type holds a string of characters. Figure 4-10 shows
the reference type in memory. You don’t deal with the object directly—
instead, you work with it via the reference.
Definite Assignment and Null
References
C# requires that you assign a value to a variable before you read the value
of the variable. The compiler checks your code to ensure that every path
through your code assigns a value to every variable that you read. This is
called definite assignment.
The assignment of a value doesn’t need to occur when you declare the
variable; you just have to make sure that you have made an assignment
before you read the variable value. Here are some statements that
demonstrate this:
int myInt; // declare a variable, but don't assign to it
myInt = 20; // assign a value to the variable
int sum = 100 + myInt; // we can read the value because we
have made an assignment
Common Programming Tasks
The chapters that follow focus on the major features of
C#: classes, methods, fields, parameters, delegates, and
so on. These are such important topics that it can be
easy to overlook the tasks that are most commonly
required of programmers. In the following sections, I
describe how to assign values to variables, make
comparisons between values, selectively execute blocks
of code, and iterate over data items.
Assigning Values
The C# assignment operator is the equals sign (=).
Figure 4-13 shows how the assignment operator is
used to assign a value to a variable.
Making Comparisions
The C# comparison operator (==) is used to determine
whether two variables are the same.
Making Comparisons (Cont.)
Performing Selections
Selection statements let you select blocks of code
statements to be executed if a condition is met. C#
supports two selection statements—the if statement and
the switch statement.
Using an if Statement
With an if statement, you define a block of code statements
that are performed only if a condition is met.
Adding else if Clauses
You can choose between code blocks by adding else if clauses to
an if statement, like this:


if (x == 50) {
    Console.WriteLine("First Code Block Selected");
} else if (x == 60) {
    Console.WriteLine("Second Code Block Selected");
} else if (x == 100) {
    Console.WriteLine("Third Code Block Selected");
}
Adding an else clause
An if statement can contain a single else clause that will be
performed if the condition in the statement and all of the
conditions in any else if clauses evaluate to false. The else clause
must come at the end of the if statement, like this:


if (x == 100) {
    Console.WriteLine("First Code Block Selected");
} else {
    Console.WriteLine("Second Code Block Selected");
}
Using a switch Statement
A switch statement selects one of a set of code statements to execute by
comparing a value to a set of constants.

string myName = "Adam Freeman";
switch (myName) {
    case "Joe Smith":
      Console.WriteLine("Name is Joe Smith");
      break;
    case "Adam Freeman":
      Console.WriteLine("Name is Adam Freeman");
      break;
    default:
      Console.WriteLine("Default reached");
      break;
}
Using a switch Statement
(Cont.)
Jumping to Another Switch Section
You can combine the statements in switch sections by using a goto
case statement, which jumps to the specified section, as follows:

switch (myName) {
    case "Joe Smith":
      Console.WriteLine("Name is Joe Smith");
      break;
    case "Adam Freeman":
      Console.WriteLine("Name is Adam Freeman, Jane Jones or Peter
Kent");
      goto case "Joe Smith";
    default:
      Console.WriteLine("Default reached");
      break;
}
Iterating Data Items
One of the most common programming tasks is to
perform the same series of actions for each
element in a sequence of data items—for example,
items in an array or a collection (see in next
Chapter). C# supports four ways of performing
iterations.
Using a for Loop
A for loop repeatedly performs a block of statements while a condition
remains true. Before the first iteration, an initializer executes one or
more expressions. At the end of each iteration, an iterator executes one
or more statements. Another iteration will be performed if the
condition evaluates to true.
Breaking Out of a for Loop
You can terminate a for loop before the condition evaluates
to false by using the break keyword, like this:

for (int i = 0; i < 100; i++) {
   Console.WriteLine("Iteration for value: {0}", i);
   if (i == 5) {
      break;
   }
}
Continuing to the Next Iteration
Normally a for loop will perform all the statements in the code
block before moving on to the next iteration. By using the
continue keyword, you can move to the next iteration without
performing any statements that follow. Here is an example:

for (int i = 0; i < 5; i++) {
    Console.WriteLine("Iteration for value: {0}", i);
    if (i == 2 || i == 3) {
        continue;
    }
    Console.WriteLine("Reached end of iteration for value: {0}",
i);
}
Using a do…while Loop
Using a while Loop
Numeric Types
C# has a number of predefined numeric types that
can be referred to using keywords. I tend use the
keywords, rather than the type names, but different
programmers have varying styles, and it is useful to
know how the keywords and the types relate to
each other. There is no advantage in using one
style over the other; the C# compiler converts the
keywords into the correct type automatically, which
means that you can mix keywords and types freely,
even in the same code.
Numeric Types (Cont.)
Using Numeric Literals
C# allows you to define numeric values literally so
that you can just use the value of the number in a
statement, like this:
Using Numeric Operators
Numeric types have limited value on their
own; they need to be combined with
operators that allow you to perform
calculations and otherwise manipulate the
values they represent. In the following
sections, I describe the five kinds of numeric
operator that C# supports.
Using Numeric Operators
(Cont.)
Arithmetic Operators
C# includes basic arithmetic operators that
allow you to perform basic calculations.
Unary Operators
The C# unary operators are so-called because they work on
a single numeric value.
Unary Operators (Cont.)
// define a number
float f = 26.765f;
// use the unary plus operator
float up = +f;
// use the unary minus operator
float um = -f;
// print out the results
Console.WriteLine("Unary plus result: {0}",
up);
Console.WriteLine("Unary minus result: {0}",
um);
Relational Operators
The C# relational operators allow you to compare
one numeric type to another.
Assignment Operators
With one exception, the assignment operators allow you to
conveniently apply one of the other operators and assign
the result in a single step.
Assignment Operators
(Cont.)
The assignment operators allow shorthand when you want
to perform an operation on a variable and assign the result
to the same variable. So, these statements:


int x = 10;
x = x + 2;


can be written as follows:


int x = 10;
x += 2;
Classes and Objects
You create new functionality in C#
programs by defining classes.
Classes are the blueprints used to
create the objects that you use to
represent items in your program.
Creating a Basic Class
Remember that classes are the blueprints from which objects are
created. Imagine we had a blueprint for a car; for the sake of an
example, let’s say the blueprint is for a 2010 Volvo C30. The
blueprint specifies every detail of the car, but it isn’t a car itself. It
just describes how the car should be constructed. We have to go
through the process of constructing a car from the blueprint to
end up with something that we can get into and drive away, and
that something will be a Volvo C30, because that’s what we used
as the blueprint.

public class VolvoC30 {
   // class body
}
Creating a Basic Class
(Cont.)
This class is so simple that it doesn’t do anything yet, but
we’ll add some features as we work through.
Adding features to a Class
It is as though we wrote “Volvo C30” on a blueprint
and then just walked away. If we gave the blueprint to
someone else, they’d have only the name to go on. We
have not provided any information about what
features we require. We add features to a class by
adding class members. There are a range of different
categories of class members, some of which are
described in the following sections. All of the different
member types are described in depth in the chapters
that follow.
Adding Fields
A field is a piece of information that each object created from the class
will have; this can be one of the built-in value types that C# supports
(such as a number or a Boolean value), or it can be another object (a
reference type). If a field refers to another object, then that object can
be one of those included with the .NET Framework (such as a string), or
it can be a type we have created, like the VolvoC30 class.


public class VolvoC30 {
   public string CarOwner;
   public string PaintColor;
   public int MilesPerGallon= 30;
}
Adding Methods
Methods let your object perform actions. That’s a pretty
wide definition, and the nature of your methods will
depend on the nature of your class. If we remain with the
car metaphor, then we could have methods to start the
engine, open the window, plot a navigation route, and so
on. If our class represented a person, we might have
methods that change marital status, employment status,
and relationships, with objects representing other people.
Adding Methods (Cont.)
public class VolvoC30 {
    public string CarOwner;
    public string PaintColor;
    public int MilesPerGallon = 30;
    public int CalculateFuelForTrip(int tripDistance) {
        return tripDistance / MilesPerGallon;
    }
    public void PrintCarDetails() {
        System.Console.WriteLine("--- Car Details ---");
        System.Console.WriteLine("Car Owner: {0}", CarOwner);
        System.Console.WriteLine("Car Color: {0}", PaintColor);
        System.Console.WriteLine("Gas Mileage: {0} mpg",
MilesPerGallon);
    }
}
Adding a Constructor
A constructor is a special method that you use when creating a new object, allowing you
to provide data via parameters that will set the initial state of the object.
Creating Objects from
Classes
Objects are often referred to as instances, for example,

“This object is an instance of the VolvoC30 class.” This is

often shortened so that it is commonly said that “This is an

instance of VolvoC30.” To create an object from a class, we

use the new operator, sometimes referred to as the

construction or instantiation operator. We tell the new

operator which class to work with, and it creates a new

object of the type representing by the class.
Creating Objects from Classes
(Cont.)
Using Objects
Once we have created an object, we can work with it using
the members we defined in the class. Working with an
object typically means doing one of two things: changing
the value of a field to change the state of an object or using
one of the objects methods to perform an action. Methods
can modify the value of fields as well, so sometimes you’ll
be performing a calculation and modifying the state of an
object in one go.
Reading and Modifying Fields
To read the value of a field, we use the dot operator (.) to combine the
name we have given to the object instance and the name of the field
we want to access.

// create a new object of the VolvoC30 type
VolvoC30 myCar = new VolvoC30("Adam Freeman", "Black");
// create a second VolvoC30 object
VolvoC30 joesCar = new VolvoC30("Joe Smith", "Silver");
// read the value of the myCar.CarOwner field
string owner = myCar.CarOwner;
Console.WriteLine("Field value: {0}", owner);
Using Static Fields
The fields in all the examples in the previous sections have been instance fields,
meaning that each object has its own field. This is why we have to use the object
reference with the dot operator to access the field. We have to tell the .NET runtime
which object’s field we want to work with.
public class VolvoC30 {

   public string CarOwner;

   public string PaintColor;

   public int MilesPerGallon = 30;

   public static int EngineCapacity = 2000;

   public VolvoC30(string newOwner, string paintColor) {

       CarOwner = newOwner;

       PaintColor = paintColor;

   }
Using Static Fields (Cont.)
public int CalculateFuelForTrip(int tripDistance) {

        return tripDistance / MilesPerGallon;

    }

    public void PrintCarDetails() {

        System.Console.WriteLine("--- Car Details ---");

        System.Console.WriteLine("Car Owner: {0}", CarOwner);

        System.Console.WriteLine("Car Color: {0}", PaintColor);

        System.Console.WriteLine("Gas Mileage: {0} mpg", MilesPerGallon);

        System.Console.WriteLine("Engine Capacity: {0} cc", EngineCapacity);

    }

}
Calling Methods
A new object doesn’t just get a set of fields and properties; it also gets its own set of
methods. In our VolvoC30 class, we defined two methods, called PrintCarDetails and
CalculateFuelForTrip.

public class VolvoC30 {

   public string CarOwner;

   public string PaintColor;

   public int MilesPerGallon = 30;

   public VolvoC30(string newOwner, string paintColor) {

       CarOwner = newOwner;

       PaintColor = paintColor;

   }
Calling Methods (Cont.)
public void PrintCarDetails() {

        System.Console.WriteLine("--- Car Details ---");

        System.Console.WriteLine("Car Owner: {0}", CarOwner);

        System.Console.WriteLine("Car Color: {0}", PaintColor);

        System.Console.WriteLine("Gas Mileage: {0} mpg",

MilesPerGallon);

    }

}
Using Access Modifiers
You can restrict the use of a class by applying an access modifier to the class
definition.

More Related Content

What's hot

Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerVineet Kumar Saini
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic conceptsAbhinav Vatsa
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageRakesh Roshan
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to cHattori Sidek
 
Learn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & ArraysLearn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & ArraysEng Teong Cheah
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageHossam Ghareeb
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 FocJAYA
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSivakumar R D .
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of CSuchit Patel
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsEng Teong Cheah
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiSowmya Jyothi
 
Learning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageLearning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageAbhishek Dwivedi
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoobirbal
 
IOS Swift language 2nd tutorial
IOS Swift language 2nd tutorialIOS Swift language 2nd tutorial
IOS Swift language 2nd tutorialHassan A-j
 

What's hot (19)

Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
 
Introduction of C#
Introduction of C#Introduction of C#
Introduction of C#
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic concepts
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 
Learn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & ArraysLearn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & Arrays
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
 
Pc module1
Pc module1Pc module1
Pc module1
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.Sivakumar
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 
C programming
C programmingC programming
C programming
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
 
Learning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageLearning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C Language
 
CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
 
IOS Swift language 2nd tutorial
IOS Swift language 2nd tutorialIOS Swift language 2nd tutorial
IOS Swift language 2nd tutorial
 

Viewers also liked

Computer programming chapter ( 3 )
Computer programming chapter ( 3 ) Computer programming chapter ( 3 )
Computer programming chapter ( 3 ) Ibrahim Elewah
 
C++ Programming Club-Lecture 1
C++ Programming Club-Lecture 1C++ Programming Club-Lecture 1
C++ Programming Club-Lecture 1Ammara Javed
 
Programming Fundamental Presentation
Programming Fundamental PresentationProgramming Fundamental Presentation
Programming Fundamental Presentationfazli khaliq
 
Computer Programming in C++
Computer Programming in C++ Computer Programming in C++
Computer Programming in C++ Dreamtech Press
 
c++ programming Unit 1 introduction to c++
c++ programming Unit 1  introduction to c++c++ programming Unit 1  introduction to c++
c++ programming Unit 1 introduction to c++AAKASH KUMAR
 
Intro To Programming Concepts
Intro To Programming ConceptsIntro To Programming Concepts
Intro To Programming ConceptsJussi Pohjolainen
 
SSRP Self Learning Guide Maths Class 10 - In Hindi
SSRP Self Learning Guide Maths Class 10 - In HindiSSRP Self Learning Guide Maths Class 10 - In Hindi
SSRP Self Learning Guide Maths Class 10 - In Hindikusumafoundation
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingHaris Bin Zahid
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented languagefarhan amjad
 
Introduction - Imperative and Object-Oriented Languages
Introduction - Imperative and Object-Oriented LanguagesIntroduction - Imperative and Object-Oriented Languages
Introduction - Imperative and Object-Oriented LanguagesGuido Wachsmuth
 
Cbse class 10 hindi course b model answers by candidates 2015
Cbse class 10 hindi course b model answers by candidates 2015Cbse class 10 hindi course b model answers by candidates 2015
Cbse class 10 hindi course b model answers by candidates 2015Saurabh Singh Negi
 
Object Oriented Language
Object Oriented LanguageObject Oriented Language
Object Oriented Languagedheva B
 

Viewers also liked (20)

Computer programming chapter ( 3 )
Computer programming chapter ( 3 ) Computer programming chapter ( 3 )
Computer programming chapter ( 3 )
 
C++ Programming Club-Lecture 1
C++ Programming Club-Lecture 1C++ Programming Club-Lecture 1
C++ Programming Club-Lecture 1
 
Programming Fundamental Presentation
Programming Fundamental PresentationProgramming Fundamental Presentation
Programming Fundamental Presentation
 
Computer Programming in C++
Computer Programming in C++ Computer Programming in C++
Computer Programming in C++
 
High Level Programming Constructs
High Level Programming ConstructsHigh Level Programming Constructs
High Level Programming Constructs
 
c++ programming Unit 1 introduction to c++
c++ programming Unit 1  introduction to c++c++ programming Unit 1  introduction to c++
c++ programming Unit 1 introduction to c++
 
Intro To Programming Concepts
Intro To Programming ConceptsIntro To Programming Concepts
Intro To Programming Concepts
 
C++ language
C++ languageC++ language
C++ language
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 
Oops
OopsOops
Oops
 
Labsheet_3
Labsheet_3Labsheet_3
Labsheet_3
 
SSRP Self Learning Guide Maths Class 10 - In Hindi
SSRP Self Learning Guide Maths Class 10 - In HindiSSRP Self Learning Guide Maths Class 10 - In Hindi
SSRP Self Learning Guide Maths Class 10 - In Hindi
 
Unit i
Unit iUnit i
Unit i
 
Labsheet2
Labsheet2Labsheet2
Labsheet2
 
Oops Concepts
Oops ConceptsOops Concepts
Oops Concepts
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
 
Introduction - Imperative and Object-Oriented Languages
Introduction - Imperative and Object-Oriented LanguagesIntroduction - Imperative and Object-Oriented Languages
Introduction - Imperative and Object-Oriented Languages
 
Cbse class 10 hindi course b model answers by candidates 2015
Cbse class 10 hindi course b model answers by candidates 2015Cbse class 10 hindi course b model answers by candidates 2015
Cbse class 10 hindi course b model answers by candidates 2015
 
Object Oriented Language
Object Oriented LanguageObject Oriented Language
Object Oriented Language
 

Similar to Chapter3: fundamental programming

Similar to Chapter3: fundamental programming (20)

CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Cordovilla
CordovillaCordovilla
Cordovilla
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
 
C# slid
C# slidC# slid
C# slid
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
Visual c sharp
Visual c sharpVisual c sharp
Visual c sharp
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
C programming
C programmingC programming
C programming
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
New features in C# 6
New features in C# 6New features in C# 6
New features in C# 6
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).ppt
 
Beginner C++ easy slide and simple definition with questions
Beginner C++ easy slide and simple definition with questions Beginner C++ easy slide and simple definition with questions
Beginner C++ easy slide and simple definition with questions
 
C programming notes
C programming notesC programming notes
C programming notes
 
C programming notes.pdf
C programming notes.pdfC programming notes.pdf
C programming notes.pdf
 

More from Ngeam Soly

សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាម
សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាមសន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាម
សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាមNgeam Soly
 
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...Ngeam Soly
 
មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++Ngeam Soly
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.netNgeam Soly
 
Chapter 2: Ms SQL Server
Chapter 2: Ms SQL ServerChapter 2: Ms SQL Server
Chapter 2: Ms SQL ServerNgeam Soly
 
1 introduction
1   introduction1   introduction
1 introductionNgeam Soly
 
Chapter01 introduction
Chapter01 introductionChapter01 introduction
Chapter01 introductionNgeam Soly
 
Slide for presentation
Slide for presentation Slide for presentation
Slide for presentation Ngeam Soly
 
Accounting assingment year ii
Accounting assingment year iiAccounting assingment year ii
Accounting assingment year iiNgeam Soly
 
Account's Assignment
Account's AssignmentAccount's Assignment
Account's AssignmentNgeam Soly
 
Chapter5: Usage of Build-In Functions or Methods
Chapter5: Usage of Build-In Functions or MethodsChapter5: Usage of Build-In Functions or Methods
Chapter5: Usage of Build-In Functions or MethodsNgeam Soly
 

More from Ngeam Soly (11)

សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាម
សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាមសន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាម
សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាម
 
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...
 
មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
Chapter 2: Ms SQL Server
Chapter 2: Ms SQL ServerChapter 2: Ms SQL Server
Chapter 2: Ms SQL Server
 
1 introduction
1   introduction1   introduction
1 introduction
 
Chapter01 introduction
Chapter01 introductionChapter01 introduction
Chapter01 introduction
 
Slide for presentation
Slide for presentation Slide for presentation
Slide for presentation
 
Accounting assingment year ii
Accounting assingment year iiAccounting assingment year ii
Accounting assingment year ii
 
Account's Assignment
Account's AssignmentAccount's Assignment
Account's Assignment
 
Chapter5: Usage of Build-In Functions or Methods
Chapter5: Usage of Build-In Functions or MethodsChapter5: Usage of Build-In Functions or Methods
Chapter5: Usage of Build-In Functions or Methods
 

Recently uploaded

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 

Recently uploaded (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

Chapter3: fundamental programming

  • 2. C# Syntax • Like C/C++ and Java
  • 4. Identifiers (Cont.) • Consist of Unicode characters • Can begin with a letter or an underscore • Cannot a keywords • eg. int, string, double, …
  • 5. Capitalization Styles • Pascal case, eg. MyValue • Camel case, eg. myValueNumber • Uppercase, eg. UI
  • 10. Statements There are different kinds of statement in C#: • A code block • Declaration statements • Expression statements • Selection statements • Iteration statements • Control statements
  • 12. Types Every piece of data in C# must have a type. This is a key part of C# being a strongly typed programming language. The C# compiler and runtime both use the type of each data item to reduce some kinds of programming problems. There are two kinds of types in C#: value types and reference types. The distinction between the two causes programmers new to object-oriented programming a lot of confusion.
  • 13. Value Types Value-type variables directly contain their data—that is to say that the content of a value-type variable is its value. The following statement assigns a value of 25 to a variable called myInt. The type of the variable myInt is int, which is a value type.
  • 15. Reference Types Reference types come in two parts—an object and the reference to that object. Here is a statement that creates a reference-type object: StringBuilder myObject = new StringBuilder("Adam"); The StringBuilder type holds a string of characters. Figure 4-10 shows the reference type in memory. You don’t deal with the object directly— instead, you work with it via the reference.
  • 16. Definite Assignment and Null References C# requires that you assign a value to a variable before you read the value of the variable. The compiler checks your code to ensure that every path through your code assigns a value to every variable that you read. This is called definite assignment. The assignment of a value doesn’t need to occur when you declare the variable; you just have to make sure that you have made an assignment before you read the variable value. Here are some statements that demonstrate this: int myInt; // declare a variable, but don't assign to it myInt = 20; // assign a value to the variable int sum = 100 + myInt; // we can read the value because we have made an assignment
  • 17. Common Programming Tasks The chapters that follow focus on the major features of C#: classes, methods, fields, parameters, delegates, and so on. These are such important topics that it can be easy to overlook the tasks that are most commonly required of programmers. In the following sections, I describe how to assign values to variables, make comparisons between values, selectively execute blocks of code, and iterate over data items.
  • 18. Assigning Values The C# assignment operator is the equals sign (=). Figure 4-13 shows how the assignment operator is used to assign a value to a variable.
  • 19. Making Comparisions The C# comparison operator (==) is used to determine whether two variables are the same.
  • 21. Performing Selections Selection statements let you select blocks of code statements to be executed if a condition is met. C# supports two selection statements—the if statement and the switch statement.
  • 22. Using an if Statement With an if statement, you define a block of code statements that are performed only if a condition is met.
  • 23. Adding else if Clauses You can choose between code blocks by adding else if clauses to an if statement, like this: if (x == 50) { Console.WriteLine("First Code Block Selected"); } else if (x == 60) { Console.WriteLine("Second Code Block Selected"); } else if (x == 100) { Console.WriteLine("Third Code Block Selected"); }
  • 24. Adding an else clause An if statement can contain a single else clause that will be performed if the condition in the statement and all of the conditions in any else if clauses evaluate to false. The else clause must come at the end of the if statement, like this: if (x == 100) { Console.WriteLine("First Code Block Selected"); } else { Console.WriteLine("Second Code Block Selected"); }
  • 25. Using a switch Statement A switch statement selects one of a set of code statements to execute by comparing a value to a set of constants. string myName = "Adam Freeman"; switch (myName) { case "Joe Smith": Console.WriteLine("Name is Joe Smith"); break; case "Adam Freeman": Console.WriteLine("Name is Adam Freeman"); break; default: Console.WriteLine("Default reached"); break; }
  • 26. Using a switch Statement (Cont.)
  • 27. Jumping to Another Switch Section You can combine the statements in switch sections by using a goto case statement, which jumps to the specified section, as follows: switch (myName) { case "Joe Smith": Console.WriteLine("Name is Joe Smith"); break; case "Adam Freeman": Console.WriteLine("Name is Adam Freeman, Jane Jones or Peter Kent"); goto case "Joe Smith"; default: Console.WriteLine("Default reached"); break; }
  • 28. Iterating Data Items One of the most common programming tasks is to perform the same series of actions for each element in a sequence of data items—for example, items in an array or a collection (see in next Chapter). C# supports four ways of performing iterations.
  • 29. Using a for Loop A for loop repeatedly performs a block of statements while a condition remains true. Before the first iteration, an initializer executes one or more expressions. At the end of each iteration, an iterator executes one or more statements. Another iteration will be performed if the condition evaluates to true.
  • 30. Breaking Out of a for Loop You can terminate a for loop before the condition evaluates to false by using the break keyword, like this: for (int i = 0; i < 100; i++) { Console.WriteLine("Iteration for value: {0}", i); if (i == 5) { break; } }
  • 31. Continuing to the Next Iteration Normally a for loop will perform all the statements in the code block before moving on to the next iteration. By using the continue keyword, you can move to the next iteration without performing any statements that follow. Here is an example: for (int i = 0; i < 5; i++) { Console.WriteLine("Iteration for value: {0}", i); if (i == 2 || i == 3) { continue; } Console.WriteLine("Reached end of iteration for value: {0}", i); }
  • 34. Numeric Types C# has a number of predefined numeric types that can be referred to using keywords. I tend use the keywords, rather than the type names, but different programmers have varying styles, and it is useful to know how the keywords and the types relate to each other. There is no advantage in using one style over the other; the C# compiler converts the keywords into the correct type automatically, which means that you can mix keywords and types freely, even in the same code.
  • 36. Using Numeric Literals C# allows you to define numeric values literally so that you can just use the value of the number in a statement, like this:
  • 37. Using Numeric Operators Numeric types have limited value on their own; they need to be combined with operators that allow you to perform calculations and otherwise manipulate the values they represent. In the following sections, I describe the five kinds of numeric operator that C# supports.
  • 39. Arithmetic Operators C# includes basic arithmetic operators that allow you to perform basic calculations.
  • 40. Unary Operators The C# unary operators are so-called because they work on a single numeric value.
  • 41. Unary Operators (Cont.) // define a number float f = 26.765f; // use the unary plus operator float up = +f; // use the unary minus operator float um = -f; // print out the results Console.WriteLine("Unary plus result: {0}", up); Console.WriteLine("Unary minus result: {0}", um);
  • 42. Relational Operators The C# relational operators allow you to compare one numeric type to another.
  • 43. Assignment Operators With one exception, the assignment operators allow you to conveniently apply one of the other operators and assign the result in a single step.
  • 44. Assignment Operators (Cont.) The assignment operators allow shorthand when you want to perform an operation on a variable and assign the result to the same variable. So, these statements: int x = 10; x = x + 2; can be written as follows: int x = 10; x += 2;
  • 45. Classes and Objects You create new functionality in C# programs by defining classes. Classes are the blueprints used to create the objects that you use to represent items in your program.
  • 46. Creating a Basic Class Remember that classes are the blueprints from which objects are created. Imagine we had a blueprint for a car; for the sake of an example, let’s say the blueprint is for a 2010 Volvo C30. The blueprint specifies every detail of the car, but it isn’t a car itself. It just describes how the car should be constructed. We have to go through the process of constructing a car from the blueprint to end up with something that we can get into and drive away, and that something will be a Volvo C30, because that’s what we used as the blueprint. public class VolvoC30 { // class body }
  • 47. Creating a Basic Class (Cont.) This class is so simple that it doesn’t do anything yet, but we’ll add some features as we work through.
  • 48. Adding features to a Class It is as though we wrote “Volvo C30” on a blueprint and then just walked away. If we gave the blueprint to someone else, they’d have only the name to go on. We have not provided any information about what features we require. We add features to a class by adding class members. There are a range of different categories of class members, some of which are described in the following sections. All of the different member types are described in depth in the chapters that follow.
  • 49. Adding Fields A field is a piece of information that each object created from the class will have; this can be one of the built-in value types that C# supports (such as a number or a Boolean value), or it can be another object (a reference type). If a field refers to another object, then that object can be one of those included with the .NET Framework (such as a string), or it can be a type we have created, like the VolvoC30 class. public class VolvoC30 { public string CarOwner; public string PaintColor; public int MilesPerGallon= 30; }
  • 50. Adding Methods Methods let your object perform actions. That’s a pretty wide definition, and the nature of your methods will depend on the nature of your class. If we remain with the car metaphor, then we could have methods to start the engine, open the window, plot a navigation route, and so on. If our class represented a person, we might have methods that change marital status, employment status, and relationships, with objects representing other people.
  • 51. Adding Methods (Cont.) public class VolvoC30 { public string CarOwner; public string PaintColor; public int MilesPerGallon = 30; public int CalculateFuelForTrip(int tripDistance) { return tripDistance / MilesPerGallon; } public void PrintCarDetails() { System.Console.WriteLine("--- Car Details ---"); System.Console.WriteLine("Car Owner: {0}", CarOwner); System.Console.WriteLine("Car Color: {0}", PaintColor); System.Console.WriteLine("Gas Mileage: {0} mpg", MilesPerGallon); } }
  • 52. Adding a Constructor A constructor is a special method that you use when creating a new object, allowing you to provide data via parameters that will set the initial state of the object.
  • 53. Creating Objects from Classes Objects are often referred to as instances, for example, “This object is an instance of the VolvoC30 class.” This is often shortened so that it is commonly said that “This is an instance of VolvoC30.” To create an object from a class, we use the new operator, sometimes referred to as the construction or instantiation operator. We tell the new operator which class to work with, and it creates a new object of the type representing by the class.
  • 54. Creating Objects from Classes (Cont.)
  • 55. Using Objects Once we have created an object, we can work with it using the members we defined in the class. Working with an object typically means doing one of two things: changing the value of a field to change the state of an object or using one of the objects methods to perform an action. Methods can modify the value of fields as well, so sometimes you’ll be performing a calculation and modifying the state of an object in one go.
  • 56. Reading and Modifying Fields To read the value of a field, we use the dot operator (.) to combine the name we have given to the object instance and the name of the field we want to access. // create a new object of the VolvoC30 type VolvoC30 myCar = new VolvoC30("Adam Freeman", "Black"); // create a second VolvoC30 object VolvoC30 joesCar = new VolvoC30("Joe Smith", "Silver"); // read the value of the myCar.CarOwner field string owner = myCar.CarOwner; Console.WriteLine("Field value: {0}", owner);
  • 57. Using Static Fields The fields in all the examples in the previous sections have been instance fields, meaning that each object has its own field. This is why we have to use the object reference with the dot operator to access the field. We have to tell the .NET runtime which object’s field we want to work with. public class VolvoC30 { public string CarOwner; public string PaintColor; public int MilesPerGallon = 30; public static int EngineCapacity = 2000; public VolvoC30(string newOwner, string paintColor) { CarOwner = newOwner; PaintColor = paintColor; }
  • 58. Using Static Fields (Cont.) public int CalculateFuelForTrip(int tripDistance) { return tripDistance / MilesPerGallon; } public void PrintCarDetails() { System.Console.WriteLine("--- Car Details ---"); System.Console.WriteLine("Car Owner: {0}", CarOwner); System.Console.WriteLine("Car Color: {0}", PaintColor); System.Console.WriteLine("Gas Mileage: {0} mpg", MilesPerGallon); System.Console.WriteLine("Engine Capacity: {0} cc", EngineCapacity); } }
  • 59. Calling Methods A new object doesn’t just get a set of fields and properties; it also gets its own set of methods. In our VolvoC30 class, we defined two methods, called PrintCarDetails and CalculateFuelForTrip. public class VolvoC30 { public string CarOwner; public string PaintColor; public int MilesPerGallon = 30; public VolvoC30(string newOwner, string paintColor) { CarOwner = newOwner; PaintColor = paintColor; }
  • 60. Calling Methods (Cont.) public void PrintCarDetails() { System.Console.WriteLine("--- Car Details ---"); System.Console.WriteLine("Car Owner: {0}", CarOwner); System.Console.WriteLine("Car Color: {0}", PaintColor); System.Console.WriteLine("Gas Mileage: {0} mpg", MilesPerGallon); } }
  • 61. Using Access Modifiers You can restrict the use of a class by applying an access modifier to the class definition.