C# Programming: 3.0 Fundamentals II

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

C# Programming Purvis Samsoodeen

C# Programming
By Purvis Samsoodeen

3.0 Fundamentals II

3.1.0 Language Features

3.1.1 Classes, Objects and Methods

 Class fundamentals
 Instantiate an object
 Method basics
 Method parameters
 Return a value from a method
 Constructors
 new
 Garbage collection
 Destructors
 The this keyword

A class is a template that defines the form of an object. It typically


specifies both code and data, with the code acting on the data. C# uses
a class specification to construct objects. Objects are instances of a
class. Thus, a class is essentially a set of plans that specify how to
build an object. It is important to be clear on one issue: A class is a
logical abstraction. It is not until an object of that class has been
created that a physical representation of that class exists in memory.

A class is created by using the keyword class. The general form of a


class definition that contains only instance variables and methods is
shown here:

Page 1 of 10
C# Programming Purvis Samsoodeen

class classname {
// Declare instance variables.
access type var1;
access type var2;
// ...
access type varN;
// Declare methods.
access ret-type method1(parameters) {
// body of method
}
access ret-type method2(parameters) {
// body of method
}
// ...
access ret-type methodN(parameters) {
// body of method
}
}

3.1.2 Data Types and Operators

 C#’s basic types

C# contains two general categories of built-in data types: value


types and reference types. The difference between the two types is
what a variable contains. For a value type, a variable holds an
actual value, such 101 or 98.6. For a reference type, a variable
holds a reference to the value.

 Format output
 Literals

In C#, literals refer to fixed values that are represented in their


human-readable form. For example, the number 100 is a literal.

C# literals can be of any of the value types. The way each literal is
represented depends upon its type. Character literals are enclosed
between single quotes. For example ‘a’ and ‘%’ are both character
literals.
Integer literals are specified as numbers without fractional
components. For example, 10 and –100 are integer literals.

Page 2 of 10
C# Programming Purvis Samsoodeen

Floating-point literals require the use of the decimal point followed


by the number’s fractional component. For example, 11.123 is a
floating-point literal. C# also allows you to use scientific notation
for floating-point numbers.

 Initialize variables
 The scope rules of a method

The scope defined by a method begins with its opening curly brace
and ends with its closing curly brace. However, if that method has
parameters, they, too, are included within the scope defined by the
method.
As a general rule, local variables declared inside a scope is not
visible to code that is defined outside that scope. Thus, when you
declare a variable within a scope, you are preventing it from being
accessed or modified by code outside the scope. Indeed, the scope
rules provide the foundation for encapsulation.
Scopes can be nested. For example, each time you create a block of
code, you are creating a new, nested scope. When this occurs, the
outer scope encloses the inner scope. This means that local
variables declared in the outer scope will be visible to code within
the inner scope.
However, the reverse is not true. Local variables declared within
the inner scope will not be visible outside it.

// Demonstrate block scope.

using System;

class ScopeDemo {
static void Main() {
int x; // known to all code within Main()
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
Console.WriteLine("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
Console.WriteLine("x is " + x);
}
}

Page 3 of 10
C# Programming Purvis Samsoodeen

 Type conversion and casting

A cast is an instruction to the compiler to convert an expression


into a specified type.

 The arithmetic operators

 The relational and logical operators

 The assignment operator

The assignment operator is the single equal sign, =. The


assignment operator works in C# much as it does in other
computer languages. It has this general form: var = expression;
Here, the type of var must be compatible with the type of
expression.

 Expressions

Page 4 of 10
C# Programming Purvis Samsoodeen

3.1.3 Operators and Operator Overloading

 Operator overloading fundamentals

C# allows you to define the meaning of an operator relative to a class


that you create. This process is called operator overloading. By
overloading an operator, you expand its usage to your class. The
effects of the operator are completely under your control and may
differ from class to class. For example, a class that defines a linked list
might use the + operator to add an object to the list. A class that
implements a stack might use the + to push an object onto the stack.
Another class might use the + operator in an entirely different way.
When an operator is overloaded, none of its original meaning is lost. It
is simply that a new operation, relative to a specific class, is added.
Therefore, overloading the + to handle a linked list, for example, does
not cause its meaning relative to integers (that is, addition) to be
changed.

 Overload binary operators

// General form for overloading a binary operator.


public static ret-type operator op(param-type1 operand1, param-type2
operand2)
{
// operations
}

Refer listing 1 in the code handout for an example.

 Overload unary operators

// General form for overloading a unary operator.


public static ret-type operator op(param-type operand)
{
// operations
}

Refer listing 2 in the code handout for an example.

 Overload relational operators


Page 5 of 10
C# Programming Purvis Samsoodeen

The relational operators, such as = = or <, can also be overloaded, and


the process is straightforward. Usually, an overloaded relational
operator returns a true or false value. This is in keeping with the
normal usage of these operators and allows the overloaded relational
operators to be used in conditional expressions. If you return a
different type result, you are greatly restricting the operator’s utility.

Refer listing 5 in the code handout for an example.

 Indexers

As you know, array indexing is performed using the [ ] operator. It is


possible to overload the [ ] operator for classes that you create, but you
don’t use an operator method. Instead, you create an indexer. An
indexer allows an object to be indexed like an array. The main use of
indexers is to support the creation of specialized arrays that are subject
to one or more constraints. However, you can use an indexer for any
purpose for which an array-like syntax is beneficial. Indexers can have
one or more dimensions.

One-dimensional indexers have this general form:

element-type this[int index] {


// The get accessor.
get {
// return the value specified by index
}
}
// The set accessor.
set {
// set the value specified by index
}
}

Refer listing 6 in the code handout for an example.

 Properties

Page 6 of 10
C# Programming Purvis Samsoodeen

A property combines a field with the methods that access it.


Properties are similar to indexers. A property consists of a name, along
with get and set accessors. The accessors are used to get and set the
value of a variable. The key benefit of a property is that its name can
be used in expressions and assignments like a normal variable, but in
actuality, the get and set accessors are automatically invoked. This is
similar to the way that an indexer’s get and set accessors are
automatically used.
The general form of a property is shown here:
type name {
get {
// get accessor code
}
set {
// set accessor code
}
}

3.2.0 Object Oriented Programming

3.2.1 What is OOP?

Object-oriented programming took the best ideas of structured


programming and combined them with several new concepts. The result
was a different and better way of organizing a program. In the most
general sense, a program can be organized in one of two ways: around its
code (what is happening) or around its data (what is being affected). Using
only structured programming techniques, programs are typically organized
around code. This approach can be thought of as “code acting on data.”

Object-oriented programs work the other way around. They are organized
around data, with the key principle being “data controlling access to
code.” In an object-oriented language, you define the data and the routines
that are permitted to act on that data. Thus, a data type defines precisely
what sort of operations can be applied to that data.

3.2.2 The Four Pillars of OOP

3.3.0 Inheritance, Polymorphism


Page 7 of 10
C# Programming Purvis Samsoodeen

3.3.1 Abstraction

Abstraction is simplifying complex reality by modeling classes


appropriate to the problem, and working at the most appropriate level of
inheritance for a given aspect of the problem.
For example, Lassie the Dog may be treated as a Dog much of the time, a
Collie when necessary to access Collie-specific attributes or behaviors,
and as an Animal (perhaps the parent class of Dog) when counting
Timmy’spets.
Abstraction is also achieved through Composition For example, a class
Car would be made up of an Engine, Gearbox, Steering objects, and many
more components. To build the Car class, one does not need to know how
the different components work internally, but only how to interface with
them, i.e., send messages to them, receive messages from them, and
perhaps make the different objects composing the class interact with each
other.

3.3.2 Polymorphism

Polymorphism (from Greek, meaning “many forms”) is the quality that


allows one interface to access a general class of actions. A simple example
of polymorphism is found in the steering wheel of an automobile. The
steering wheel (the interface) is the same, no matter what type of actual
steering mechanism is used. That is, the steering wheel works the same
whether your car has manual steering, power steering, or rack-and-pinion
steering. Thus, turning the steering wheel left causes the car to go left no
matter what type of steering is used. The benefit of the uniform interface
is, of course, that once you know how to operate the steering wheel, you
can drive any type of car.
The same principle can also apply to programming. For example, consider
a stack (which is a first-in, last-out list). You might have a program that
requires three different types of stacks. One stack is used for integer
values, one for floating-point values, and one for characters. In this case,
the algorithm that implements each stack is the same, even though the data
being stored differs. In a non–object-oriented language, you would be
required to create three different sets of stack routines, with each set using
different names. However, because of polymorphism, in C#, you can
specify the general form of a stack once and then use it for all three
specific situations. This way, if you know how to use one stack, you can
use them all.
Page 8 of 10
C# Programming Purvis Samsoodeen

More generally, the concept of polymorphism is often expressed by the


phrase “one interface, multiple methods.” This means that it is possible to
design a generic interface to a group of related activities. Polymorphism
helps reduce complexity by allowing the same interface to be used to
specify a general class of action. It is the compiler’s job to select the
specific action (that is, method) as it applies to each situation. You, the
programmer, don’t need to do this selection manually. You need only
remember and utilize the general interface.

3.3.3 Inheritance

Inheritance is the process by which one object can acquire the properties
of another object. This is important because it supports the concept of
hierarchical classification. If you think about it, most knowledge is made
manageable by hierarchical (that is, top-down) classifications.
For example, a Red Delicious apple is part of the classification apple,
which, in turn, is part of the fruit class, which is under the larger class
food. That is, the food class possesses certain qualities (edible, nutritious,
and so on) that also, logically, apply to its subclass, fruit. In addition to
these qualities, the fruit class has specific characteristics (juicy, sweet, and
so forth) that distinguish it from other food. The apple class defines those
qualities specific to an apple (grows on trees, not tropical, and so on). A
Red Delicious apple would, in turn, inherit all the qualities of all preceding
classes and would define only those qualities that make it unique.
Without the use of hierarchies, each object would have to explicitly define
all of its characteristics. Using inheritance, an object need only define
those qualities that make it unique within its class. It can inherit its general
attributes from its parent. Thus, it is the inheritance mechanism that makes
it possible for one object to be a specific instance of a more general case.

3.3.4 Encapsulation

Encapsulation is a programming mechanism that binds together code and


the data it manipulates, and keeps both safe from outside interference and
misuse. In an object-oriented language, code and data can be bound
together in such a way that a self-contained black box is created. Within
the box are all necessary data and code. When code and data are linked

Page 9 of 10
C# Programming Purvis Samsoodeen

together in this fashion, an object is created. In other words, an object is


the device that supports encapsulation.

C#’s basic unit of encapsulation is the class. A class defines the form of an
object. It specifies both the data and the code that will operate on that data.
C# uses a class specification to construct objects. Objects are instances of
a class. Thus, a class is essentially a set of plans that specify how to build
an object.

Page 10 of 10

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy