Professional Documents
Culture Documents
• Abstraction
• Encapsulation
• Polymorphism
• Inheritance.
Abstraction is the ability to generalize an object as a data type that has a specific
set of characteristics and is able to perform a set of actions.
Examples:
C# Example of Class:
Object References
When we work with an object we are using a reference to that object. On the other
hand, when we are working with simple data types such as Integer, we are working
with the actual value rather than a reference.
When we create a new object using the New keyword, we store a reference to that
object in a variable. For instance:
Now we have a second variable, which also has a reference to that same object. We
can use either variable interchangeably, since they both reference the exact same
object. The thing we need to remember is that the variable we have is not the object
itself but, rather, is just a reference or pointer to the object itself.
Early binding means that our code directly interacts with the object, by directly
calling its methods. Since the compiler knows the object's data type ahead of time, it
can directly compile code to invoke the methods on the object. Early binding also
allows the IDE to use IntelliSense to aid our development efforts; it allows the
compiler to ensure that we are referencing methods that do exist and that we are
providing the proper parameter values.
Late binding means that our code interacts with an object dynamically at run-time.
This provides a great deal of flexibility since our code literally doesn't care what type
of object it is interacting with as long as the object supports the methods we want to
call. Because the type of the object isn't known by the IDE or compiler, neither
IntelliSense nor compile-time syntax checking is possible but we get unprecedented
flexibility in exchange.
If we enable strict type checking by using Option Strict On at the top of our code
modules, then the IDE and compiler will enforce early binding behavior. By default,
Option Strict is turned off and so we have easy access to the use of late binding
within our code.
Access Modifiers
Access Modifiers are keywords used to specify the declared accessibility of a member
of a type.
Private is hidden and usable only by the class itself. No code using a class instance
can access a private member directly and neither can a descendant class.
Protected members are similar to private ones in that they are accessible only by
the containing class. However, protected members also may be used by a
descendant class. So members that are likely to be needed by a descendant class
should be marked protected.
We use an interface to get access to an object's data and behavior. The object's data
and behaviors are contained within the object, so a client application can treat the
object like a black box accessible only through its interface. This is a key object-
oriented concept called Encapsulation. The idea is that any programs that make use
of this object won't have direct access to the behaviors or data-but rather those
programs must make use of our object's interface.
1. Interface
2. Implementation or Behavior
3. Member or Instance variables
Interface
The interface is defined as a set of methods (Sub and Function routines), properties
(Property routines), events, and fields (variables or attributes) that are declared
Public in scope.
Implementation or Behavior
The code inside of a method is called the implementation. Sometimes it is also called
behavior since it is this code that actually makes the object do useful work.
Client applications can use our object even if we change the implementation-as long
as we don't change the interface. As long as our method name and its parameter list
and return data type remain unchanged, we can change the implementation all we
want.
• Method name
• Data types of parameters
• Either Parameter is passed ByVal or ByRef.
• Return type of method.
The third key part of an object is its data, or state. Every instance of a class is
absolutely identical in terms of its interface and its implementation-the only thing
that can vary at all is the data contained within that particular object.
Member variables are those declared so that they are available to all code within our
class. Typically member variables are Private in scope-available only to the code in
our class itself. They are also sometimes referred to as instance variables or as
attributes. The .NET Framework also refers to them as fields.
We shouldn't confuse instance variables with properties. A Property is a type of
method that is geared around retrieving and setting values, while an instance
variable is a variable within the class that may hold the value exposed by a Property.
Because interfaces must be defined by inheriting classes and structs, they define a
contract. For instance, if class foo inherits from the IDisposable interface, it is
making a statement that it guarantees it has the Dispose() method, which is the only
member of the IDisposable interface. Any code that wishes to use class foo may
check to see if class foo inherits IDisposable. When the answer is true, then the code
knows that it can call foo.Dispose().
interface IMyInterface
{
void MethodToImplement();
}
All the methods of Interface are public by default and no access modifiers (like
private, public) are allowed with any method of Interface.
Note that this class inherits the IMyInterface interface; it must implement its all
members. While implementing interface methods all those needs to be declared
public only. It does this by implementing the MethodToImplement() method. Notice
that this method implementation has the exact same signature, parameters and
method name, as defined in the IMyInterface interface. Any difference will cause a
compiler error. Interfaces may also inherit other interfaces. Following listing shows
how inherited interfaces are implemented.
using System;
interface IParentInterface
{
void ParentInterfaceMethod();
}
interface IMyInterface : IParentInterface
{
void MethodToImplement();
}
class InterfaceImplementer : IMyInterface
{
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
public void ParentInterfaceMethod()
{
Console.WriteLine("ParentInterfaceMethod() called.");
}
}
The code in above listing contains two interfaces: IMyInterface and the interface it
inherits, IParentInterface. When one interface inherits another, any implementing
class or struct must implement every interface member in the entire inheritance
chain. Since the InterfaceImplementer class in above listing inherits from
IMyInterface, it also inherits IParentInterface. Therefore, the InterfaceImplementer
class must implement the MethodToImplement() method specified in the
IMyInterface interface and the ParentInterfaceMethod() method specified in the
IParentInterface interface.
In summary, you can implement an interface and use it in a class. Interfaces may
also be inherited by other interface. Any class or struct that inherits an interface
must also implement all members in the entire interface inheritance chain.
Inheritance is the idea that one class, called a subclass, can be based on another
class, called a base class. Inheritance provides a mechanism for creating hierarchies
of objects.
Inheritance is the ability to apply another class's interface and code to your own
class.
Access Keywords
The base keyword is used to access members of the base class from within a derived
class:
Call a method on the base class that has been overridden by another method.
Specify which base-class constructor should be called when creating instances of the
derived class. A base class access is permitted only in a constructor, an instance
method, or an instance property accessor.
In following example, both the base class, Person, and the derived class, Employee,
have a method named Getinfo. By using the base keyword, it is possible to call the
Getinfo method on the base class, from within the derived class.
using System;
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee: Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass
{
public static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
Output
Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG
Base class constructors can be called from derived classes. To call a base class
constructor, use the base() constructor reference. This is desirable when it's
necessary to initialize a base class appropriately.
Here's an example that shows the derived class constructor with an address
parameter:
In this code, the Customer class does not have an address, so it passes the
parameter to its base class constructor by adding a colon and the base keyword with
the parameter to its declaration. This calls the Contact constructor with the address
parameter, where the address field in Contact is initialized.
One more example which shows how base-class constructor is called when creating
instances of a derived class:
using System;
public class MyBase
{
int num;
public MyBase()
{
Console.WriteLine("In MyBase()");
}
public MyBase(int i)
{
num = i;
Console.WriteLine("in MyBase(int i)");
}
public int GetNum()
{
return num;
}
}
public class MyDerived : MyBase
{
static int i = 32;
// This constructor will call MyBase.MyBase()
public MyDerived(int ii) : base()
{
}
// This constructor will call MyBase.MyBase(int i)
public MyDerived() : base(i)
{
}
public static void Main()
{
MyDerived md = new MyDerived(); // calls public MyDerived() : base(i) and
// passes i=32 in base class
MyDerived md1 = new MyDerived(1); // call public MyDerived() : base(i)
}
}
Output
in MyBase(int i)
in MyBase()
The following example will not compile. It illustrates the effects of not including a
default constructor in a class definition:
In this example, the Customer constructor does not call the base class constructor.
This is obviously a bug, since the address field will never be initialized.
When a class has no explicit constructor, the system assigns a default constructor.
The default constructor automatically calls a default or parameterless base
constructor. Here's an example of automatic default constructor generation that
would occur for the preceding example:
When a class does not declare any constructors, the code in this example is
automatically generated. The default base class constructor is called implicitly when
no derived class constructors are defined. Once a derived class constructor is
defined, whether or not it has parameters, a default constructor will not be
automatically defined, as the preceding code showed.
Derived classes can access the members of their base class if those members have
protected or greater access. Simply use the member name in the appropriate
context, just as if that member were a part of the derived class itself. Here's an
example:
In above example, the GenerateReport() method of the Customer class calls the
FullAddress() method in its base class, Contact. All classes have full access to their
own members without qualification. Qualification refers to using a class name with
the dot operator to access a class member-MyObject.SomeMethod(), for instance.
This shows that a derived class can access its base class members in the same
manner as its own.
now you can't call this method using base.GetInfo() from derived class instead you
have to call Person.GetInfo() from derived class.
Inside Static members we can access only static fields, methods etc.
Following example will give error, because we can't access name in GetInfo()
because name is not static.
• the current instance for which a method is called. Static member functions do
not have a this pointer. The this keyword can be used to access members
from within constructors, instance methods, and instance accessors.
The following are common uses of this:
In above example, this.name refers to private variable name in the class. If we write
name = name, then this will refer to argument name of the constructor Employee
and not to private variable name in the class. In this case private variable name will
never be initialized.
// keywords_this.cs
// this example
using System;
public class Employee
{
public string name;
public string alias;
public decimal salary = 3000.00m;
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
// Printing method:
public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:
Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
}
}
public class Tax
{
public static decimal CalcTax(Employee E)
{
return (0.08m*(E.salary));
}
}
public class MainClass
{
public static void Main()
{
// Create objects:
Employee E1 = new Employee ("John M. Trainer", "jtrainer");
// Display results:
E1.printEmployee();
}
}
Output
Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00
Abstract Classes
Abstract classes are a special type of base classes. In addition to normal class
members, they have abstract class members. These Abstract class members are
methods and properties that are declared without an implementation. All classes
derived directly from abstract classes must implement all of these abstract methods
and properties.
Abstract classes can never be instantiated. This would be illogical, because of the
members without implementations.So what good is a class that can't be
instantiated? Lots! Abstract classes sit toward the top of a class hierarchy. They
establish structure and meaning to code. They make frameworks easier to build. This
is possible because abstract classes have information and behavior common to all
derived classes in a framework. Take a look at the following example:
Contact, is an abstract class. Contact has two abstract members, and it has an
abstract method named generateReport(). This method is declared with the abstract
modifier in front of the method declaration. It has no implementation (no braces)
and is terminated with a semicolon. The Name property is also declared abstract.
The accessors of properties are terminated with semicolons.
The abstract base class Contact has two derived classes, Customer and SiteOwner.
Both of these derived classes implement the abstract members of the Contact class.
The generateReport() method in each derived class has an override modifier in its
declaration. Likewise, the Name declaration contains an override modifier in both
Customer and SiteOwner.
The most famous of all abstract classes is the Object class. It may be referred to as
object or Object, but it's still the same class. Object is the base class for all other
classes in C#. It's also the default base class when a base class is not specified. The
following class declarations produce the same exact results:
abstract public class Contact : Object
{
// class members
}
abstract public class Contact
{
// class members
}
• Interfaces are closely related to abstract classes that have all members
abstract.
• For an abstract class, at least one method of the class must be an abstract
method that means it may have concrete methods.
• For an interface, all the methods must be abstract
• Class that implements an interface much provide concrete implementation of
all the methods definition in an interface or else must be declare an abstract
class
• In C#, multiple inheritance is possible only through implementation of
multiple interfaces. Abstract class can only be derived once.
• An interface defines a contract and can only contains four entities viz
methods, properties, events and indexes. An interface thus cannot contain
constants, fields, operators, constructors, destructors, static constructors, or
types.
• Also an interface cannot contain static members of any kind. The modifiers
abstract, public, protected, internal, private, virtual, override is disallowed, as
they make no sense in this context.
• Class members that implement the interface members must be publicly
accessible.
Overriding Summery:
A derived class may override a virtual method of the base class with the keyword
override. The following restrictions must be followed.
• Keyword override is used in the definition of child class method that is going
to override the base class's virtual method.
• The return type must be the same as the virtual method have in base class.
• The name of the method should also be same.
• The parameter-list must also be same in order, number and type of
parameters.
• The accessibility of the overriding method should not be more restricted than
that of the accessibility defined with virtual method of the base class. This
accessibility either be the same or less restricted.
• The virtual methods can be sealed in the child or derived classes to prevent
further modifications in the implementation of the virtual method in the
derived classes, by declaring them as sealed methods.
Sometimes derived class members have the same name as a corresponding base
class member. In this case, the derived member is said to be "hiding" the base class
member.
When hiding occurs, the derived member is masking the functionality of the base
class member. Users of the derived class won't be able to see the hidden member;
they'll see only the derived class member. The following code shows how hiding a
base class member works.
In this example, both SiteOwner and its base class, Contact, have a method named
FullAddress(). The FullAddress() method in the SiteOwner class hides the
FullAddress() method in the Contact class. This means that when an instance of a
SiteOwner class is invoked with a call to the FullAddress() method, it is the
SiteOwner class FullAddress() method that is called, not the FullAddress() method of
the Contact class.
Although a base class member may be hidden, the derived class can still access it. It
does this through the base identifier. Sometimes this is desirable. It is often useful to
take advantage of the base class functionality and then add to it with the derived
class code. The next example shows how to refer to a base class method from the
derived class.
In this particular example, the FullAddress() method of the Contact class is called
from within the FullAddress() method of the SiteOwner class. This is accomplished
with a base class reference. This provides another way to reuse code and add on to it
with customized behavior.
Versioning
Here's the scenario: A developer creates a class that inherits from a third-party
library. For the purposes of this discussion, we assume that the Contact class
represents the third-party library. Here's the example:
In this example, the FullAddress() method does not exist in the base class. There is
no problem yet. Later on, the creators of the third-party library update their code.
Part of this update includes a new member in a base class with the exact same name
as the derived class:
In this code, the base class method FullAddress() contains different functionality
than the derived class method. In other languages, this scenario would break the
code because of implicit polymorphism. However, this does not break any code in C#
because when the FullAddress() method is called on SiteOwner, it is still the
SiteOwner class method that gets called.
This scenario generates a warning message. One way to eliminate the warning
message is to place a new modifier in front of the derived class method name, as the
following example shows:
using System;
public class WebSite
{
public string SiteName;
public string URL;
public string Description;
public WebSite()
{
}
public WebSite( string strSiteName, string strURL, string strDescription )
{
SiteName = strSiteName;
URL = strURL;
Description = strDescription;
}
public override string ToString()
{
return SiteName + ", " +URL + ", " +Description;
}
}
public class Contact
{
public string address;
public string city;
public string state;
public string zip;
public string FullAddress()
{
string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;
return fullAddress;
}
}
public class SiteOwner : Contact
{
int siteHits;
string name;
WebSite mySite;
public SiteOwner()
{
mySite = new WebSite();
siteHits = 0;
}
public SiteOwner(string aName, WebSite aSite)
{
mySite = new WebSite(aSite.SiteName,aSite.URL,aSite.Description);
Name = aName;
}
new public string FullAddress()
{
string fullAddress = mySite.ToString();
return fullAddress;
}
public string Name
{
get
{
siteHits++;
return name;
}
set
{
name = value;
siteHits = 0;
}
}
}
public class Test
{
public static void Main()
{
WebSite mySite = new WebSite("Le Financier","http://www.LeFinancier.com","Fancy
Financial Site");
SiteOwner anOwner = new SiteOwner("John Doe", mySite);
string address;
anOwner.address = "123 Lane Lane";
anOwner.city = "Some Town";
anOwner.state = "HI";
anOwner.zip = "45678";
address = anOwner.FullAddress(); // Different Results
Console.WriteLine("Address: \n{0}\n", address);
}
}
This has the effect of explicitly letting the compiler know the developer's intent.
Placing the new modifier in front of the derived class member states that the
developers know there is a base class method with the same name, and they
definitely want to hide that member. This prevents breakage of existing code that
depends on the implementation of the derived class member. With C#, the method
in the derived class is called when an object of the derived class type is used.
Likewise, the method in the base class is called when an object of the Base class
type is called. Another problem this presents is that the base class may present
some desirable new features that wouldn't be available through the derived class.
To use these new features requires one of a few different workarounds. One option
would be to rename the derived class member, which would allow programs to use a
base class method through a derived class member. The drawback to this option
would be if there were other classes relying upon the implementation of the derived
class member with the same name. This scenario will break code and, for this
reason, is considered extremely bad form.
Another option is to define a new method in the derived class that called the base
class method. This allows users of the derived class to have the new functionality of
the base class, yet retain their existing functionality with the derived class. While this
would work, there are maintainability concerns for the derived class.
Sealed Classes
Sealed classes are classes that can't be derived from. To prevent other classes from
inheriting from a class, make it a sealed class. There are a couple good reasons to
create sealed classes, including optimization and security.
Sealing a class avoids the system overhead associated with virtual methods. This
allows the compiler to perform certain optimizations that are otherwise unavailable
with normal classes.
Another good reason to seal a class is for security. Inheritance, by its very nature,
dictates a certain amount of protected access to the internals of a potential base
class. Sealing a class does away with the possibility of corruption by derived classes.
A good example of a sealed class is the String class. The following example shows
how to create a sealed class:
This example generates a compiler error. Since the CustomerStats class is sealed, it
can't be inherited by the CustomerInfo class.The CustomerStats class was meant to
be used as an encapsulated object in another class. This is shown by the declaration
of a CustomerStats object in the Customer class.
Polymorphism
Polymorphism is reflected in the ability to write one routine that can operate on
objects from more than one class-treating different objects from different classes in
exactly the same way. For instance, if both Customer and Vendor objects have a
Name property, and we can write a routine that calls the Name property regardless
of whether we're using a Customer or Vendor object, then we have polymorphism.
Polymorphism will not implement code behind the vehicle's properties and methods.
Instead, polymorphism is the implementation of an interface. If the car, truck, and
semitruck all implement the same vehicle interface, then the client code for all three
classes can be exactly the same.
Child class are now free to provide their own implementation of this virtual method,
that is called overriding. The following points are important regarding virtual
keyword:-
If the method is not virtual, the compiler simply uses the reference type to invoke
the appropriate method.
If the method is virtual, the compiler will generate code to checkup the reference
type at runtime it is actually denoting to, then the appropriate method is called from
the class of the reference type.
When a virtual method is called, runtime check (late method binding) is made to
identify the object and appropriate method is invoked, all this is done at runtime.
Implementing Polymorphism
The key factor here is the ability to dynamically invoke methods in a class based on
their type. Essentially, a program would have a group of objects, examine the type
of each one, and execute the appropriate method. Here's an example:
using System;
public class WebSite
{
public string SiteName;
public string URL;
public string Description;
public WebSite()
{
}
public WebSite( string strSiteName, string strURL, string strDescription )
{
SiteName = strSiteName;
URL = strURL;
Description = strDescription;
}
public override string ToString()
{
return SiteName + ", " +URL + ", " +Description;
}
}
When we inherit above class, we have two choices to invoke constructor of the class.
So this is an example of design time polymorphism. Here at design time we have to
decide which method we need to invoke while inheriting the class.
The Microsoft .NET common language runtime requires that all resources be
allocated from the managed heap. Objects are automatically freed when they are no
longer needed by the application.
An application creates an object using the new operator. This operator first makes
sure that the bytes required by the new object fit in the reserved region (committing
storage if necessary). If the object fits, then pointer points to the object in the heap,
this object's constructor is called, and the new operator returns the address of the
object.
Above fig shows a managed heap consisting of three objects: A, B, and C. The next
object to be allocated will be placed where NextObjPtr points (immediately after
object C).
When an application calls the new operator to create an object, there may not be
enough address space left in the region to allocate to the object. The heap detects
this by adding the size of the new object to NextObjPtr. If NextObjPtr is beyond the
end of the address space region, then the heap is full and a collection must be
performed.
Every application has a set of roots. Roots identify storage locations, which refer to
objects on the managed heap or to objects that are set to null. For example, all the
global and static object pointers in an application are considered part of the
application's roots. In addition, any local variable/parameter object pointers on a
thread's stack are considered part of the application's roots. Finally, any CPU
registers containing pointers to objects in the managed heap are also considered part
of the application's roots. The list of active roots is maintained by the just-in-time
(JIT) compiler and common language runtime, and is made accessible to the garbage
collector's algorithm.
When the garbage collector starts running, it makes the assumption that all objects
in the heap are garbage. In other words, it assumes that none of the application's
roots refer to any objects in the heap. Now, the garbage collector starts walking the
roots and building a graph of all objects reachable from the roots. For example, the
garbage collector may locate a global variable that points to an object in the heap.
Following fig shows a heap with several allocated objects where the application's
roots refer directly to objects A, C, D, and F. All of these objects become part of the
graph. When adding object D, the collector notices that this object refers to object H,
and object H is also added to the graph. The collector continues to walk through all
reachable objects recursively.
Once this part of the graph is complete, the garbage collector checks the next root
and walks the objects again. As the garbage collector walks from object to object, if
it attempts to add an object to the graph that it previously added, then the garbage
collector can stop walking down that path. This serves two purposes. First, it helps
performance significantly since it doesn't walk through a set of objects more than
once. Second, it prevents infinite loops should you have any circular linked lists of
objects.
Once all the roots have been checked, the garbage collector's graph contains the set
of all objects that are somehow reachable from the application's roots; any objects
that are not in the graph are not accessible by the application, and are therefore
considered garbage.
The garbage collector now walks through the heap linearly, looking for contiguous
blocks of garbage objects (now considered free space). The garbage collector then
shifts the non-garbage objects down in memory (using the standard memcpy
function), removing all of the gaps in the heap. Of course, moving the objects in
memory invalidates all pointers to the objects. So the garbage collector must modify
the application's roots so that the pointers point to the objects' new locations. In
addition, if any object contains a pointer to another object, the garbage collector is
responsible for correcting these pointers as well.
GC generates a significant performance hit, and this is the major downside of using a
managed heap. However, keep in mind that GCs only occur when the heap is full
and, until then, the managed heap is significantly faster than a C-runtime heap. The
runtime's garbage collector also offers some optimizations using Generations that
greatly improve the performance of garbage collection.
You no longer have to implement any code that manages the lifetime of any
resources that your application uses. Now it is not possible to leak resources, since
any resource not accessible from your application's roots can be collected at some
point. Also it is not possible to access a resource that is freed, since the resource
won't be freed if it is reachable. If it's not reachable, then your application has no
way to access it.
class Application
{
public static int Main(String[] args)
{
// ArrayList object created in heap, myArray is now in root
ArrayList myArray = new ArrayList();
// Create 10000 objects in the heap
for (int x = 0; x < 10000; x++)
{
myArray.Add(new Object()); // Object object created in heap
}
// Right now, myArray is a root (on the thread's stack). So,
// myArray is reachable and the 10000 objects it points to are also reachable.
Console.WriteLine(myArray.Count);
// After the last reference to myArray in the code, myArray is not a root.
// Note that the method doesn't have to return, the JIT compiler knows
// to make myArray not a root after the last reference to it in the code.
// Since myArray is not a root, all 10001 objects are not reachable
// and are considered garbage. However, the objects are not
// collected until a GC is performed.
}
}
If GC is so great, you might be wondering why it isn't in ANSI C++. The reason is
that a garbage collector must be able to identify an application's roots and must also
be able to find all object pointers. The problem with C++ is that it allows casting a
pointer from one type to another, and there's no way to know what a pointer refers
to. In the common language runtime, the managed heap always knows the actual
type of an object, and the metadata information is used to determine which
members of an object refer to other objects.
Generations
One feature of the garbage collector that exists purely to improve performance is
called generations. A generational garbage collector (also known as an ephemeral
garbage collector) makes the following assumptions:
• The newer an object is, the shorter its lifetime will be.
• The older an object is, the longer its lifetime will be.
• Newer objects tend to have strong relationships to each other and are
frequently accessed around the same time.
• Compacting a portion of the heap is faster than compacting the whole heap.
When initialized, the managed heap contains no objects. Objects added to the heap
are said to be in generation 0, as you can see in following fig. Stated simply, objects
in generation 0 are young objects that have never been examined by the garbage
collector.
Now, if more objects are added to the heap, the heap fills and a garbage collection
must occur. When the garbage collector analyzes the heap, it builds the graph of
garbage (shown here in Green) and non-garbage objects. Any objects that survive
the collection are compacted into the left-most portion of the heap. These objects
have survived a collection, are older, and are now considered to be in generation 1.
As even more objects are added to the heap, these new, young objects are placed in
generation 0. If generation 0 fills again, a GC is performed. This time, all objects in
generation 1 that survive are compacted and considered to be in generation 2 (see
following fig). All survivors in generation 0 are now compacted and considered to be
in generation 1. Generation 0 currently contains no objects, but all new objects will
go into generation 0.
Currently, generation 2 is the highest generation supported by the runtime's garbage
collector. When future collections occur, any surviving objects currently in generation
2 simply stay in generation 2.
Generational garbage collecting improves performance. When the heap fills and a
collection occurs, the garbage collector can choose to examine only the objects in
generation 0 and ignore the objects in any greater generations. After all, the newer
an object is, the shorter its lifetime is expected to be. So, collecting and compacting
generation 0 objects is likely to reclaim a significant amount of space from the heap
and be faster than if the collector had examined the objects in all generations.
A generational collector can offer more optimizations by not traversing every object
in the managed heap. If a root or object refers to an object in an old generation, the
garbage collector can ignore any of the older objects' inner references, decreasing
the time required to build the graph of reachable objects. Of course, it is possible
that an old object refers to a new object. So that these objects are examined, the
collector can take advantage of the system's write-watch support (provided by the
Win32 GetWriteWatch function in Kernel32.dll). This support lets the collector know
which old objects (if any) have been written to since the last collection. These
specific old objects can have their references checked to see if they refer to any new
objects.
If collecting generation 0 doesn't provide the necessary amount of storage, then the
collector can attempt to collect the objects from generations 1 and 0. If all else fails,
then the collector can collect the objects from all generations-2, 1, and 0.
One of the assumptions stated earlier was that newer objects tend to have strong
relationships to each other and are frequently accessed around the same time. Since
new objects are allocated contiguously in memory, you gain performance from
locality of reference. More specifically, it is highly likely that all the objects can reside
in the CPU's cache. Your application will access these objects with phenomenal speed
since the CPU will be able to perform most of its manipulations without having cache
misses which forces RAM access.
Microsoft's performance tests show that managed heap allocations are faster than
standard allocations performed by the Win32 HeapAlloc function. These tests also
show that it takes less than 1 millisecond on a 200 MHz Pentium to perform a full GC
of generation 0. It is Microsoft's goal to make GCs take no more time than an
ordinary page fault.
• Most heaps (like the C runtime heap) allocate objects wherever they find free
space. Therefore, if I create several objects consecutively, it is quite possible
that these objects will be separated by megabytes of address space.
However, in the managed heap, allocating several objects consecutively
ensures that the objects are contiguous in memory.
• When memory is allocated from a Win32 heap, the heap must be examined to
find a block of memory that can satisfy the request. This is not required in
managed heap, since here objects are contiguous in memory.
• In Win32 heap, data structures that the heap maintains must be updated. The
managed heap, on the other hand, only needs to increment the heap pointer.
Finalization
The garbage collector offers an additional feature that you may want to take
advantage of: finalization. Finalization allows a resource to gracefully clean up after
itself when it is being collected. By using finalization, a resource representing a file or
network connection is able to clean itself up properly when the garbage collector
decides to free the resource's memory.
When the garbage collector detects that an object is garbage, the garbage collector
calls the object's Finalize method (if it exists) and then the object's memory is
reclaimed. For example, let's say you have the following type (in C#):
Some time in the future, the garbage collector will determine that this object is
garbage. When that happens, the garbage collector will see that the type has a
Finalize method and will call the method, causing "In Finalize" to appear in the
console window and reclaiming the memory block used by this object.
When designing a type it is best to avoid using a Finalize method. There are several
reasons for this:
• You have no control over when the Finalize method will execute. The object
may hold on to resources until the next time the garbage collector runs.
• When an application terminates, some objects are still reachable and will not
have their Finalize method called. This can happen if background threads are
using the objects or if objects are created during application shutdown or
AppDomain unloading. In addition, by default, Finalize methods are not called
for unreachable objects when an application exits so that the application may
terminate quickly. Of course, all operating system resources will be reclaimed,
but any objects in the managed heap are not able to clean up gracefully. You
can change this default behavior by calling the System.GC type's
RequestFinalizeOnShutdown method. However, you should use this method
with care since calling it means that your type is controlling a policy for the
entire application.
• The runtime doesn't make any guarantees as to the order in which Finalize
methods are called. For example, let's say there is an object that contains a
pointer to an inner object. The garbage collector has detected that both
objects are garbage. Furthermore, say that the inner object's Finalize method
gets called first. Now, the outer object's Finalize method is allowed to access
the inner object and call methods on it, but the inner object has been
finalized and the results may be unpredictable. For this reason, it is strongly
recommended that Finalize methods not access any inner, member objects.
If you determine that your type must implement a Finalize method, then make sure
the code executes as quickly as possible. Avoid all actions that would block the
Finalize method, including any thread synchronization operations. Also, if you let any
exceptions escape the Finalize method, the system just assumes that the Finalize
method returned and continues calling other objects' Finalize methods.
When the compiler generates code for a constructor, the compiler automatically
inserts a call to the base type's constructor. Likewise, when a C++ compiler
generates code for a destructor, the compiler automatically inserts a call to the base
type's destructor. Finalize methods are different from destructors. The compiler has
no special knowledge about a Finalize method, so the compiler does not
automatically generate code to call a base type's Finalize method. If you want this
behavior-and frequently you do-then you must explicitly call the base type's Finalize
method from your type's Finalize method:
Note that you'll usually call the base type's Finalize method as the last statement in
the derived type's Finalize method. This keeps the base object alive as long as
possible. Since calling a base type Finalize method is common, C# has a syntax that
simplifies your work. In C#, the following code:
class MyObject
{
MyObject()
{
}
}
Note that this C# syntax looks identical to the C++ language's syntax for defining a
destructor. But remember, C# doesn't support destructors. Don't let the identical
syntax fool you.
Finalization Internals
When an application creates a new object, the new operator allocates the memory
from the heap. If the object's type contains a Finalize method, then a pointer to the
object is placed on the finalization queue. The finalization queue is an internal data
structure controlled by the garbage collector. Each entry in the queue points to an
object that should have its Finalize method called before the object's memory can be
reclaimed.
Following fig shows a heap containing several objects. Some of these objects are
reachable from the application's roots, and some are not. When objects C, E, F, I,
and J were created, the system detected that these objects had Finalize methods and
pointers to these objects were added to the finalization queue.
When a GC occurs, objects B, E, G, H, I, and J are determined to be garbage. The
garbage collector scans the finalization queue looking for pointers to these objects.
When a pointer is found, the pointer is removed from the finalization queue and
appended to the freachable queue (pronounced "F-reachable"). The freachable queue
is another internal data structure controlled by the garbage collector. Each pointer in
the freachable queue identifies an object that is ready to have its Finalize method
called.
After the collection, the managed heap looks like following fig. Here, you see that the
memory occupied by objects B, G, and H has been reclaimed because these objects
did not have a Finalize method that needed to be called. However, the memory
occupied by objects E, I, and J could not be reclaimed because their Finalize method
has not been called yet.
There is a special runtime thread dedicated to calling Finalize methods. When the
freachable queue is empty (which is usually the case), this thread sleeps. But when
entries appear, this thread wakes, removes each entry from the queue, and calls
each object's Finalize method. Because of this, you should not execute any code in a
Finalize method that makes any assumption about the thread that's executing the
code. For example, avoid accessing thread local storage in the Finalize method.
The interaction of the finalization queue and the freachable queue is quite
fascinating. First, let me tell you how the freachable queue got its name. The f is
obvious and stands for finalization; every entry in the freachable queue should have
its Finalize method called. The "reachable" part of the name means that the objects
are reachable. To put it another way, the freachable queue is considered to be a root
just like global and static variables are roots. Therefore, if an object is on the
freachable queue, then the object is reachable and is not garbage.
In short, when an object is not reachable, the garbage collector considers the object
garbage. Then, when the garbage collector moves an object's entry from the
finalization queue to the freachable queue, the object is no longer considered
garbage and its memory is not reclaimed. At this point, the garbage collector has
finished identifying garbage. Some of the objects identified as garbage have been
reclassified as not garbage. The garbage collector compacts the reclaimable memory
and the special runtime thread empties the freachable queue, executing each
object's Finalize method.
The next time the garbage collector is invoked, it sees that the finalized objects are
truly garbage, since the application's roots don't point to it and the freachable queue
no longer points to it. Now the memory for the object is simply reclaimed. The
important thing to understand here is that two GCs are required to reclaim memory
used by objects that require finalization. In reality, more than two collections may be
necessary since the objects could get promoted to an older generation. Above fig
shows what the managed heap looks like after the second GC.
Dispose Method
Use this method to close or release unmanaged resources such as files, streams, and
handles held by an instance of the class that implements this interface. This method
is, by convention, used for all tasks associated with freeing resources held by an
object, or preparing an object for reuse.
When implementing this method, objects must seek to ensure that all held resources
are freed by propagating the call through the containment hierarchy. For example, if
an object A allocates an object B, and object B allocates an object C, then A's
Dispose implementation must call Dispose on B, which must in turn call Dispose on
C. Objects must also call the Dispose method of their base class if the base class
implements IDisposable.
If an object's Dispose method is called more than once, the object must ignore all
calls after the first one. The object must not throw an exception if its Dispose
method is called multiple times. Dispose can throw an exception if an error occurs
because a resource has already been freed and Dispose had not been called
previously.
Because the Dispose method must be called explicitly, objects that implement
IDisposable must also implement a finalizer to handle freeing resources when
Dispose is not called. By default, the garbage collector will automatically call an
object's finalizer prior to reclaiming its memory. However, once the Dispose method
has been called, it is typically unnecessary for the garbage collector to call the
disposed object's finalizer. To prevent automatic finalization, Dispose
implementations can call the GC.SuppressFinalize method.
The System.GC type allows your application some direct control over the garbage
collector. You can query the maximum generation supported by the managed heap
by reading the GC.MaxGeneration property. Currently, the GC.MaxGeneration
property always returns 2.
It is also possible to force the garbage collector to perform a collection by calling one
of the two methods shown here:
The first method allows you to specify which generation to collect. You may pass any
integer from 0 to GC.MaxGeneration, inclusive. Passing 0 causes generation 0 to be
collected; passing 1 cause generation 1 and 0 to be collected; and passing 2 causes
generation 2, 1, and 0 to be collected. The version of the Collect method that takes
no parameters forces a full collection of all generations and is equivalent to calling:
GC.Collect(GC.MaxGeneration);
Under most circumstances, you should avoid calling any of the Collect methods; it is
best to just let the garbage collector run on its own accord. However, since your
application knows more about its behavior than the runtime does, you could help
matters by explicitly forcing some collections. For example, it might make sense for
your application to force a full collection of all generations after the user saves his
data file. I imagine Internet browsers performing a full collection when pages are
unloaded. You might also want to force a collection when your application is
performing other lengthy operations; this hides the fact that the collection is taking
processing time and prevents a collection from occurring when the user is interacting
with your application.
Lastly, the garbage collector offers two methods that allow you to determine which
generation an object is currently in:
This chapter rounds out your introduction to the core aspects of the C# language by
examining a number of advanced (but extremely useful) syntactic constructs. To
begin, you learn how to construct and use an indexer method. This C# mechanism
enables you to build custom types, which exposes internal subtypes using the
familiar bracket operator (i.e., []). If you have a C++ background, you will find that
creating a C# indexer method is analogous to overloading the [] operator on a C++
class. Once you learn how to build an indexer, you then examine how to overload
various operators (+, -, <, > and so forth) for a custom C# type.
This chapter then examines three techniques that enable the objects in your system
to engage in bidirectional communications. First, you learn about the C# "delegate"
keyword, which is little more than a type-safe function pointer. Once you learn how
to create and manipulate delegates, you are in a perfect position to investigate
the .NET event protocol, which is based on the delegation model. Finally, you
discover how the use of custom interfaces can also enable bidirectional
communications (which should ring a bell for those coming from a COM background).
I wrap up by examining how you can document your types using XML attributes, and
how the Visual Studio.NET IDE automatically generates Web-based documentation
for your projects. Although this might not qualify as a truly "advanced" technique, it
is a high note on which to end the chapter.
At this point, you should feel confident building C# types using traditional OOP (refer
to Chapter 3) as well as interface-based programming techniques (refer to Chapter
4). In this chapter, I take some time to examine some additional aspects of C# that
you may not be readily failure with, beginning with the concept of an indexer. Most
programmers (such as yourself) are very familiar with the process of accessing
discrete items held within a standard array using the index (aka bracket) operator:
The C# language supports the capability to build custom classes that may be
indexed just like an array of intrinsic types. It should be no big surprise that the
method that provides the capability to access items in this manner is termed an
"indexer." Before exploring how to create such a construct, let's begin by seeing one
in action. Assume you have added support for an indexer method to the Cars
container developed in the previous chapter. Observe the following usage:
As you can see, indexers behave much like a custom collection supporting the
IEnumerator and IEnumerable interfaces. The only major difference is that rather
than A Comprehensive Guide to C# and the .NET Platform, ©2001 Andrew Troelsen
(Apress, ISBN: 1-893115-59-3) p. 5-3 accessing the contents using interface
references, you are able to manipulate the internal collection of automobiles just like
a standard array.
Now for the big question: How do you configure the Cars class (or any class) to do
so? The indexer itself is represented as a slightly mangled C# property. In its
simplest form, an indexer is created using the this[] syntax:
// Let's rollback to the basics and simply make use of a standard array
// to contain the cars. You are free to use an ArrayList if you desire…
private Car[] carArray;
public Cars()
{
carArray = new Car[10];
}
// The indexer returns a Car based on a numerical index.
public Car this[int pos]
{
// Accessor returns an item in the array.
get
{
if (pos < 0 || pos > 10)
throw new IndexOutOfRangeException("Out of range!");
else
return (carArray[pos]);
}
// Mutator populates the array.
set { carArray[pos] = value; }
}
}
Beyond the use of the "this" keyword, the indexer looks just like any other C#
property declaration. Do be aware that indexers do not provide any array-like
functionality beyond the use of the subscript operator. In other words, the object
user cannot write code such as:
To support this functionality, you would need to add your own Length property to the
Cars type, and delegate accordingly:
However, if you are in need of this functionality, you will find your task will be much
easier if you make direct use of one of the System.Collections types to hold your
internal items, rather than a simple array.
Up until this point, every sample application you have developed added various bits
of code to Main(), which (in some way or another) sent messages to a given object.
However, you have not yet examined how these objects can talk back to the object
that created them in the first place. In the "real world" it is quite common for the
objects in a system to engage in a two-way conversation. Thus, let's examine a
number of ways in which objects can be programmed to do this very thing.
As you may know, the Windows API makes frequent use of function pointers to
create entities termed "callback functions" or simply "callbacks." Using callbacks,
programmers are able to configure one function to report back to (call back) another
function in the application. The problem with standard C(++)callback functions is
that they represent nothing more than a simple memory address. Ideally, C(++)
callbacks could be configured to include additional type-safe information such as the
number of (and types of) parameters, return value, and calling convention. Sadly,
this is not the case in traditional C(++)/Win32 callback functions.
Notice that the class that is created on your behalf contains two public methods that
enable you to synchronously or asynchronously work with the delegate (Invoke() and
BeginInvoke() respectively). To keep things simple, I will focus only on the
synchronous behavior of the MulticastDelegate type.
To illustrate the use of delegates, let's begin by updating the Car class to include two
new Boolean member variables. The first is used to determine if your automobile is
due for a wash (isDirty); the other represents if the car in question is in need of a
tire rotation (shouldRotate). To enable the object user to interact with this new state
data, Car also defines some additional properties and an updated constructor. Here
is the story so far:
isDirty = dirty;
shouldRotate = rotate;
}
public bool Dirty // Get and set isDirty.
{
get{ return isDirty; }
set{ isDirty = value; }
}
public bool Rotate // Get and set shouldRotate.
{
get{ return shouldRotate; }
set{ shouldRotate = value; }
}
}
Now, assume you have declared the following delegate (which again, is nothing more
than an object-oriented wrapper around a function pointer) within your current
namespace:
Here, you have created a delegate named CarDelegate. The CarDelegate type
represents "some" function taking a Car as a parameter and returning void. If you
were to examine the internal representation of this type using ILDasm.exe, you
would see something like Figure 5-3 (notice the "extends" informational node).
Figure 5-3. C# delegates represent a class deriving from MulticastDelegate.
Currently, your delegate is decoupled from its logically related Car type (given that
you have simply declared the CarDelegate type within the defining namespace).
While there is nothing horribly wrong with the approach, a more enlightened
alternative would be to define the CarDelegate directly within the Car class:
Given that the "delegate" keyword produces a new class deriving from
System.MulticastDelegate, the CarDelegate is in fact a nested type definition! If you
check ILDasm.exe (see Figure 5-4), you will see the truth of the matter.
Members of System.MutlicastDelegate
So to review thus far, when you create delegates, you indirectly build a type that
derives from System.MulticastDelegate (which by the way, derives from the
System.Delegate base class). Table 5-2 illustrates some interesting inherited
members to be aware of.
Inherited
Meaning in Life
Member
Method This property returns the name of the method pointed to.
If the method pointed to is a member of a class, this member
Target returns the name of the class. If the value returned from Target
equals null, the method pointed to is static.
This static method is used to build a delegate that points to a
Combine()
number of different functions.
Returns an array of Delegate types, each representing an entry in
GetInvocationList()
the list of function pointers.
This static method removes a delegate from the list of function
Remove()
pointers.
Multicast delegates are capable of pointing to any number of functions, because this
class has the capability to hold multiple function pointers using an internal linked list.
The function pointers themselves can be added to the linked list using the Combine()
method or the overloaded + operator. To remove a function from the internal list,
call Remove().
Now that you have a pointer to "some" function, you can create other functions that
take this delegate as a parameter. To illustrate, assume you have a new class named
Garage. This type maintains a collection of Car types contained in an ArrayList. Upon
creation, the ArrayList is filled with some initial Car types.
More importantly, the Garage class defines a public ProcessCars() method, which
takes a single argument of type Car.CarDelegate. In the implementation of
ProcessCars(), you pass each Car in your collection as a parameter to the "function
pointed to" by the delegate.
To help understand the inner workings of the delegation model, let's also make use
of two members defined by the System.MulticastDelegate class (Target and Method)
to determine exactly which function the delegate is currently pointing to. Here, then,
is the complete definition of the Garage class:
// The Garage class has a method that makes use of the CarDelegate.
public class Garage
{
// A list of all ca cars in the garage.
ArrayList theCars = new ArrayList();
// Create the cars in the garage.
public Garage()
{
// Recall, we updated the ctor to set isDirty and shouldRotate.
theCars.Add(new Car("Viper", 100, 0, true, false));
theCars.Add(new Car("Fred", 100, 0, false, false));
theCars.Add(new Car("BillyBob", 100, 0, false, true));
theCars.Add(new Car("Bart", 100, 0, true, true));
theCars.Add(new Car("Stan", 100, 0, false, true));
}
// This method takes a Car.CarDelegate as a parameter.his
// Therefore! 'proc' is nothing more than a function pointer! herefore!
public void ProcessCars(Car.CarDelegate proc)
{
// Diagnostics: Where are we forwarding the call?
Console.WriteLine("***** Calling: {0} *****", d.Method.ToString());
// Diagnostics: Are we calling an instance method or a static method?
if (proc.Target != null)
Console.WriteLine("-->Target: {0}", proc.Target.ToString());
else
Console.WriteLine("-->Target is a static method");
// Real Work: Now call the method, passing in each car.
foreach (Car c in theCars)
proc(c);
}
}
When the object user calls ProcessCars(), it will send in the name of the method that
should handle this request. For the sake of argument, assume these are static
members named WashCar() and RotateTires(). Consider the following usage:
Notice (of course) that the two static methods are an exact match to the delegate
type (void return value and a single Car argument). Also, recall that when you pass
in the name of your function as a constructor parameter, you are adding this item to
the internal linked list maintained by System.MulticastDelegate. Figure 5-5 shows
the output of this test run. (Notice the output messages supplied by Target and
Method properties.)
As you can see, the Main() method begins by creating an instance of the Garage
type.This class has been configured to delegate all work to other named static
functions. Now,when you write the following:
what you are effectively saying is "Add a pointer to the WashCar() function to the
CarDelegate type, and pass this delegate to Garage.ProcessCars()." Like most real-
world garages, the real work is delegated to another part of the system (which
explains why a 30-minute oil change takes 2 hours). Given this, you can assume that
ProcessCars() actually looks like the following under the hood:
Also notice that when you are calling ProcessCars(), you must create a new instance
of the custom delegate:
This might seem odd at first, given that a delegate represents a function pointer.
However, remember that this function pointer is represented by an instance of type
System.MulticastDelegate, and therefore must be "new-ed.
Multicasting
Recall that a multicast delegate is an object that is capable of calling any number of
functions. In the current example, you did not make use of this feature. Rather, you
made two calls to Garage.ProcessCars(), sending in a new instance of the
CarDelegate each time. To illustrate multicasting, assume you have updated Main()
to look like the following:
Here, you begin by creating two new CarDelegate objects, each of which points to a
given function. When you call ProcessCars(), you are actually passing in a new
delegate, which holds each function pointer within the internal linked list (crazy
huh?). Do note that the + operator is simply a shorthand for calling the static
Delegate.Combine() method. Thus, you could write the following equivalent (but
uglier) code:
// The + operator has the same effect as calling the Combine() method.
g.ProcessCars((Car.CarDelegate)Delegate.Combine(wash, rotate));
Furthermore, if you wish to hang on to the new delegate for later use, you could
write
the following instead:
Regardless of how you configure a multicast delegate, understand that when you call
Combine() (or use the overloaded + operator) you are adding a new function pointer
to the internal list. If you wish to remove an item from this internal linked list, you
can call the static Remove() method. The first parameter marks the delegate you
wish to manipulate, while the second parameter marks the item to remove:
Before you view the output of this program, let's also update ProcessCars() to print
out each function pointer stored in the linked list using Delegate.GetInvocationList().
This method returns an array of Delegate objects, which you iterate over using
foreach:
Currently, the CarDelegate type is storing pointers to static functions. This is not a
requirement of the delegate protocol. It is also possible to delegate a call to a
method defined on any object instance. To illustrate, assume that the WashCar() and
RotateTires() methods have now been moved into a new class named ServiceDept:
Now notice the output in Figure 5-7 (check out the name of the target).
SOURCE CODE The CarDelegate project is located under the Chapter 5 subdirectory.
Delegates are fairly interesting constructs because you can resolve the name of a
function to call at runtime, rather than compile time. Admittedly, this syntactic
orchestration can take a bit of getting used to. However, because the ability for one
object to call back to another object is such a helpful construct, C# provides the
"event" keyword to lessen the burden of using delegates in the raw.
The most prevalent use of the event keyword would be found in GUI-based
applications, in which Button, TextBox, and Calendar widgets all report back to the
containing Form when a given action (such as clicking a Button) has occurred.
However, events are not limited to GUI-based applications. Indeed, they can be quite
helpful when creating "non-GUI" based projects (as you will now see).
Let's reconfigure the Car to send two events to those who happen to be listening.
The first event (AboutToBlow) will be sent when the current speed is 10 miles below
the maximum speed. The second event (Exploded) will be sent when the user
attempts to speed up a car that is already dead. Establishing an event is a two-step
process. First, you need to define a delegate, which as you recall represents a
pointer to the method(s) to call when the event is sent. Next, you define the events
themselves using the "event" keyword. Here is the updated Car class (also notice
that I have added a private Boolean to represent the state of the car):
Firing an event (i.e., sending the event to those who happen to be listening) is as
simple as specifying the event by name and sending out any specified parameters.
To illustrate, update the previous implementation of SpeedUp() to send each event
accordingly (and remove the previous exception logic):
With this, you have configured the car to send two custom events (under the correct
conditions). You will see the usage of this new automobile in just a moment, but
first, let's check the event architecture in a bit more detail.
A given event actually expands into two hidden public functions, one having an
"add_" prefix, the other having a "remove_" prefix. For example, the Exploded event
expands to the following methods:
To illustrate, check out Figure 5-8, a screenshot of the Car type as seen through the
eyes of ILDasm.exe.
Figure 5-8. Events under the hood
As you can see, each event (Exploded and AboutToBlow) is internally represented as
the following members:
If you were to check out the IL instructions behind add_AboutToBlow(), you would
find the following (note the call to Delegate.Combine() is handled on your behalf):
The IL instructions for the event itself make use of the [.addon] and [.removeon]
tags to establish the correct add_XXX and remove_XXX methods (also note the static
private class is mentioned by name):
Assume you have now created an instance of the Car class and wish to listen to the
events it is capable of sending. The goal is to create a method that represents the
"event sink" (i.e., the method called by the delegate). To do so, you need to call the
correct add_XXX() method to ensure that your method is added to the list of function
pointers maintained by your delegate. However, you do not call add_XXX() and
remove_XXX() directly, but rather use the overloaded += and -= operators.
Basically, when you wish to listen to an event, follow the pattern shown here:
// I'm listening…
// ObjectVariable.EventName += new ObjectVariable.DelegateName(functionToCall);
//
Car.Exploded += new Car.EngineHandler(OnBlowUp OnBlowUp);
When you wish to detach from a source of events, use the -= operator:
// Shut up already!
// ObjectVariable.EventName -= new ObjectVariable.DelegateName(functionToCall);
//
Car.Exploded -= new Car.EngineHandler(OnBlowUp OnBlowUp);
If you wish to have multiple event sinks called by a given event, simply repeat the
process:
Now, when the Exploded event is sent, the associated delegate calls OnBlowUp() as
well as OnBlowUp2(), as shown in Figure 5-10.
At this point, you have the background to build objects that can participate in a two-
way conversation. However, understand that you are free to build a helper object to
respond to an object's event set, much in the same way that you created a helper
class to be called by all delegates. For example, let's move your event sink methods
out of the CarApp class and into a new class named CarEventSink:
The CarApp class is then a bit more self-contained, as the event sink methods have
been pulled out of the CarApp definition and into their own custom type. Here is the
update:
SOURCE CODE The CarEvents project is located under the Chapter 5 subdirectory.
COM programmers may be familiar with the notion of defining and implementing
"callback interfaces." This technique allows a COM client to receive events from a
coclass using a custom COM interface, and is often used to bypass the overhead
imposed by the official COM connection point architecture. For an illustration of using
the interface as a callback, let's examine how callback interfaces can be created
using C# (and .NET in general). Consider this last topic a bonus section, which
proves the point that there is always more than one way to solve a problem.
First, let's keep the same assumption that the Car type wishes to inform the outside
world when it is about to blow (current speed is 10 miles below the maximum speed)
and has exploded. However, this time you will not be using the "delegate" or "event"
keywords, but rather the following custom interface:
This interface will be implemented by a sink object, on which the Car will make calls.
Now that you have an object that implements the event interface, your next task is
to pass a reference to this sink into the Car. The Car holds onto the reference, and
makes calls back on the sink when appropriate. In order to allow the Car to obtain a
reference to the sink, you can assume some method has been added to the default
public interface.
In keeping with the COM paradigm, let's call this method Advise(). When the object
user wishes to detach from the event source, he may call another method
(Unadvise() in COM-speak). In order to allow the object user to register multiple
event sinks, let's assume that the Car maintains an ArrayList to represent each
outstanding connection (analogous to the array of IUnknown* interfaces used with
classic COM connection points). Here is the story so far:
Now, Car.SpeedUp() can be retrofitted to iterate over the list of connections and fire
the correct notification when appropriate (i.e., call the correct method on the sink):
The following is some client-side code, now making use of a callback interface to
listen to the Car events:
Any language can be called object oriented if it has data and method that use data
encapsulated in items named objects. An object oriented programming method has many
advantages, some of them are flexibility and code reusability.
All the programming languages supporting Object oriented Programming will be supporting
these three main concepts:
1. Encapsulation
2. Inheritance
3. Polymorphism
Encapsulation in C#:
Encapsulation is process of keeping data and methods together inside objects. In this way
developer must define some methods of object's interaction. In C# , encapsulation is realized
through the classes. A Class can contain data structures and methods. Consider the following
class.
public Aperture()
{
In this example we encapsulate some data such as height, width, thickness and method
GetVolume. Other methods or objects can interact with this object through methods that have
public access modifier. It must be done using . operator.
Inheritance in C#:
In a few words, Inheritance is the process of creation new classes from already existing
classes. The inheritance feature allows us to reuse some parts of code. So, now we have some
derived class that inherits base class's members. Consider the following code snippet:
As you see to inherit one class from another, we need to write base class name after : symbol.
Next thing that was done in code Door () constructor also inherits base class constructor. And at
last we add new private field. All members of Aperture class are also in Door class. We can
inherit all the members that has access modifier higher than protected.
Polymorphism in C#:
Polymorphism is possibility to change behavior with objects depending of object's data type. In
C# polymorphism realizes through the using of keyword virtual and override. Let look on the
example of code:
Now we need to re-define it in our derived Door class. The usage of virtual methods can be
clarified when we creating an instance of derived class from the base class:
In such cases, the runtime keeps record of all the virtual function details in a table called
VMT(Virtual Method Table) and then in runtime dynamically picks the correct version of the
function to be used. Here it uses Out() method from derived class of course
There are several rules for caching data. First, if data can be used more than once it's a
good candidate for caching. Second, if data is general rather than specific to a given
request or user, it's a great candidate for the cache. If the data is user- or request-specific,
but is long lived, it can still be cached, but may not be used as frequently. Third, an often
overlooked rule is that sometimes you can cache too much. Generally on an x86 machine,
you want to run a process with no higher than 800MB of private bytes in order to reduce
the chance of an out-of-memory error. Therefore, caching should be bounded. In other
words, you may be able to reuse a result of a computation, but if that computation takes
10 parameters, you might attempt to cache on 10 permutations, which will likely get you
into trouble. One of the most common support calls for ASP.NET is out-of-memory
errors caused by overcaching, especially of large datasets.Common Performance Myths
One of the most common myths is that C# code is faster than Visual Basic code. There is
a grain of truth in this, as it is possible to take several performance-hindering actions in
Visual Basic that are not possible to accomplish in C#, such as not explicitly declaring
types. But if good programming practices are followed, there is no reason why Visual
Basic and C# code cannot execute with nearly identical performance. To put it more
succinctly, similar code produces similar results.
Another myth is that codebehind is faster than inline, which is absolutely false. It doesn't
matter where your code for your ASP.NET application lives, whether in a codebehind file
or inline with the ASP.NET page. Sometimes I prefer to use inline code as changes don't
incur the same update costs as codebehind. For example, with codebehind you have to
update the entire codebehind DLL, which can be a scary proposition.
Myth number three is that components are faster than pages. This was true in Classic
ASP when compiled COM servers were much faster than VBScript. With ASP.NET,
however, both pages and components are classes. Whether your code is inline in a page,
within a codebehind, or in a separate component makes little performance difference.
Organizationally, it is better to group functionality logically this way, but again it makes
no difference with regard to performance.
The final myth I want to dispel is that every functionality that you want to occur between
two apps should be implemented as a Web service. Web services should be used to
connect disparate systems or to provide remote access to system functionality or
behaviors. They should not be used internally to connect two similar systems. While easy
to use, there are much better alternatives. The worst thing you can do is use Web services
for communicating between ASP and ASP.NET applications running on the same server,
which I've witnessed all too frequently.
Figure 3 ASP.NET Cache
There are a several great features of the Cache that you need to know. The first is that the
Cache implements a least-recently-used algorithm, allowing ASP.NET to force a Cache
purge—automatically removing unused items from the Cache—if memory is running
low. Secondly, the Cache supports expiration dependencies that can force invalidation.
These include time, key, and file. Time is often used, but with ASP.NET 2.0 a new and
more powerful invalidation type is being introduced: database cache invalidation. This
refers to the automatic removal of entries in the cache when data in the database changes.
For more information on database cache invalidation, see Dino Esposito's Cutting Edge
column in the July 2004 issue of MSDN®Magazine. For a look at the architecture of the
cache, see Figure 3.
Connection Pooling is the ability to reuse the database connection for more than one user.
That connection might be SQL, OLEDB, ORACLE or whatever. This way of organizing
connections in a smarter manner improves performance as the applications do not need to
open and close the connection multiple times.
All of us know that we declare the connection string in web.config as follows in .NET
Application and make use of this in code behind while connecting to databases.
<connectionStrings>
</connectionStrings>
Points to Ponder
• Disabling the connection pooling, infers that the connection object that is created
by the user will not be re-used to any other user.
• A Connection pool will be created when Open() method of connection object is
called. If the same application is using multiple Connection Strings (say more
than one) then multiple connection pools will be created corresponding to each
connection string.
• Connection Pooling is applied in ADO.Net by default.
• Connections that are not explicitly closed are not added or returned to the pool.
Hence The Close() or Dispose() method of Connection need to be called to close
the connection.
• A Connection Pool is freed from the memory when the last connection to the
database is closed.
• Connection Pool’s life time is ended as soon as the application domain is
unloaded. For example at any time when IISRESET runs the Connection Pool
gets destroyed
• Connection Pools cannot be shared across application domains.
Try
{
SqlConnection _sqlConnection = new SqlConnection();
_sqlConnection.ConnectionString =
ConfigurationManager.ConnectionStrings["sqlConnectionString"].ToString();
if (_sqlConnection.State = ConnectionState.Closed)
_sqlConnection.Open();
/*Do some Operations … */}
catch (Exception ex)
{ /*Do something */
}
finally
{ if (_sqlConnection.State != ConnectionState.Closed)
_sqlConnection.Close();
}
Connection Pooling improves the performance of the data driven B2B applications as we
save some time in reusing the existing active database connections. I will be explaining it
in more detail in my next article.
5. What are the term SOLID stands in OOPs? Explain about it?
SOLID stands for Single Responsibility Open Closed Liskov Substitution Interface
Segregation Dependency Inversion .
SOLID Principles of Object-Oriented Design, as introduced by Robert C Martin.
Single Responsibility Principle
A class (or method) should only have one reason to change.
Open Closed Principle
Extending a class shouldn't require modification of that class.
Liskov Substitution Principle
Derived classes must be substitutable for their base classes.
Interface Segregation Principle
Make fine grained interfaces that are client specific.
Dependency Inversion Principle
Program to the interface, not the implementation.
6. What is Single Responsibility Principle of a class?
There should never be more than one reason for a class to change. The classes should
exist for one purpose only.