Wednesday, April 30, 2008

Partial Classes-2

The first example shows an easy solution todefining nested types. With the power ofpartial classes, nested types can be completely isolated to their ownfiles. DataAccessLayer is defined as partial sothat the nested type DataSourceCollection can be defined in a separatepart. The second example is probably more of atelling of the dangers of partial types when used for no good reason. Here we see that both the containing typeDataAccessLayer and the contained type DataSourceCollection are defined aspartial. Hence the the definitions can bebroken into multiple parts. Please practicecaution when using partial types, particularly with regard to nested types. You will find that in a complex program it will bealmost impossible to determine what the full definition of any one type is onceit is defined as partial.

Partialtype attributes
Attributes on partial types are combined in anunspecified order so that the appear to all be defined on the given type. In the preceding section we defined a typeDataAccessLayer as follows.

public partial class DataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

}

public partial classDataAccessLayer
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}

publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}
}
}


Attributes can be added to each part of the typedefinition as follows.

//Dal.cs
[Docking]
public partial classDataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}
}

//dal.datasourcecollection.cs
[Serializable]
public partial classDataAccessLayer
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}

In the above example, an different attribute hasbeen added to each part of the definition of DataAccessLayer. To the part defined in dal.cs, the attributeDockingAttribute has been attached. To the partdefined in dal.datasourcecollection.cs, the SerializableAttribute has beenattached. This activity is equivalent tospecifying both attributes on the type asfollows.

[Serializable, Docking ]

Inheritanceand Interface Implementation
Now that we are done having all this fun it’s timeto lay down some rules regarding what you can and cant do with partialtypes. To help with the discussion, it isimportant that we visualize what the end result of a partial type is. The previous section defined a partial typeDataAccessLayer as follows.

//Dal.cs
[Docking]
public partial classDataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}
}

//dal.datasourcecollection.cs
[Serializable]
public partial classDataAccessLayer
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}

This definition, once compiled, will be equivalentto the listing below.

[Docking, Serializable]
public classDataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

public class DataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}


The lesson here is that a partial class, no matterhow fragmented, is still on functional unit. Hence, any accessibility specifications applied to a partial type must agreewith all parts of the type that also include the accessibilityspecification. The concept is illustrated withthe sample below.

[Docking]
public partial classDataAccessLayer : GenericDAL
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}
}


internal partialclass DataAccessLayer : GenericDAL
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}

Notice that in this definition of DataAccessLayer,the two parts inherit from a base type GenericDAL. Also notice that while one part defines the class aspublic, the other uses the internal modifier. Attempting to compile this listing will fail with the followingmessage.

Error1 Partial declarations of'PartialTypes2.DataAccessLayer' have conflicting accessibilitymodifiers

The reason is evident from our first demonstrationin this section. Although DataAccessLayer isfragmented, it is still type and a type cannot be both internal and public atthe same time.

The next issue is that of base classes, andis not as easy to ascertain. Examine the listing below.

[Docking]
public partial classDataAccessLayer : GenericDAL
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}
}


partial classDataAccessLayer : DataSource
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}

Although the modifier incompatibility has beenremoved from the type, a problem persists during compilation of the abovesource. The difference here is that the secondpart of DataAccessLayer is now attempting to inherit from a different base typeDataSource, than the first part which inherits from GenericDAL. This might not seem intuitive because it contradictsthe combining behavior of partial type attributes; however, returning to ourinitial demonstration on the singularity of partial types, DataAccessLayer is atype; consequently, it can only inherit from one base class. The formal rule dictates that when a partial classdeclaration includes a base class specification it must agree with all otherparts that include a base class specification. Attempting to compile the listing above would produce the following errormessage.

Error1 Partial declarations of'PartialTypes2.DataAccessLayer' must not specify different base classes

Now in the world of interfaces, where multipleinheritance is the game, the compining behavior returns. Examine the example below.

public partial class DataAccessLayer : GenericDAL
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

}


partial classDataAccessLayer : IDataSourceManager
{
publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}
Similar to the example in the last section, thesecond part of DataAccessLayer defines a different base than the first. Unlike the sample in the previous section; however,IDataSourceManager is an interface and not a class. The formal rule state that the set of baseinterfaces for a type declared in multiple parts is the union of the baseinterfaces specified on each part. Furthermore,a particular base interface may only be named once on each part, but it ispermitted for multiple parts to name the same base interface(s).

This means that the first part in the listingabove could have been defined to include the IDataSourceManager interface aswell. The listing below illustrates.


public partial class DataAccessLayer : GenericDAL,IDataSourceManager
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

}

<<<<Previous

Partial Classes-1

Partial classes

Introduction

Examine the examaple below:

//definition for BinaryTree.h
class BinaryTree
{
public:
BinaryTree(void);
~BinaryTree(void);
int seed;
char*name;
void Load(char*name);
char* Find();
};

In C++ the class definitions can be separated fromthe implementations. The above snippet is takenfrom a file BinaryTree.h which contains all definitions associated with theBinaryTree class but no implementation code. Continuing with the example, the implementation file BinaryTree.cpp would bedefined as follows.

#include ".\binarytree.h"

BinaryTree::BinaryTree(void)
{
}

BinaryTree::~BinaryTree(void)
{
}

void BinaryTree::Load(char* str){
this->name =str;
}

char* BinaryTree::Find(){
returnthis->name;
}


As you can see from the sample, the first line ofBinaryTree.cpp explicitly declares the inclusion of the class definition foundin binarytree.h. Consequently; this completelyseparate file can use members defined in the later as though they were definedthere. The sample is of course nonsensical but the concept neverthelessprevails; the ability to create types across multiple files.

It is important to note that the idea of havingmultiple public types in one file was so revolting to the devout object orientedprogrammer at one time that entire languages, Java for instance, excludedit. However, you will find that while it isgood programming practice to maintain all source code for a type in a singlefile, sometimes a type becomes large enough that this is an impracticalconstraint.

Partials
C# 2.0 introduces the concept of partial typedefinitions for classes, structs, and interfaces, as a means to break types in aprogram into multiple pieces to be stored in different source files for easiermaintenance and development. This approach isparticularly useful when the need arises to use nested types or provideinterface implementation.

Unlike c/C++ where an #include keyword was used toexplicitly bind the contents of a header file to the implementation file, C#2.0partial type links are inferred through the type names given. Also, these are no interface definitions necessaryin c#2.0. A sample of a partial type is given below.

//Binarytree_header.cs
public partial class BinaryTree
{
intseed;
stringname;
publicBinaryTree()
{
}
}


The above example attempts to recreate theBinaryTree sample we saw earlier in the chapter using C#; notice that no includestatements are needed nor are any function prototypes defined. Furtherimplementation of this class may now be defined in other files, for instance aBinaryTree_Load.cs file may be created which produces more BinaryTreefunctionality.

//BinaryTree_load.cs: Loadfunctionality
public partial classBinaryTree
{
public voidLoad(string name)
{
this.name= name;
}

}

We can also create another file BinaryTree_find.cswhich would have all the functionality associated with finding an element in thetree.

//BinaryTree_find.cs: findfunctionality
public partial classBinaryTree
{
public stringFind()
{
returnname;
}
}

As you can see from the above samples, the newtype modifier,partial, isused when defining a type in multiple parts. It indicates that additional partsmay exist elsewhere. I stress the word maybecause each partial type declaration is autonomous. The example below illustrates this by creating apartial type declaration that includes no other parts.

public partial class BinaryTree
{

intx;


}


The code above will compile successfully. Addinganother part to the type will not change this successful compilation.

public partial class BinaryTree
{
inty;
}

Finally, a constructor can be added to instantiatethe two variables defined in both parts of the type. A sample showing all three parts is highlightedbelow.

public partial class BinaryTree
{
int x;
}

public partial classBinaryTree
{
inty;
}

public partial classBinaryTree
{
publicBinaryTree()
{
this.x =100;
this.y =100;
}
}


Each partial type declaration must include thepartial modifier and must be declared within the same namespace as the otherparts.

Compiling the code above will produce thefollowing type definition.

public partial class BinaryTree
{
intx;
inty;
publicBinaryTree()
{
this.x =100;
this.y =100;
}
}

If we compiled the BinaryTree sample from thefirst section it would produce a type definition similar to the one depictedbelow.



public class BinaryTree
{
intseed;
stringname;
publicBinaryTree()
{
}

public voidLoad(string name)
{
this.name= name;
}

public stringFind()
{
returnname;
}
}

It is important to note that partial types DO NOTallow already compiled types to be extended. This is because all parts of a partial type must be compiled together such thatthe parts can be merged at compile-time to produce an actual type; as discussedin the example above. The partial modifier, ifit appears, must appear immediately before either class, struct, or interfacekeywords, but is not itself a keyword.


NestedPartials
Examine the three types defined in the samplebelow.

public struct DataSource
{
public stringconnectionString;
}

public classDataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}

publicDataSource this[string dataSourceName]
{
get
{
return (DataSource)items[dataSourceName];
}
}
}
}

The snippet defines a struct DataSource of whichthe type DataSourceCollection is an aggregate through the items Hashtable. This type DataSourceCollection also happens to be anested type of the DataAccessLayer type. Usingpartial types in this scenario, the nested type DataSourceCollection may also bedeclared in multiple parts by using the partial modifier. Hence DataAccessLayer may also be defined asfollows.

public class DataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

public partialclass DataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}


}

public partialclass DataSourceCollection
{
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}
}


}

This would not make to much sense though, sincethe type DataSourceCollection is only qualified through its containerDataAccessLayer there is no way to specify a part outside of theDataSourceCollection type definition. A moreoptimal approach is to define either the containing type as partial with thecontained type as not.

public partial class DataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

}

public partial classDataAccessLayer
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}

publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}
}
}

Or to define both containing and contained partsas partial.

public partial class DataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}
}

public partial classDataAccessLayer
{
public partialclass DataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
}
}

public partial classDataAccessLayer
{
public partialclass DataSourceCollection
{
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}
}
}


NEXT>>>

How to remove duplicate rows from a table in SQL Server

This article was previously published under Q139444
SUMMARY
Microsoft SQL Server tables should never contain duplicate rows, nor non-unique primary keys. For brevity, we will sometimes refer to primary keys as "key" or "PK" in this article, but this will always denote "primary key." Duplicate PKs are a violation of entity integrity, and should be disallowed in a relational system. SQL Server has various mechanisms for enforcing entity integrity, including indexes, UNIQUE constraints, PRIMARY KEY constraints, and triggers.

Despite this, under unusual circumstances duplicate primary keys may occur, and if so they must be eliminated. One way they can occur is if duplicate PKs exist in non-relational data outside SQL Server, and the data is imported while PK uniqueness is not being enforced. Another way they can occur is through a database design error, such as not enforcing entity integrity on each table.

Often duplicate PKs are noticed when you attempt to create a unique index, which will abort if duplicate keys are found. This message is:
Msg 1505, Level 16, State 1 Create unique index aborted on duplicate key.
If you are using SQL Server 2000 or SQL Server 2005, you may receive the following error message:
Msg 1505, Level 16, State 1 CREATE UNIQUE INDEX terminated because a duplicate key was found for object name '%.*ls' and index name '%.*ls'. The duplicate key value is %ls.
This article discusses how to locate and remove duplicate primary keys from a table. However, you should closely examine the process which allowed the duplicates to happen in order to prevent a recurrence.
MORE INFORMATION
For this example, we will use the following table with duplicate PK values. In this table the primary key is the two columns (col1, col2). We cannot create a unique index or PRIMARY KEY constraint since two rows have duplicate PKs. This procedure illustrates how to identify and remove the duplicates.
create table t1(col1 int, col2 int, col3 char(50)) insert into t1 values (1, 1, 'data value one') insert into t1 values (1, 1, 'data value one') insert into t1 values (1, 2, 'data value two')
The first step is to identify which rows have duplicate primary key values:
SELECT col1, col2, count(*) FROM t1 GROUP BY col1, col2 HAVING count(*) > 1
This will return one row for each set of duplicate PK values in the table. The last column in this result is the number of duplicates for the particular PK value.
col1 col2
1 1 2


If there are only a few sets of duplicate PK values, the best procedure is to delete these manually on an individual basis. For example:
set rowcount 1 delete from t1 where col1=1 and col2=1
The rowcount value should be n-1 the number of duplicates for a given key value. In this example, there are 2 duplicates so rowcount is set to 1. The col1/col2 values are taken from the above GROUP BY query result. If the GROUP BY query returns multiple rows, the "set rowcount" query will have to be run once for each of these rows. Each time it is run, set rowcount to n-1 the number of duplicates of the particular PK value.

Before deleting the rows, you should verify that the entire row is duplicate. While unlikely, it is possible that the PK values are duplicate, yet the row as a whole is not. An example of this would be a table with Social Security Number as the primary key, and having two different people (or rows) with the same number, each having unique attributes. In such a case whatever malfunction caused the duplicate key may have also caused valid unique data to be placed in the row. This data should copied out and preserved for study and possible reconciliation prior to deleting the data.

If there are many distinct sets of duplicate PK values in the table, it may be too time-consuming to remove them individually. In this case the following procedure can be used:
1. First, run the above GROUP BY query to determine how many sets of duplicate PK values exist, and the count of duplicates for each set.
2. Select the duplicate key values into a holding table. For example:
SELECT col1, col2, col3=count(*) INTO holdkey FROM t1 GROUP BY col1, col2 HAVING count(*) > 1
3. Select the duplicate rows into a holding table, eliminating duplicates in the process. For example:
SELECT DISTINCT t1.* INTO holddups FROM t1, holdkey WHERE t1.col1 = holdkey.col1 AND t1.col2 = holdkey.col2
4. At this point, the holddups table should have unique PKs, however, this will not be the case if t1 had duplicate PKs, yet unique rows (as in the SSN example above). Verify that each key in holddups is unique, and that you do not have duplicate keys, yet unique rows. If so, you must stop here and reconcile which of the rows you wish to keep for a given duplicate key value. For example, the query:
SELECT col1, col2, count(*) FROM holddups GROUP BY col1, col2
should return a count of 1 for each row. If yes, proceed to step 5 below. If no, you have duplicate keys, yet unique rows, and need to decide which rows to save. This will usually entail either discarding a row, or creating a new unique key value for this row. Take one of these two steps for each such duplicate PK in the holddups table.
5. Delete the duplicate rows from the original table. For example:
DELETE t1 FROM t1, holdkey WHERE t1.col1 = holdkey.col1 AND t1.col2 = holdkey.col2
6. Put the unique rows back in the original table. For example:
INSERT t1 SELECT * FROM holddups
________________________________________

Sunday, April 27, 2008

Differences Between VB.NET& C# .NET-3

Programming Difference
Purpose VB.NET C#

Declaring Variables
VB.NET>>Dim x As Integer
Public x As Integer = 10
C#.NET>>int x;
int x = 10;

Comments
VB.NET>> ' comment
x = 1 ' comment
Rem comment

C#.NET>>// comment
/* multiline
comment */

Assignment Statements
nVal = 7
nVal = 7;

Conditional Statements

VB.NET>>
If nCnt <= nMax Then
' Same as nTotal =
' nTotal + nCnt.
nTotal += nCnt
' Same as nCnt = nCnt + 1.
nCnt += 1
Else
nTotal += nCnt
nCnt -= 1
End If

C#.NET>>
if (nCnt <= nMax)
{
nTotal += nCnt;
nCnt++;
}
else
{
nTotal +=nCnt;
nCnt--;
}



Selection Statements

VB.NET>>
Select Case n
Case 0
MsgBox ("Zero")
' Visual Basic .NET exits
' the Select at
' the end of a Case.
Case 1
MsgBox ("One")
Case 2
MsgBox ("Two")
Case Else
MsgBox ("Default")
End Select


C#.NET>>

switch(n)
{
case 0:
Console.WriteLine("Zero");
break;
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
default:
Console.WriteLine("?");
break;
}

FOR Loops

VB.NET>>

For n = 1 To 10
MsgBox("The number is " & n)
Next

For Each prop In obj
prop = 42
Next prop

C#.NET>>
for (int i = 1; i <= 10; i++)
Console.WriteLine(
"The number is {0}", i);
foreach(prop current in obj)
{
current=42;
}

Hiding Base Class Members

VB.NET>>
Public Class BaseCls
' The element to be shadowed
Public Z As Integer = 100
public Sub Test()
System.Console.WriteLine( _
"Test in BaseCls")
End Sub
End Class

Public Class DervCls
Inherits BaseCls
' The shadowing element.
Public Shadows Z As String = "*"
public Shadows Sub Test()
System.Console.WriteLine( _
"Test in DervCls")
End Sub
End Class

Public Class UseClasses
' DervCls widens to BaseCls.
Dim BObj As BaseCls =
New DervCls()
' Access through derived
' class.
Dim DObj As DervCls =
New DervCls()

Public Sub ShowZ()
System.Console.WriteLine( _
"Accessed through base "&_
"class: " & BObj.Z)
System.Console.WriteLine(_
"Accessed through derived "&_
"class: " & DObj.Z)
BObj.Test()
DObj.Test()
End Sub
End Class


C#.NET>>
public class BaseCls
{
// The element to be hidden
public int Z = 100;
public void Test()
{
System.Console.WriteLine(
"Test in BaseCls");
}
}

public class DervCls : BaseCls
{
// The hiding element
public new string Z = "*";
public new void Test()
{
System.Console.WriteLine(
"Test in DervCls");
}
}

public class UseClasses
{
// DervCls widens to BaseCls
BaseCls BObj = new DervCls();
// Access through derived
//class
DervCls DObj = new DervCls();
public void ShowZ()
{
System.Console.WriteLine(
"Accessed through " +
"base class: {0}",
BObj.Z);
System.Console.WriteLine(
"Accessed through" +
" derived class:{0}",
DObj.Z);
BObj.Test();
DObj.Test();
}
}
WHILE Loops

VB.NET>>
' Test at start of loop
While n < 100 .
' Same as n = n + 1.
n += 1
End While '

C#.NET>>
while (n < 100)
n++;



Parameter Passing by Value
VB.NET>>
' The argument Y is
'passed by value.
Public Sub ABC( _
ByVal y As Long)
'If ABC changes y, the
' changes do not affect x.
End Sub

ABC(x) ' Call the procedure.
' You can force parameters to
' be passed by value,
' regardless of how
' they are declared,
' by enclosing
' the parameters in
' extra parentheses.
ABC((x))

C#.NET>>
/* Note that there is
no way to pass reference
types (objects) strictly
by value. You can choose
to either pass the reference
(essentially a pointer), or
a reference to the reference
(a pointer to a pointer).*/
// The method:
void ABC(int x)
{
...
}
// Calling the method:
ABC(i);
Parameter Passing by Reference

VB.NET>>
Public Sub ABC(ByRef y As Long)
' The parameter y is declared
'by referece:
' If ABC changes y, the changes are
' made to the value of x.
End Sub

ABC(x) ' Call the procedure.




C#.NET>>
/* Note that there is no
way to pass reference types
(objects) strictly by value.
You can choose to either
pass the reference
(essentially a pointer),
or a reference to the
reference (a pointer to a
pointer).*/
// Note also that unsafe C#
//methods can take pointers
//just like C++ methods. For
//details, see unsafe.
// The method:
void ABC(ref int x)
{
...
}
// Calling the method:
ABC(ref i);

Structured Exception Handling

VB.NET>>
Try
If x = 0 Then
Throw New Exception( _
"x equals zero")
Else
Throw New Exception( _
"x does not equal zero")
End If
Catch err As System.Exception
MsgBox( _
"Error: " & Err.Description)
Finally
MsgBox( _
"Executing finally block.")
End Try


C#.NET>>
// try-catch-finally
try
{
if (x == 0)
throw new System.Exception(
"x equals zero");
else
throw new System.Exception(
"x does not equal zero");
}
catch (System.Exception err)
{
System.Console.WriteLine(
err.Message);
}
finally
{
System.Console.WriteLine(
"executing finally block");
}



Set an Object Reference to Nothing

VB.NET>> o = Nothing
C#.NET>> o = null;

Initializing Value Types

VB.NET>>
Dim dt as New System.DateTime( _
2001, 4, 12, 22, 16, 49, 844)

C#.NET>>
System.DateTime dt =
new System.DateTime(
2001, 4, 12, 22, 16,
49, 844);



New Features of both languages in 2005 version



VB.NET>>>>>
Visual Basic 2005 has many new and improved language features -- such as inheritance, interfaces, overriding, shared members, and overloading -- that make it a powerful object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit multithreading. This language has following new features,
1. Continue Statement, which immediately skips to the next iteration of a Do, For, or While loop.
2. IsNot operator, which you can avoid using the Not and Is operators in an awkward order.
3. 3. Using...End. Using statement block ensures disposal of a system resource when your code leaves the block for any reason.
4. Public Sub setbigbold( _
5. ByVal c As Control)
6. Using nf As New _
7. System.Drawing.Font("Arial",_
8. 12.0F, FontStyle.Bold)
9. c.Font = nf
10. c.Text = "This is" &_
11. "12-point Arial bold"
12. End Using
End Sub
13. Explicit Zero Lower Bound on an Array, Visual Basic now permits an array declaration to specify the lower bound (0) of each dimension along with the upper bound.
14. Unsigned Types, Visual Basic now supports unsigned integer data types (UShort, UInteger, and ULong) as well as the signed type SByte.
15. Operator Overloading, Visual Basic now allows you to define a standard operator (such as +, &, Not, or Mod) on a class or structure you have defined.
16. Partial Types, to separate generated code from your authored code into separate source files.
17. Visual Basic now supports type parameters on generic classes, structures, interfaces, procedures, and delegates. A corresponding type argument specifies at compilation time the data type of one of the elements in the generic type.
18. Custom Events. You can declare custom events by using the Custom keyword as a modifier for the Event statement. In a custom event, you specify exactly what happens when code adds or removes an event handler to or from the event, or when code raises the event.
19. Compiler Checking Options, The /nowarn and /warnaserror options provide more control over how warnings are handled. Each one of these compiler options now takes a list of warning IDs as an optional parameter, to specify to which warnings the option applies.
20. There are eight new command-line compiler options:
a. The /codepage option specifies which codepage to use when opening source files.
b. The /doc option generates an XML documentation file based on comments within your code.
c. The /errorreport option provides a convenient way to report a Visual Basic internal compiler error to Microsoft.
d. The /filealign option specifies the size of sections in your output file.
e. The /noconfig option causes the compiler to ignore the Vbc.rsp file.
f. The /nostdlib option prevents the import of mscorlib.dll, which defines the entire System namespace.
g. The /platform option specifies the processor to be targeted by the output file, in those situations where it is necessary to explicitly specify it.
h. The /unify option suppresses warnings resulting from a mismatch between the versions of directly and indirectly referenced assemblies.






C#.NET>>>>>>>

With the release of Visual Studio 2005, the C# language has been updated to version 2.0. This language has following new features:
1. Generics types are added to the language to enable programmers to achieve a high level of code reuse and enhanced performance for collection classes. Generic types can differ only by arity. Parameters can also be forced to be specific types.
2. Iterators make it easier to dictate how a for each loop will iterate over a collection's contents.
3. // Iterator Example
4. public class NumChar
5. {
6. string[] saNum = {
7. "One", "Two", "Three",
8. "Four", "Five", "Six",
9. "Seven", "Eight", "Nine",
10. "Zero"};
11. public
12. System.Collections.IEnumerator
13. GetEnumerator()
14. {
15. foreach (string num in saNum)
16. yield return num;
17. }
18. }
19. // Create an instance of
20. // the collection class
21. NumChar oNumChar = new NumChar();
22. // Iterate through it with foreach
23. foreach (string num in oNumChar)
24. Console.WriteLine(num);
25. Partial type definitions allow a single type, such as a class, to be split into multiple files. The Visual Studio designer uses this feature to separate its generated code from user code.
26. Nullable types allow a variable to contain a value that is undefined.
27. Anonymous Method is now possible to pass a block of code as a parameter. Anywhere a delegate is expected, a code block can be used instead: There is no need to define a new method.
28. button1.Click +=
29. delegate { MessageBox.Show(
"Click!") };
30. . The namespace alias qualifier (::) provides more control over accessing namespace members. The global :: alias allows to access the root namespace that may be hidden by an entity in your code.
31. Static classes are a safe and convenient way of declaring a class containing static methods that cannot be instantiated. In C# v1.2 you would have defined the class constructor as private to prevent the class being instantiated.
32. 8. There are eight new compiler options:
a. /langversion option: Can be used to specify compatibility with a specific version of the language.
b. /platform option: Enables you to target IPF (IA64 or Itanium) and AMD64 architectures.
c. #pragma warning: Used to disable and enable individual warnings in code.
d. /linkresource option: Contains additional options.
e. /errorreport option: Can be used to report internal compiler errors to Microsoft over the Internet.
f. /keycontainer and /keyfile: Support specifying cryptographic keys.

Conclusion
I think that this article will help you understand both language features and also you can choose a language based on your taste. I will update this article in future if there are any changes.


<<<<PREVIOUS

Differences Between VB.NET& C# .NET-2

Keyword Differences
Purpose
VB.NET
C#

Declare a variable VB.NET
Private, Public, Friend, Protected, Static1, Shared, Dim
Declare a variable c#.NET
declarators (keywords include user-defined types and built-in types)

Declare a named constant vb.net
Const
Declare a named constant c#.net
const

Create a new object vb.net
New, CreateObject()
Create a new object c#.net
new

Function/method does not return a value vb.net
Sub
Function/method does not return a value c#.net
void

Overload a function or method (Visual Basic: overload a procedure or method) vb.net
Overloads
Overload a function or method (Visual Basic: overload a procedure or method) c#.net
(No language keyword required for this purpose)

Refer to the current object vb.net
Me
Refer to the current object c#.net
this

Make a nonvirtual call to a virtual method of the current object vb.net
MyClass
Make a nonvirtual call to a virtual method of the current object c#.net
n/a

Retrieve character from a string
vb.net>> GetChar Function
c#.net>> []

Declare a compound data type (Visual Basic: Structure)
vb.net>>Structure End Structure
c#.net>>struct, class, interface

Initialize an object (constructors)
vb.net>>Sub New()
c#.net>>Constructors, or system default type constructors

Terminate an object directly
vb.net>>n/a
c#.net>> n/a

Method called by the system just before garbage collection reclaims an object7
vb.net>> Finalize
c#.net>>destructor

Initialize a variable where it is declared

vb.net>>Dim x As Long = 5
c#.net>>Dim c As New _
Car(FuelTypeEnum.Gas)


// initialize to a value:
vb.net>>int x = 123;
// or use default
// constructor:
c#.net>>int x = new int();


Take the address of a function
vb.net>> AddressOf (For class members, this operator returns a reference to a function in the form of a delegate instance)
c#.net>>delegate

Declare that an object can be modified asynchronously
vb.net>>n/a
c#.net>> volatile

Force explicit declaration of variables
vb.net>>Option Explicit
c#.net>>n/a. (All variables must be declared prior to use)

Test for an object variable that does not refer to an object
vb.net>>obj = Nothing
c#.net>>obj == null

Value of an object variable that does not refer to an object
vb.net>> Nothing
c#.net>> null

Test for a database null expression
vb.net>>IsDbNull
c#.net>>n/a

Test whether a Variant variable has been initialized
vb.net>>n/a
c#.net>>n/a

Define a default property
vb.net>>Default
c#.net>>by using indexers

Refer to a base class
vb.net>>MyBase
c#.net>>base

Declare an interface
vb.net>>Interface
c#.net>>interface

Specify an interface to be implemented
vb.net>>Implements (statement)
c#.net>>class C1 : I1

Declare a class
vb.net>>Class
c#.net>>class

Specify that a class can only be inherited. An instance of the class cannot be created.
vb.net>> MustInherit
c#.net>>abstract

Specify that a class cannot be inherited
vb.net>> NotInheritable
c#.net>>sealed

Declare an enumerated type
vb.net>> Enum End Enum
c#.net>>enum

Declare a class constant
vb.net>> Const
c#.net>>const (Applied to a field declaration)

Derive a class from a base class
vb.net>> Inherits C2
c#.net>>class C1 : C2

Override a method
vb.net>>Overrides
c#.net>> override

Declare a method that must be implemented in a deriving class
vb.net>> MustOverride
c#.net>> abstract

Declare a method that can't be overridden
vb.net>> NotOverridable (Methods are not overridable by default.)
c#.net>> sealed

Declare a virtual method, property (Visual Basic), or property accessor (C#, C++)
vb.net>>Overridable
c#.net>> virtual

Hide a base class member in a derived class
vb.net>> Shadowing
c#.net>> n/a

Declare a typesafe reference to a class method
vb.net>> Delegate
c#.net>>delegate

Specify that a variable can contain an object whose events you wish to handle
vb.net>> WithEvents
c#.net>> (Write code - no specific keyword)

Specify the events for which an event procedure will be called
vb.net>> Handles (Event procedures can still be associated with a WithEvents variable by naming pattern.)
c#.net>> n/a

Evaluate an object expression once, in order to access multiple members

vb.net>>With objExpr
<.member>
<.member>
End With

c#.net>>n/a

Structured exception handling

vb.net>>Try
Catch

Finally

End Try

c#.net>> try, catch, finally, throw

Decision structure (selection)
vb.net>> Select Case ..., Case, Case Else, End Select
c#.net>>switch, case, default, goto, break

Decision structure (if ... then)
vb.net>>If ... Then, ElseIf ... Then, Else, End If
c#.net>> if, else

Loop structure (conditional)
vb.net>> While, Do [While, Until] ..., Loop [While, Until]
c#.net>>do, while, continue

Loop structure (iteration)
vb.net>> For ..., [Exit For], Next
For Each ..., [Exit For,] Next
c#.net>> for, foreach

Declare an array

vb.net>>Dim a() As Long


c#.net>>int[] x = new int[5];


Initialize an array

vb.net>>Dim a() As Long = {3, 4, 5}



c#.net>>int[] x = new int[5] {
1, 2, 3, 4, 5};


Reallocate array
vb.net>> Redim
c#.net>> n/a

Visible outside the project or assembly
vb.net>>Public
c#.net>> public

Invisible outside the assembly (C#/Visual Basic) or within the package (Visual J#, JScript)
vb.net>> Friend
c#.net>> internal

Visible only within the project (for nested classes, within the enclosing class)
vb.net>>Private
c#.net>> private

Accessible outside class and project or module
vb.net>> Public
c#.net>>public

Accessible outside the class, but within the project
vb.net>> Friend
c#.net>>internal

Only accessible within class or module
vb.net>> Private
c#.net>> private

Only accessible to current and derived classes
vb.net>> Protected
c#.net>> protected

Preserve procedure's local variables
vb.net>> Static
c#.net>>n/a

Shared by all instances of a class
vb.net>> Shared
c#.net>> static

Comment code
vb.net>> '
Rem
c#.net>> //, /* */ for multi-line comments
/// for XML comments

Case-sensitive?
vb.net>> No
c#.net>> Yes

Call Windows API
vb.net>>Declare
c#.net>> use Platform Invoke

Declare and raise an event
vb.net>> Event, RaiseEvent
c#.net>>event

Threading primitives
vb.net>> SyncLock
c#.net>> lock

Go to
vb.net>> Goto
c#.net>> goto



Data types Differences
Purpose/Size


Decimal
vb.net>>Decimal
c#.net>> decimal

Date
vb.net>>Date
c#.net>> DateTime

(varies)
vb.net>> String
c#.net>> string

1 byte
vb.net>> Byte
c#.net>> byte

2 bytes
vb.net>>Boolean
c#.net>> bool

2 bytes
vb.net>> Short, Char (Unicode character)
c#.net>>short, char (Unicode character)

4 bytes
vb.net>> Integer
c#.net>> int

8 bytes
vb.net>> Long
c#.net>> long

4 bytes
vb.net>>Single
c#.net>> float

8 bytes
vb.net>> Double
c#.net>> double



Operators Differences
Purpose


Integer division
vb.net>>\
c#.net>> /

Modulus (division returning only the remainder)
vb.net>> Mod
c#.net>> %

Exponentiation
vb.net>>^
c#.net>> n/a

Integer division Assignment
vb.net>>\=
c#.net>> /=

Concatenate
vb.net>>&= NEW
c#.net>>+=

Modulus
vb.net>>n/a
c#.net>>%=

Bitwise-AND
vb.net>> n/a
c#.net>> &=

Bitwise-exclusive-OR
vb.net>> n/a
c#.net>>^=

Bitwise-inclusive-OR
vb.net>>n/a
c#.net>> |=

Equal
vb.net>> =
c#.net>> ==

Not equal
vb.net>><>
c#.net>> !=

Compare two object reference variables
vb.net>> Is
c#.net>>==

Compare object reference type
vb.net>> TypeOf x Is Class1
c#.net>> x is Class1

Concatenate strings
vb.net>> &
c#.net>>+

Shortcircuited Boolean AND
vb.net>>AndAlso
c#.net>>&&

Shortcircuited Boolean OR
vb.net>>OrElse
c#.net>> ||

Scope resolution
vb.net>> .
c#.net>> . and base

Array element
vb.net>> ()
c#.net>> [ ]

Type cast
vb.net>> Cint, CDbl, ..., CType
c#.net>> (type)

Postfix increment
vb.net>> n/a
c#.net>> ++

Postfix decrement
vb.net>>n/a
c#.net>> --

Indirection
vb.net>> n/a
c#.net>> * (unsafe mode only)

Address of
vb.net>> AddressOf
c#.net>> & (unsafe mode only; also see fixed)

Logical-NOT
vb.net>> Not
c#.net>> !

One's complement
vb.net>> Not
c#.net>>~

Prefix increment
vb.net>> n/a
c#.net>>++

Prefix decrement
vb.net>> n/a
c#.net>>--

Size of type
vb.net>> n/a
c#.net>>sizeof

Bitwise-AND
vb.net>>And
c#.net>> &

Bitwise-exclusive-OR
vb.net>> Xor
c#.net>>^

Bitwise-inclusive-OR
vb.net>>Or
c#.net>> |

Logical-AND
vb.net>> And
c#.net>>&&

Logical-OR
vb.net>> Or
c#.net>> ||

Conditional
vb.net>>If Function ()
c#.net>> ?:

Pointer to member
vb.net>>n/a
c#.net>> . (Unsafe mode only)



Programming Difference
<<<<PREVOIUS
NEXT>>>>

Differences Between VB.NET& C# .NET-1

Contents
Introduction
Advantages of both languages
Keyword Differences
Data types Differences
Operators Differences
Programming Difference
New Features of both languages in 2005 version
Conclusion
History
Introduction
Some people like VB.NET's natural language, case-insensitive approach, others like C#'s terse syntax. But both have access to the same framework libraries. We will discuss about the differences in the following topics:
Advantages of both languages
Keyword Differences
Data types Differences
Operators Differences
Programming Difference
Advantages of both languages

VB.net Advantages

Support for optional parameters - very handy for some COM interoperability.
Support for late binding with Option Strict off - type safety at compile time goes out of the window, but legacy libraries which don't have strongly typed interfaces become easier to use.
Support for named indexers.
Various legacy VB functions (provided in the Microsoft.VisualBasic namespace, and can be used by other languages with a reference to the Microsoft.VisualBasic.dll). Many of these can be harmful to performance if used unwisely, however, and many people believe they should be avoided for the most part.
The with construct: it's a matter of debate as to whether this is an advantage or not, but it's certainly a difference.
Simpler (in expression - perhaps more complicated in understanding) event handling, where a method can declare that it handles an event, rather than the handler having to be set up in code.
The ability to implement interfaces with methods of different names. (Arguably this makes it harder to find the implementation of an interface, however.)
Catch ... When ... clauses, which allow exceptions to be filtered based on runtime expressions rather than just by type.
The VB.NET parts of Visual Studio .NET compiles your code in the background. While this is considered as an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.

IN C#.net Advantages

XML documentation generated from source code comments. (This is coming in VB.NET with Whidbey (the code name for the next version of Visual Studio and .NET), and there are tools which will do it with existing VB.NET code already.)
Operator overloading - again, coming to VB.NET in Whidbey.
Language support for unsigned types (you can use them from VB.NET, but they aren't in the language itself). Again, support for these is coming to VB.NET in Whidbey.
The using statement, which makes unmanaged resource disposal simple.
Explicit interface implementation, where an interface which is already implemented in a base class can be re-implemented separately in a derived class. Arguably this makes the class harder to understand, in the same way that member hiding normally does.
Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies). Note that unsafe code is still managed code, i.e., it is compiled to IL, JITted, and run within the CLR.


NEXT>>>>

Thursday, April 24, 2008

Generics

Generic Method Creation

A generic method is a method that can process a value whose type is known only when the variable is accessed. To create a generic method, on the right side of the name of the method, type the <> operator. Inside of this operator, enter a letter or a name, which is referred to as parameter type. Here is an example:

public class Generator
{
public void Show()
{
}
}
One of the ways you can use the parameter type is to pass an argument to the method. You do this by preceding the name of the argument with the parameter type. Here is an example:

public class Generator
{
public void Show(TypeOfValue value)
{
}
}
In the body of the method, you can process the argument as you see fit. At a minimum, and based on our earlier program, you can simply display the value by passing it to the Console.WriteLine() method. Here is an example:

public class Generator
{
public void Show(TypeOfValue value)
{
Console.WriteLine(value);
}
}
By tradition, most programmers and most documents use the letter T for the parameter type.



Creating a Generic Method



To create a generic method, change the ShowItem() method as follows:
public void ShowItem(T item)
{
Console.WriteLine("Item: {0}", item);
}




Calling a Generic Method



As mentioned earlier, one of the particularities of a generic method is that, at the time it is defined, the method doesn't know the type of the parameter. This means that, when calling the method, you must make sure you clearly specify the type of value that will be processed. You can do this by directly passing (a constant of) the type of value that the method will process. Here are different examples of calling our Show() method:

using System;

public class Generator
{
public void Show(TypeOfValue value)
{
Console.WriteLine(value);
}
}

public class Exercise
{
static int Main()
{
var exo = new Generator();

// Call the version of the function that displays an integer
var Value1 = 246;
exo.Show(Value1);

// Call the version of the function that displays a character
var Value2 = 'G';
exo.Show(Value2);

// Call the version of the function that displays a decimal
var Value3 = 355.65;
exo.Show(Value3);

return 0;
}
}
When complied and executed, this program would produce:

246
G
355.65
Press any key to continue . . .

A Generic Method With Various Parameter Types



As seen above, you can pass different arguments to a method. You can also pass different parameter types, in any appropriate order of your choice, to a method. To pass two parameter types to a method, inside its <> operator, enter the names of two parameter types separated by a comma. Here is an example:

public class Generator
{
public void Show()
{
}
}
If you want to use the parameter types, you can pass an argument for each to the method. Remember that each parameter type represents a data type; so you can use it as the type of an argument. Here are examples:

public class Generator
{
public void Show(FirstType first,
SecondType second)
{
}
}
In the body of the method, you can then use the arguments as you see fit. For example, you can display their values by passing them to the Console.WriteLine() method. Here is an example:

public class Generator
{
public void Show(FirstType first,
SecondType second)
{
Console.WriteLine("First: {0}\nSecond: {1}\n", first, second);
}
}
Calling a Generic Method With Various Parameter Types



To call a method that takes various parameters, you can simply pass it the value of each argument. Here is an example:

using System;

public class Generator
{
public void Show(FirstType first,
SecondType second)
{
Console.WriteLine("First: {0}\nSecond: {1}\n", first, second);
}
}

public class Exercise
{
static int Main()
{
var exo = new Generator();

var iValue = 246;
var message = "Some Message";
exo.Show(message, iValue);

return 0;
}
}
This would produce:

First: Some Message
Second: 246

Press any key to continue . . .
An alternative is to specify the type of each argument. To do this, inside the <> operator on the right side of the name of the method, enter the data types separated by a comma. Here are examples:

using System;

public class Generator
{
public void Show(FirstType first,
SecondType second)
{
Console.WriteLine("First: {0}\nSecond: {1}\n", first, second);
}
}

public class Exercise
{
static int Main()
{
var exo = new Generator();

var iValue = 246;
var message = "Some Message";
exo.Show(message, iValue);

iValue = 85;
var cValue = 'G';
exo.Show(iValue, cValue);

var weeklyHours = 42.50d;
var hourlySalary = 25.05;
exo.Show(weeklyHours, hourlySalary);

return 0;
}
}
This would produce:

First: Some Message
Second: 246

First: 85
Second: G

First: 42.5
Second: 25.05

Press any key to continue . . .

Notice that the arguments can be of the same type or different types. It is up to you to determine the type of a particular argument when calling the method.

Software Design Patterns

This article is an introduction to Software Design Patterns. "Design Patterns" sounds new to a guy frm visual basic background . hmm. What you mean by "Design Patterns" for Software. Is it a new terminology just coined for software alone. Nope.. Its there in all fields !!!!.

So lets discuss what is Software Design Patterns from a developer perspective.

Design Patterns are pre-defined solutions to design problems in any software development. In our day-to-day life we are coming across lot of similiar problems and there are n- number of ways of solve the same.. But have u ever thing that the same problem which u solved can be handled in a different or a better method which is already defined..

Are you looking for a definition for Design patterns ?

"Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Design patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges"


The Gang of Four patterns is the base for all software design patterns available :-

GoF is caategorized into three groups

1. Creational
2. Structural
3. Behavioral

Just to summarize each group, here is the list of all 23 software design patterns

Creational Design Patterns

1. Abstract Factory
2. Factory Method
3. Prototype
4. Builder
5. Singleton

Structural Design Patterns

6. Adapter
7. Bridge
8. Composite
9. Decorator
10.Facade
11.Flyweight
12.proxy

Behavioural Patterns

13. Chain of Responsibility
14. Command
15. Interpreter
16. Iterator
17. Mediator
18. Memento
19. Observer
20. State
21. Strategy
22. Template Method
23. Visitor


Hope this will help you to get a general understanding of Software Design Patterns. In the
Upcoming sections I would like to discuss each design patterns in-depth

Wednesday, April 23, 2008

OOPS Concepts by Example

I assume that you are familar with the following OOP
concepts; classes, objects, attributes, methods, types. If not, then this article might not be
in your realm. I'd suggest starting with the basic concepts of C++ before you attempt to
understand the more indepth concepts that I'll be discussing in this article. When we
speak of OOP concepts, the conversation usually revolves around encapsulation,
inheritance and polymorphism. This is what I will attempt to describe in this article.
Inheritance
Let us start by defining inheritnace. A very good website for finding computer science
definitions is http://www.whatis.com. The definitions in this article are stolen from that
website.
Definition: Inheritance
Inheritance is the concept that when a class of object is defined, any subclass that is
defined can inherit the definitions of one or more general classes. This means for the
programmer that an object in a subclass need not carry its own definition of data and
methods that are generic to the class (or classes) of which it is a part. This not only
speeds up program development; it also ensures an inherent validity to the defined
subclass object (what works and is consistent about the class will also work for the
subclass).
The simple example in C++ is having a class that inherits a data member from its parent
class.
class A
{
public:
integer d;
};
class B : public A
{
public:
};
The class B in the example does not have any direct data member does it? Yes, it does. It
inherits the data member d from class A. When one class inherits from another, it
acquires all of its methods and data. We can then instantiate an object of class B and call
into that data member.
void func()
{
B b;
b.d = 10;
};
www.kbcafe.com
Copyright 2001-2002 Randy Charles Morin
Polymorphism
Inheritance is a very easy concept to understand. Polymorphism on the other hand is
much harder. Polymorphism is about an objects ability to provide context when methods
or operators are called on the object.
Definition: Polymorphism
In object-oriented programming, polymorphism (from the Greek meaning "having
multiple forms") is the characteristic of being able to assign a different meaning to a
particular symbol or "operator" in different contexts.
The simple example is two classes that inherit from a common parent and implement the
same virtual method.
class A
{
public:
virtual void f()=0;
};
class B
{
public:
virtual void f()
{std::cout << "Hello from B" << std::endl;};
};
class C
{
public:
virtual void f()
{std::cout << "Hello from C" << std::endl;};
};
I
f I have an object A, then calling the method f() will produce different results depending
on the context, the real type of the object A.
func(A & a)
{
A.f();
};
Encapsulation
The least understood of the three concepts is encapsulation. Sometimes, encapsulation is
also called protection or information hiding. In fact, encapsulation, protection and
information hiding are three overlapping concepts.
Definition: Encapsulation
Encapsulation is the inclusion within a program object of all the resources need for
the object to function - basically, the method and the data. The object is said to
"publish its interfaces." Other objects adhere to these interfaces to use the object
without having to be concerned with how the object accomplishes it. The idea is
"don't tell me how you do it; just do it." An object can be thought of as a selfcontained
atom. The object interface consists of public methods and instantiate data.
Protection and information hiding are techniques used to accomplish encapsulation of an
object. Protection is when you limit the use of class data or methods. Information hiding
www.kbcafe.com
Copyright 2001-2002 Randy Charles Morin
is when you remove data, methods or code from a class's public interface in order to
refine the scope of an object. So how are these three concepts implemented in C++?
You'll remember that C++ classes have a public, protected and private interface. Moving
methods or data from public to protected or to private, you are hiding the information
from the public or protected interface. If you have a class A with one public integer data
member d, then the C++ definition would be...
class A
{
public:
integer d;
};
I
f you moved that data member from the public scope of the private scope, then you
would be hiding the member. Better said, you are hiding the member from the public
interface.
class A
{
private:
integer d;
};
I
t is important to note that information hiding are not the same as encapsulation. Just
because you protect or hide methods or data, does not mean you are encapsulating an
object. But the ability to protect or hide methods or data, provide the ability to
encapsulate an object. You might say that encapsulating is the proper use of protection
and information hiding. As an example, if I used information hiding to hide members that
should clearly be in the public interface, then I am using information hiding techniques,
but I am not encapsulating the class. In fact, I am doing the exact opposite (unencapsulating
the class). Do not get the idea that encapsulation is only information
hiding. Encapsulation is a lot more. Protection is another way of encapsulating a class.
Protection is about adding methods and data to a class. When you add methods or data to
a class, then you are protecting the methods or data from use without first having an
object of the class. In the previous example, the data member d cannot be used except as
a data member of an object of class A. It is being protected from use outside of this
scenario. I have also heard many computer scientist use information hiding and
protection interchangeably. In this case, the scientist takes the meaning of protection and
assign it to information hiding. This is quite acceptable. Although I'm no historian, I
believe the definition of information hiding has taken some turns over the years. But I do
believe it is stabilizing on the definition I presented here.
Abstraction
Another OOP concept related to encapsulation that is less widely used but gaining ground
is abstration.
Definition: Abstraction
Through the process of abstraction, a programmer hides all but the relevant data about
an object in order to reduce complexity and increase efficiency. In the same way that
abstraction sometimes works in art, the object that remains is a representation of the
original, with unwanted detail omitted. The resulting object itself can be referred to as
www.kbcafe.com
Copyright 2001-2002 Randy Charles Morin
an abstraction, meaning a named entity made up of selected attributes and behavior
specific to a particular usage of the originating entity.
The example presented is quite simple. Human's are a type of land animal and all land
animals have a number of legs. The C++ definition of this concept would be...
class LandAnimal
{
public:
virtual int NumberOfLegs()=0;
};
class Human : public LandAnimal
{
public:
virtual int NumberOfLegs()
{return 2;};
};
The method NumberOfLegs in LangAnimal is said to be a pure virtual function. An
abstract class is said to be any class with at least one pure virtual function. Here I have
created a class LandAnimal that is abstract. It can be said that the LandAnimal class was
abstracted from the commonality between all types of land animals, or at least those that I
care about. Other land animals can derive there implementation from the same class.
class Elephant : public LandAnimal
{
public:
virtual int NumberOfLegs()
{return 4;};
};
Although I cannot create an instance of the class LandAnimal, I can pass derived
instances of the class to a common function without having to implement this function for
each type of LandAnimal.
bool HasTwoLegs(LandAnimal & x)
{
return (x.NumberOfLegs()==2);
};
There is also a less rigid definition of abstraction that would include classes that without
pure virtual functions, but that should not be directly instantiated. A more rigid definition
of abstraction is called purely abstract classes. A C++ class is said to be purely abstract, if
the class only contains pure virtual functions. The LandAnimal class was such a class.
Purely abstract classes are often called interfaces, protocol classes and abstract base
classes.
More Concepts
Another growing concept in OOP is dynamic and static binding. Most languages provide
one or the other. C++ provides both. A method that is not virtual is said to be statically
bound, whereas virtual methods are said to be dynamically bound. Non-virtual methods
are statically bound, because the binding of the method is performed at compile and link
time and cannot be changed. Virtual methods are dynamically bound, because the binding
of the method is actually performed at run-time. When you call a virtual method, a small
lookup is performed in the object virtual table (a.k.a. vtable) to find the address of the
method being called. By manipulating an objects vtable at run-time, the target address
www.kbcafe.com
Copyright 2001-2002 Randy Charles Morin
can be altered. Four other growing OOP concepts are persistance, concurrency, reflection
and object composition. I will not discuss these here, but maybe in a later article. Hope
this article proves informative and thank you for your time.