SlideShare a Scribd company logo
Types, Objects and NameSPACES
ITEC420
Classes
 Classes are the code definitions for objects.
 Classes contain their own code and internal set of
private data.
 Classes interact with each other with the help of three
key ingredients.
 Properties:
 Allow you to access an object’s data. Some properties may be read-
only, so they cannot be modified, while others can be changed.
 Methods:
 Allow you to perform an action on an object. Unlike properties,
methods are used for actions that perform a distinct task or may
change the object’s state significantly.
 Events:
 Provide notification that something has happened.like buttons click
event.
2
A Simple Class
 To create class, you must define it using a special
block structure.
 public class MyClass
 {
 //class code goes here
 }
 You can define as many classes as you need in the
same file.
3
Building a Basic Class
 This class will represent a product from the catalog of an e-commerce
company. The Product class will store product data, and it will include
the built-in functionality needed to generate a block of HTML that
displays the product on a web page.
 Once you’ve defined a class, the first step is to add some basic data.
We have three member variables below.
public class Product
{
private string name;
private decimal price;
private string imageUrl;
}
 A local variable exists only until the current method ends. On the
other hand, a member variable (or field) is declared as part of a class.
It’s available to all the methods in the class, and it lives as long as the
containing object lives.
4
Building A Basic Class
 When you create a member variable, you set its accessibility. The
accessibility determines whether other parts of your code will be able to
read and alter this variable.
 The accessibility keywords don’t just apply to variables. They also apply
to methods, properties, and events
5
Creating an Object
 When creating an object, you need to specify the new keyword. The
new keyword instantiates the object(calls the constructor)
 To create an instance from the product class you need a snippet like:
Product saleProduct = new Product();
// Optionally you could do this in two steps:
// Product saleProduct;
// saleProduct = new Product();
// Now release the object from memory.
saleProduct = null;
 In .NET, you almost never need to use the last line, which releases the
object. That’s because objects are automatically released when the
appropriate variable goes out of scope. Objects are also released
when your application ends.
6
Adding Properties
 The simple Product class is essentially useless because your
code cannot manipulate it. All its information is private and
unreachable. Other classes won’t be able to set or read this
information.
 To overcome this limitation, you could make the member
variables public. Unfortunately, that approach could lead to
problems because it would give other objects free access to
change everything, even allowing them to apply invalid or
inconsistent data. Instead, you need to add a “control panel”
through which your code can manipulate Product objects in a
 safe way. You do this by adding property accessors.
 Accessors usually have two parts. The get accessor allows your
code to retrieve data from the object. The set accessor allows
your code to set the object’s data. In some cases, you might
omit one of these parts, such as when you want to create a
property that can be examined but not modified.
7
Adding Properties
public class Product
{
private string name;
private decimal price;
private string imageUrl;
public string Name
{
get
{ return name; }
set
{ name = value; }
}
8
public decimal Price
{
get
{ return price; }
set
{ price = value; }
}
public string ImageUrl
{
get
{ return imageUrl; }
set
{ imageUrl = value; }
}
}
Product saleProduct = new Product();
saleProduct.Name = "Kitchen Garbage";
saleProduct.Price = 49.99M;
saleProduct.ImageUrl = "http://mysite/garbage.png";
If you only use a get
accessor that means
the field is readonly.
Adding a Method
Methods are simply named procedures that are built into your class.
When you call a method on an object, the method does something
useful, such as return some calculated data.
public class Product
{
// (Variables and properties omitted for clarity.)
public string GetHtml()
{
string htmlString;
htmlString = "<h1>" + name + "</h1><br />";
htmlString += "<h3>Costs: " + price.ToString() + "</h3><br />";
htmlString += "<img src='" + imageUrl + "' />";
return htmlString;
}
}
9
Adding a Constructor
 Currently, the Product class has a problem. Ideally, classes
should ensure that they are always in a valid state. However,
unless you explicitly set all the appropriate properties, the
Product object won’t correspond to a valid product. This
could cause an error if you try to use a method that relies on
some of the data that hasn’t been supplied. To solve this
problem, you need to equip your class with one or more
constructors.
 A constructor is a method that automatically runs when the
class is first created. In C#, the constructor always has the
same name as the name of the class. Unlike a normal
method, the constructor doesn’t define any return type, not
even void.
10
Adding a Constructor
public class Product
{
// (Additional class code omitted for clarity.)
public Product(string name, decimal price)
{
// Set the two properties in the class.
Name = name;
Price = price;
}
}
 Here’s an example of the code you need to create an object
based on the new Product class, using its constructor:
 Product saleProduct = new Product("Kitchen Garbage", 49.99M);
11
Adding a Constructor
 If you don’t create a constructor, .NET supplies a default
public constructor that does nothing. If you create at least
one constructor, .NET will not supply a default constructor.
Thus, in the preceding example, the Product class has
exactly one constructor, which is the one that is explicitly
defined in code. To create a Product object, you must use
this constructor. This restriction prevents a client from
creating an object without specifying the bare minimum
amount of data that’s required:
 // This will not be allowed, because there is
 // no zero-argument constructor.
 Product saleProduct = new Product();
12
Value types and Reference Types
 Simple data types are value types, while classes are reference
types.
 This means a variable for a simple data type contains the
actual information you put in it (such as the number 7). On
the other hand, object variables actually store a reference that
points to a location in memory where the full object is stored.
In most cases, .NET masks you from this underlying reality,
and in many programming tasks you won’t notice the
difference. However, in three cases you will notice that object
variables act a little differently than ordinary data types:
 in assignment operations,
 in comparison operations,
 and when passing parameters.
13
Assignment Operations
 When you assign a simple data variable to another simple data variable, the
contents of the variable are copied:
integerA = integerB; // integerA now has a copy of the contents of integerB.
// There are two duplicate integers in memory.
 Reference types work a little differently. Reference types tend to deal with
larger amounts of data. Copying the entire contents of a reference type object
could slow down an application, particularly if you are performing multiple
assignments. For that reason, when you assign a reference type you copy the
reference that points to the object, not the full object content:
// Create a new Product object.
Product productVariable1 = new Product();
// Declare a second variable.
Product productVariable2;
productVariable2 = productVariable1;
// productVariable1 and productVariable2 now both point to the same thing.
// There is one object and two ways to access it.
14
Assignment operations
 The consequences of this behavior are far ranging. This example
modifies the Product object using productVariable2:
 productVariable2.Price = 25.99M;
 You’ll find that productVariable1.Price is set to 25.99. Of course, this only
makes sense because productVariable1 and productVariable2 are two
variables that point to the same in-memory object.
 If you really do want to copy an object (not a reference), you need to
create a new object, and then initialize its information to match the first
object. Some objects provide a Clone() method that allows you to easily
copy the object.
15
Equality Testing
 A similar distinction between reference types and value types appears
when you compare two variables. When you compare value types (such
as integers), you’re comparing the contents:
if (integerA == integerB)
{
// This is true as long as the integers have the same content.
}
 When you compare reference type variables, you’re actually testing
whether they’re the same instance. In other words, you’re testing whether
the references are pointing to the same object in memory, not if their
contents match:
if (productVariable1 == productVariable2)
{
// This is true if both productVariable1 and productVariable2
// point to the same thing.
// This is false if they are separate, yet identical, objects.
}
16
Passing Parameters by Reference and by Value
 You can create three types of method parameters. The standard
type is pass-by-value. When you use pass-by-value parameters,
the method receives a copy of the parameter data. That means
that if the method modifies the parameter, this change won’t
affect the calling code. By default, all parameters are pass-by-
value.
 The second type of parameter is pass-by-reference. With pass-by-
reference, the method accesses the parameter value directly. If a
method changes the value of a pass-by-reference parameter, the
original object is also modified.
 To get a better understanding of the difference, consider the
following code, which shows a method that uses a parameter
named number. This code uses the ref keyword to indicate that
number should be passed by reference. When the method
modifies this parameter (multiplying it by 2), the calling code is
also affected:
17
Passing Parameters by Reference and by Value
private void ProcessNumber(ref int number)
{
number *= 2;
}
 The following code snippet shows the effect of calling the
ProcessNumber method. Note that you need to specify
the ref keyword when you define the parameter in the
method and when you call the method. This indicates
that you are aware that the parameter value may change:
int num = 10;
ProcessNumber(ref num); // Once this call completes, Num will be
20.
18
Passing Parameters by Reference
and by Value
 The way that pass-by-value and pass-by-reference work when
you’re using value types (such as integers) is straightforward.
However, if you use reference types, such as a Product object or an
array, you won’t see this behavior. The reason is because the entire
object isn’t passed in the parameter. Instead, it’s just the reference
that’s transmitted. This is much more efficient for large objects (it
saves having to copy a large block of memory), but it doesn’t
always lead to the behavior you expect.
 One notable quirk occurs when you use the standard pass-by-
value mechanism. In this case, pass-by-value doesn’t create a copy
of the object, but a copy of the reference. This reference still
points to the same in-memory object. This means that if you pass
a Product object to a method, for example, the method will be
able to alter your Product object, regardless of whether you use
pass-by-value or pass-by-reference.
19
Output Parameters
 C# also supports a third type of parameter: the output parameter. To
use an output parameter, precede the parameter declaration with
the keyword out. Output parameters are commonly used as a way to
return multiple pieces of information from a single method.
 When you use output parameters, the calling code can submit an
uninitialized variable as a parameter, which is otherwise forbidden.
This approach wouldn’t be appropriate for the ProcessNumber()
method, because it reads the submitted parameter value (and then
doubles it). If, on the other hand, the method used the parameter
just to return information, you could use the out keyword, as shown
here:
private void ProcessNumber(int number, out int doubl, out int triple)
{
doubl = number * 2;
triple = number * 3;
}
20
Output Parameters
 Remember, output parameters are designed solely for the
method to return information to your calling code. In fact,
the method won’t be allowed to retrieve the value of an out
parameter, because it may be uninitialized. The only action
the method can take is to set the output parameter.
 Here’s an example of how you can call the revamped
ProcessNumber() method:
 int num = 10;
 int double, triple;
 ProcessNumber(num, out double, out triple);
21
Understanding Namespaces and Assemblies
22
Whether you realize it at first, every piece of code in .NET exists inside a .NET type
(typically a class). In turn, every type exists inside a namespace.
Namespaces can organize all the different types in the class library.Without namespaces,
these types would all be grouped into a single long and messy list.This sort of organization
is practical for a small set of information, but it would be impractical for the thousands
of types included with .NET.
Using Namespaces
 Often when you write ASP.NET code, you’ll just use the namespace
that Visual Studio creates automatically. If, however, you want to
organize your code into multiple namespaces, you can define the
namespace using a simple block structure, as shown here:
namespace MyCompany
{
namespace MyApp
{
public class Product
{
// Code goes here.
}
}
}
 To reach your class the reference becomes
  MyCompany.MyApp.Product
23
Importing Namespaces
 To import namespaces, you use the using statement;
 To import a namespace, you use the using statement. These
statements must appear as the first lines in your code file,
outside of any namespaces or block structures:
 using MyCompany.MyApp;
 Consider the situation without importing a namespace:
 MyCompany.MyApp.Product salesProduct = new
MyCompany.MyApp.Product();
 It’s much more manageable when you import the
MyCompany.MyApp namespace. Once you do, you can use
this syntax instead:
 Product salesProduct = new Product();
 Importing namespaces is really just a convenience. It has no
effect on the performance of your application.
24
Static Members
 The idea of static properties and methods; they can be
used without a live object. Static members are often
used to provide useful functionality related to an
object. The .NET class library uses this technique
heavily (as with the System.Math class explored in the
previous class).
 The following example shows a TaxableProduct class
that contains a static TaxRate property and private
variable. This means there is one copy of the tax rate
information, and it applies to all TaxableProduct
objects:
25
Static Members
public class TaxableProduct : Product
{
// (Other class code omitted for clarity.)
private static decimal taxRate = 1.15M;
// Now you can call TaxableProduct.TaxRate, even without an object.
public static decimal TaxRate
{
get
{ return taxRate; }
set
{ taxRate = value; }
}
}
 You can now retrieve the tax rate information directly from the class, without needing to create an
object first:
// Change the TaxRate. This will affect all TotalPrice calculations for any
// TaxableProduct object.
TaxableProduct.TaxRate = 1.24M;
26
Static Members
 Static data isn’t tied to the lifetime of an object. In fact,
it’s available throughout the life of the entire application.
This means static members are the closest thing .NET
programmers have to global data.
 A static member can’t access an instance member. To
access a nonstatic member, it needs an actual instance of
your object.
27
Partial Classes
 Partial classes give you the ability to split a
single class into more than one source code
(.cs) file. For example, if the Product class
became particularly long and intricate, you
might decide to break it into two pieces, as
shown here:
28
//This part is stored in file Product1.cs.
public partial class Product
{
private string name;
private decimal price;
private string imageUrl;
public string Name
{ get
{ return name; }
set
{ name = value; }
}
public Product(string name, decimal
price)
{
Name = name;
Price = price;
}
}
//This part is stored in file Product2.cs.
public partial class Product
{
public string GetHtml()
{
string htmlString;
htmlString = "<h1>" + name + "</h1>";
return htmlString;
}
}
Partial Classes
 A partial class behaves the same as a normal class. This means every method,
property, and variable you’ve defined in the class is available everywhere, no matter
which source file contains it. When you compile the application, the compiler tracks
down each piece of the Product class and assembles it into a complete unit. It
doesn’t matter what you name the source code files, so long as you keep the class
name consistent.
 Partial classes don’t offer much in the way of solving programming problems, but
they can be useful if you have extremely large, unwieldy classes. The real purpose
of partial classes in .NET is to hide automatically generated designer code by
placing it in a separate file from your code. Visual Studio uses this technique when
you create web pages for a web application and forms for a Windows application.
 Topics such as Generics, Delegates, Inheritance, operator overloading, adding
events are excluded from the course content.
29

More Related Content

PPT
Pressman ch-11-component-level-design
PPTX
unit 5 Architectural design
PPT
PPTX
Architectural views
PPTX
Sequence diagram
PPSX
Php and MySQL
PPTX
Session tracking in servlets
PPT
Uml class Diagram
Pressman ch-11-component-level-design
unit 5 Architectural design
Architectural views
Sequence diagram
Php and MySQL
Session tracking in servlets
Uml class Diagram

What's hot (20)

PPTX
Factory Method Pattern
PPT
Design Pattern For C# Part 1
PPTX
PHP FUNCTIONS
PPTX
Design Patterns - Abstract Factory Pattern
PPT
State Machine Diagram
PPT
Object and class relationships
PPTX
Data Flow Diagrams
PDF
Object Oriented Programming Lecture Notes
PPT
Black box and white box testing
PPT
10 component diagram
PPT
Chapter12 designing databases
PPTX
usecase (1).pptx
PDF
Sequence diagram- UML diagram
PPTX
Introduction to C# Programming
DOCX
Joins in dbms and types
PPTX
Software engineering : Layered Architecture
PPT
Cookies and sessions
PDF
Behavioral Design Patterns
PPTX
Component and Deployment Diagram - Brief Overview
Factory Method Pattern
Design Pattern For C# Part 1
PHP FUNCTIONS
Design Patterns - Abstract Factory Pattern
State Machine Diagram
Object and class relationships
Data Flow Diagrams
Object Oriented Programming Lecture Notes
Black box and white box testing
10 component diagram
Chapter12 designing databases
usecase (1).pptx
Sequence diagram- UML diagram
Introduction to C# Programming
Joins in dbms and types
Software engineering : Layered Architecture
Cookies and sessions
Behavioral Design Patterns
Component and Deployment Diagram - Brief Overview
Ad

Similar to 4. Types, Objects and NameSPACES in. Net.pptx (20)

PPTX
Objects and Types C#
PDF
Object Oriented Programming with C#
PPTX
03 classes interfaces_principlesofoop
PPT
Csharp4 objects and_types
PPT
Object Oriented Programming (Advanced )
PPTX
Object-Oriented Programming with C#
PPTX
OOP in C# Classes and Objects.
PPTX
Application package
PDF
Object oriented programming
PPTX
Notes(1).pptx
PPTX
C# overview part 2
PPTX
5. c sharp language overview part ii
PDF
.NET Portfolio
PDF
C# Summer course - Lecture 3
PPTX
PPT
Visula C# Programming Lecture 6
DOCX
C# concepts
PPTX
C# classes objects
PPT
C++ classes tutorials
Objects and Types C#
Object Oriented Programming with C#
03 classes interfaces_principlesofoop
Csharp4 objects and_types
Object Oriented Programming (Advanced )
Object-Oriented Programming with C#
OOP in C# Classes and Objects.
Application package
Object oriented programming
Notes(1).pptx
C# overview part 2
5. c sharp language overview part ii
.NET Portfolio
C# Summer course - Lecture 3
Visula C# Programming Lecture 6
C# concepts
C# classes objects
C++ classes tutorials
Ad

Recently uploaded (20)

PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
Cell Structure & Organelles in detailed.
PDF
Complications of Minimal Access Surgery at WLH
PDF
01-Introduction-to-Information-Management.pdf
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Classroom Observation Tools for Teachers
Final Presentation General Medicine 03-08-2024.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Final Presentation General Medicine 03-08-2024.pptx
Computing-Curriculum for Schools in Ghana
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Pharma ospi slides which help in ospi learning
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Cell Structure & Organelles in detailed.
Complications of Minimal Access Surgery at WLH
01-Introduction-to-Information-Management.pdf
Weekly quiz Compilation Jan -July 25.pdf
O7-L3 Supply Chain Operations - ICLT Program
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Microbial diseases, their pathogenesis and prophylaxis

4. Types, Objects and NameSPACES in. Net.pptx

  • 1. Types, Objects and NameSPACES ITEC420
  • 2. Classes  Classes are the code definitions for objects.  Classes contain their own code and internal set of private data.  Classes interact with each other with the help of three key ingredients.  Properties:  Allow you to access an object’s data. Some properties may be read- only, so they cannot be modified, while others can be changed.  Methods:  Allow you to perform an action on an object. Unlike properties, methods are used for actions that perform a distinct task or may change the object’s state significantly.  Events:  Provide notification that something has happened.like buttons click event. 2
  • 3. A Simple Class  To create class, you must define it using a special block structure.  public class MyClass  {  //class code goes here  }  You can define as many classes as you need in the same file. 3
  • 4. Building a Basic Class  This class will represent a product from the catalog of an e-commerce company. The Product class will store product data, and it will include the built-in functionality needed to generate a block of HTML that displays the product on a web page.  Once you’ve defined a class, the first step is to add some basic data. We have three member variables below. public class Product { private string name; private decimal price; private string imageUrl; }  A local variable exists only until the current method ends. On the other hand, a member variable (or field) is declared as part of a class. It’s available to all the methods in the class, and it lives as long as the containing object lives. 4
  • 5. Building A Basic Class  When you create a member variable, you set its accessibility. The accessibility determines whether other parts of your code will be able to read and alter this variable.  The accessibility keywords don’t just apply to variables. They also apply to methods, properties, and events 5
  • 6. Creating an Object  When creating an object, you need to specify the new keyword. The new keyword instantiates the object(calls the constructor)  To create an instance from the product class you need a snippet like: Product saleProduct = new Product(); // Optionally you could do this in two steps: // Product saleProduct; // saleProduct = new Product(); // Now release the object from memory. saleProduct = null;  In .NET, you almost never need to use the last line, which releases the object. That’s because objects are automatically released when the appropriate variable goes out of scope. Objects are also released when your application ends. 6
  • 7. Adding Properties  The simple Product class is essentially useless because your code cannot manipulate it. All its information is private and unreachable. Other classes won’t be able to set or read this information.  To overcome this limitation, you could make the member variables public. Unfortunately, that approach could lead to problems because it would give other objects free access to change everything, even allowing them to apply invalid or inconsistent data. Instead, you need to add a “control panel” through which your code can manipulate Product objects in a  safe way. You do this by adding property accessors.  Accessors usually have two parts. The get accessor allows your code to retrieve data from the object. The set accessor allows your code to set the object’s data. In some cases, you might omit one of these parts, such as when you want to create a property that can be examined but not modified. 7
  • 8. Adding Properties public class Product { private string name; private decimal price; private string imageUrl; public string Name { get { return name; } set { name = value; } } 8 public decimal Price { get { return price; } set { price = value; } } public string ImageUrl { get { return imageUrl; } set { imageUrl = value; } } } Product saleProduct = new Product(); saleProduct.Name = "Kitchen Garbage"; saleProduct.Price = 49.99M; saleProduct.ImageUrl = "http://mysite/garbage.png"; If you only use a get accessor that means the field is readonly.
  • 9. Adding a Method Methods are simply named procedures that are built into your class. When you call a method on an object, the method does something useful, such as return some calculated data. public class Product { // (Variables and properties omitted for clarity.) public string GetHtml() { string htmlString; htmlString = "<h1>" + name + "</h1><br />"; htmlString += "<h3>Costs: " + price.ToString() + "</h3><br />"; htmlString += "<img src='" + imageUrl + "' />"; return htmlString; } } 9
  • 10. Adding a Constructor  Currently, the Product class has a problem. Ideally, classes should ensure that they are always in a valid state. However, unless you explicitly set all the appropriate properties, the Product object won’t correspond to a valid product. This could cause an error if you try to use a method that relies on some of the data that hasn’t been supplied. To solve this problem, you need to equip your class with one or more constructors.  A constructor is a method that automatically runs when the class is first created. In C#, the constructor always has the same name as the name of the class. Unlike a normal method, the constructor doesn’t define any return type, not even void. 10
  • 11. Adding a Constructor public class Product { // (Additional class code omitted for clarity.) public Product(string name, decimal price) { // Set the two properties in the class. Name = name; Price = price; } }  Here’s an example of the code you need to create an object based on the new Product class, using its constructor:  Product saleProduct = new Product("Kitchen Garbage", 49.99M); 11
  • 12. Adding a Constructor  If you don’t create a constructor, .NET supplies a default public constructor that does nothing. If you create at least one constructor, .NET will not supply a default constructor. Thus, in the preceding example, the Product class has exactly one constructor, which is the one that is explicitly defined in code. To create a Product object, you must use this constructor. This restriction prevents a client from creating an object without specifying the bare minimum amount of data that’s required:  // This will not be allowed, because there is  // no zero-argument constructor.  Product saleProduct = new Product(); 12
  • 13. Value types and Reference Types  Simple data types are value types, while classes are reference types.  This means a variable for a simple data type contains the actual information you put in it (such as the number 7). On the other hand, object variables actually store a reference that points to a location in memory where the full object is stored. In most cases, .NET masks you from this underlying reality, and in many programming tasks you won’t notice the difference. However, in three cases you will notice that object variables act a little differently than ordinary data types:  in assignment operations,  in comparison operations,  and when passing parameters. 13
  • 14. Assignment Operations  When you assign a simple data variable to another simple data variable, the contents of the variable are copied: integerA = integerB; // integerA now has a copy of the contents of integerB. // There are two duplicate integers in memory.  Reference types work a little differently. Reference types tend to deal with larger amounts of data. Copying the entire contents of a reference type object could slow down an application, particularly if you are performing multiple assignments. For that reason, when you assign a reference type you copy the reference that points to the object, not the full object content: // Create a new Product object. Product productVariable1 = new Product(); // Declare a second variable. Product productVariable2; productVariable2 = productVariable1; // productVariable1 and productVariable2 now both point to the same thing. // There is one object and two ways to access it. 14
  • 15. Assignment operations  The consequences of this behavior are far ranging. This example modifies the Product object using productVariable2:  productVariable2.Price = 25.99M;  You’ll find that productVariable1.Price is set to 25.99. Of course, this only makes sense because productVariable1 and productVariable2 are two variables that point to the same in-memory object.  If you really do want to copy an object (not a reference), you need to create a new object, and then initialize its information to match the first object. Some objects provide a Clone() method that allows you to easily copy the object. 15
  • 16. Equality Testing  A similar distinction between reference types and value types appears when you compare two variables. When you compare value types (such as integers), you’re comparing the contents: if (integerA == integerB) { // This is true as long as the integers have the same content. }  When you compare reference type variables, you’re actually testing whether they’re the same instance. In other words, you’re testing whether the references are pointing to the same object in memory, not if their contents match: if (productVariable1 == productVariable2) { // This is true if both productVariable1 and productVariable2 // point to the same thing. // This is false if they are separate, yet identical, objects. } 16
  • 17. Passing Parameters by Reference and by Value  You can create three types of method parameters. The standard type is pass-by-value. When you use pass-by-value parameters, the method receives a copy of the parameter data. That means that if the method modifies the parameter, this change won’t affect the calling code. By default, all parameters are pass-by- value.  The second type of parameter is pass-by-reference. With pass-by- reference, the method accesses the parameter value directly. If a method changes the value of a pass-by-reference parameter, the original object is also modified.  To get a better understanding of the difference, consider the following code, which shows a method that uses a parameter named number. This code uses the ref keyword to indicate that number should be passed by reference. When the method modifies this parameter (multiplying it by 2), the calling code is also affected: 17
  • 18. Passing Parameters by Reference and by Value private void ProcessNumber(ref int number) { number *= 2; }  The following code snippet shows the effect of calling the ProcessNumber method. Note that you need to specify the ref keyword when you define the parameter in the method and when you call the method. This indicates that you are aware that the parameter value may change: int num = 10; ProcessNumber(ref num); // Once this call completes, Num will be 20. 18
  • 19. Passing Parameters by Reference and by Value  The way that pass-by-value and pass-by-reference work when you’re using value types (such as integers) is straightforward. However, if you use reference types, such as a Product object or an array, you won’t see this behavior. The reason is because the entire object isn’t passed in the parameter. Instead, it’s just the reference that’s transmitted. This is much more efficient for large objects (it saves having to copy a large block of memory), but it doesn’t always lead to the behavior you expect.  One notable quirk occurs when you use the standard pass-by- value mechanism. In this case, pass-by-value doesn’t create a copy of the object, but a copy of the reference. This reference still points to the same in-memory object. This means that if you pass a Product object to a method, for example, the method will be able to alter your Product object, regardless of whether you use pass-by-value or pass-by-reference. 19
  • 20. Output Parameters  C# also supports a third type of parameter: the output parameter. To use an output parameter, precede the parameter declaration with the keyword out. Output parameters are commonly used as a way to return multiple pieces of information from a single method.  When you use output parameters, the calling code can submit an uninitialized variable as a parameter, which is otherwise forbidden. This approach wouldn’t be appropriate for the ProcessNumber() method, because it reads the submitted parameter value (and then doubles it). If, on the other hand, the method used the parameter just to return information, you could use the out keyword, as shown here: private void ProcessNumber(int number, out int doubl, out int triple) { doubl = number * 2; triple = number * 3; } 20
  • 21. Output Parameters  Remember, output parameters are designed solely for the method to return information to your calling code. In fact, the method won’t be allowed to retrieve the value of an out parameter, because it may be uninitialized. The only action the method can take is to set the output parameter.  Here’s an example of how you can call the revamped ProcessNumber() method:  int num = 10;  int double, triple;  ProcessNumber(num, out double, out triple); 21
  • 22. Understanding Namespaces and Assemblies 22 Whether you realize it at first, every piece of code in .NET exists inside a .NET type (typically a class). In turn, every type exists inside a namespace. Namespaces can organize all the different types in the class library.Without namespaces, these types would all be grouped into a single long and messy list.This sort of organization is practical for a small set of information, but it would be impractical for the thousands of types included with .NET.
  • 23. Using Namespaces  Often when you write ASP.NET code, you’ll just use the namespace that Visual Studio creates automatically. If, however, you want to organize your code into multiple namespaces, you can define the namespace using a simple block structure, as shown here: namespace MyCompany { namespace MyApp { public class Product { // Code goes here. } } }  To reach your class the reference becomes   MyCompany.MyApp.Product 23
  • 24. Importing Namespaces  To import namespaces, you use the using statement;  To import a namespace, you use the using statement. These statements must appear as the first lines in your code file, outside of any namespaces or block structures:  using MyCompany.MyApp;  Consider the situation without importing a namespace:  MyCompany.MyApp.Product salesProduct = new MyCompany.MyApp.Product();  It’s much more manageable when you import the MyCompany.MyApp namespace. Once you do, you can use this syntax instead:  Product salesProduct = new Product();  Importing namespaces is really just a convenience. It has no effect on the performance of your application. 24
  • 25. Static Members  The idea of static properties and methods; they can be used without a live object. Static members are often used to provide useful functionality related to an object. The .NET class library uses this technique heavily (as with the System.Math class explored in the previous class).  The following example shows a TaxableProduct class that contains a static TaxRate property and private variable. This means there is one copy of the tax rate information, and it applies to all TaxableProduct objects: 25
  • 26. Static Members public class TaxableProduct : Product { // (Other class code omitted for clarity.) private static decimal taxRate = 1.15M; // Now you can call TaxableProduct.TaxRate, even without an object. public static decimal TaxRate { get { return taxRate; } set { taxRate = value; } } }  You can now retrieve the tax rate information directly from the class, without needing to create an object first: // Change the TaxRate. This will affect all TotalPrice calculations for any // TaxableProduct object. TaxableProduct.TaxRate = 1.24M; 26
  • 27. Static Members  Static data isn’t tied to the lifetime of an object. In fact, it’s available throughout the life of the entire application. This means static members are the closest thing .NET programmers have to global data.  A static member can’t access an instance member. To access a nonstatic member, it needs an actual instance of your object. 27
  • 28. Partial Classes  Partial classes give you the ability to split a single class into more than one source code (.cs) file. For example, if the Product class became particularly long and intricate, you might decide to break it into two pieces, as shown here: 28 //This part is stored in file Product1.cs. public partial class Product { private string name; private decimal price; private string imageUrl; public string Name { get { return name; } set { name = value; } } public Product(string name, decimal price) { Name = name; Price = price; } } //This part is stored in file Product2.cs. public partial class Product { public string GetHtml() { string htmlString; htmlString = "<h1>" + name + "</h1>"; return htmlString; } }
  • 29. Partial Classes  A partial class behaves the same as a normal class. This means every method, property, and variable you’ve defined in the class is available everywhere, no matter which source file contains it. When you compile the application, the compiler tracks down each piece of the Product class and assembles it into a complete unit. It doesn’t matter what you name the source code files, so long as you keep the class name consistent.  Partial classes don’t offer much in the way of solving programming problems, but they can be useful if you have extremely large, unwieldy classes. The real purpose of partial classes in .NET is to hide automatically generated designer code by placing it in a separate file from your code. Visual Studio uses this technique when you create web pages for a web application and forms for a Windows application.  Topics such as Generics, Delegates, Inheritance, operator overloading, adding events are excluded from the course content. 29