COM Interoperability

July 1st, 2005 | Posted by Vidya Vrat in .NET | C# - (0 Comments)

Using .NET Assembly from COM Client
This article explains about the .NET Interoperability with COM.

Step 1: Creating a .NET Assembly Project

1.1 Visual Studio .NET IDE -> File -> New Project ->
Visual Basic Projects -> Class Library

1.2 Name the Application, for instance NetServer, this will
be our .NET Assembly Project,which will be consisting of at
least one class called Class1.vb.

1.3 Rename the class to NetClass from properties window and manually
in code window.This class will hold all the functionality of .NET Component,
in the form of few functions.

Step 2: Adding Functionality

On the path of achieving COM Interoperability, Microsoft .NET
offers an attribute named ,which is
located inside the Micrsoft.VisualBasic namespace
and it makes the .NET Class available for use by a COM Client.

It’s also a wise choice to add System.Runtime.InteropService namespace to the class, which offers various features to be used.

The figure below shows the whole Code of .NET Assembly.

Step 3: Set Property for COM Interoperability

Select NETServer project from Solution Explorer, Right Click ->
Properties -> Configuration Properties -> Build -> Check on
Register for COM Interop after setting the property, do Build The Solution. It will create
a NetServer.dll (assembly) in your applications \bin folder.

Step 4: Deploying for COM access

A .NET assembly which has been created can’t be used by a COM Client,
because COM Client can access an object with help of a Type Library,
which tells to the Client about the Object.

In .NET world there is no such concept of Type LIbrary, but because of
COM Interop feature, .NET Framework SDK offers a tool called
RegAsm.Exe which offers to make a type library and
register it in Windows Registry, the very own style of COM.

4.1 Access Command Prompt (cmd)

4.2 Change the path to your application folder
for example : C:\>D: press enter
D:\> cd Net Applications\NetServer\Bin
D:\Net Applications\NetServer\Bin>

4.3 Type the following command to create a
Type Library,which is a COM world’s buzz word and equivalent
to Metadata of a .NET Assembly.

D:\Net Applications\NetServer\Bin> RegAsm /tlb: NetServer.tlb NetServer.dll

This command will create a Type Library named NetServer.tlb
in the \bin folder of .NET Assembly application. Which was
automatically registered in Windows Registry as well.

Now the .NET Assembly is ready to use by a COM Client.

Step 5: VB 6.0 Client to access .NET Assembly

5.1 Open Visual Studio 6.0 -> Visual Basic 6.0 ->
File -> New -> Standard.Exe

5.2 Drag one Label and two Command Buttons onto the form.

Step 6: Set Reference to the Type Library

Before consuming the class you build using .NET

Project -> References -> Find the NetServer and select that.

Step 7: Code to access the .NET Class

after adding the code, run your VB 6.0 and click on the command buttons, you will see that your application communicating with .NET Assembly.


Read My articles published on









My with C# 2.0

February 4th, 2005 | Posted by Vidya Vrat in Visual Studio - (0 Comments)

This article/tutorial talks about My namespace which is
a new feature available with Microsoft .NET Framework 2.0,
and VB .NET 2005 only feature.
About My
With the latest release of Visual Studio .NET 2005
codenamed Whidbey, VB .NET 2005 has been shipped
with one extra class in .NET Framework 2.0 BCL.
The My namespace’s with VB .NET 2005 will help
to write difficult code with a lot of ease.
For example, accessing computer information,
reading computer clock, opening ports, accessing
network, files etc.
Since this most fascinating feature is VB .NET 2005
specific which aimed to help VB .NET developers, and C#
geeks still has to write code for above mentioned tasks,
as like before.
Accessing My with C#
Besides having the total control and writing the code on
your own as being the real C# developer, My namespace can
be accessed and used in C# programs.
The idea of accessing My lies in the core .NET Framework 2.0 BCL
Base Class Library), and My namespace has its implementation in
an assembly named Micrisoft.VisualBasic.dll and uses Microsoft.VisualBasic.MyServices namespace.
By having reference to this assembly, the functionality of My
namespace can be used with C# also.
Code Example
The example shows how to call My in C#
Step – 1 Run Visual Studio .NET 2005 (Whidbey)
File –> New –> Project –>Visual C# –> Console Application
Step – 2 Add Reference to Microsoft.VisualBasic.dll under References

Step – 3 Add the following line under using directive
using Microsoft.Visualbasic.MyServices;
and then add the code to call the functionality
Click to view the code
Step – 4 Run the application and see the output.

This article/tutorial briefly introduced the My namespace and how to access My with C#.
Another point is that why My is VB .NET 2005 only feature, the reason I can think is Visual Basic is the language which has been greatly recognized for its IDE and Intellisense features and this is all what satisfies the term RAD and this is why it is available with VB .NET 2005 (by default) and not with C#. VB .NET Code Editor Window recognizes My and it is a Language Enhancement with VB .NET 2005.
Since, My namespace is the part of .NET Framework 2.0 BCL (Base Class Library), implemented in Microsoft.VisualBasic.dll assembly, under the namespace Microsoft.VisualBasic.MyServices namespace, any C# developers can also take advantage of that by having a reference to the Microsoft.VisualBasic.dll and invoking the functionality from Microsoft.VisualBasic.MyServices namespace.

To achieve MCSD .NET and MCAD.NET the participant has to understand the requirements which are mentioned below.

MCAD: Microsoft Certified Application Developer

MCSD: Microsoft Certified Solution Developer

MCAD for Microsoft .NET

Visual Basic .NET Language Path (Two required)

Exam 70-305: Developing and Implementing Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio .NET


Exam 70-306: Developing and Implementing Windows-based Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio .NET

Exam 70-310: Developing XML Web Services and Server Components with Microsoft Visual Basic .NET and the Microsoft .NET Framework

Visual C# Language Path (Two required)

Exam 70-315: Developing and Implementing Web Applications with C# and Microsoft Visual Studio .NET


Exam 70-316: Developing and Implementing Windows-based Applications with C# and Microsoft Visual Studio .NET

Exam 70-320: Developing XML Web Services and Server Components with Microsoft Visual C# and the Microsoft .NET Framework

Elective Exams (One Required)

Exam 70-229: Designing and Implementing Databases with Microsoft SQL Server 2000, Enterprise Edition

Note: This exam is widely by maximum of the developers.

Exam 70-230: Designing and Implementing Solutions with Microsoft BizTalk Server 2000, Enterprise Edition

Exam 70-234: Designing and Implementing Solutions with Microsoft Commerce Server 2000

MCSD for Microsoft .NET

Track: Visual Basic .NET (Four required)

Exam 70-305: Developing and Implementing Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio .NET

Exam 70-306: Developing and Implementing Windows-based Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio .NET

Exam 70-310: Developing XML Web Services and Server Components with Microsoft Visual Basic .NET and the Microsoft .NET Framework

Exam 70-300: Analyzing Requirements and Defining .NET Solution Architectures.

Note: This exam is required for all MCSDs, regardless of language choice.or

Track: Visual C# (Four required)

Exam 70-315: Developing and Implementing Web Applications with C# and Microsoft Visual Studio .NET

Exam 70-316: Developing and Implementing Windows-based Applications with C# and Microsoft Visual Studio .NET

Exam 70-320: Developing XML Web Services and Server Components with Microsoft Visual C# and the Microsoft .NET Framework

Exam 70-300: Analyzing Requirements and Defining .NET Solution Architectures. Note: This exam is required for all MCSDs, regardless of language choice.

Elective Exams (One Required)

Exam 70-229: Designing and Implementing Databases with Microsoft SQL Server 2000, Enterprise Edition

Exam 70-230: Designing and Implementing Solutions with Microsoft BizTalk Server 2000, Enterprise Edition

Exam 70-234: Designing and Implementing Solutions with Microsoft Commerce Server 2000

Other Info about Exam

Total Time: 175 Minutes (150 Minutes for the actual exam and 25 Minutes for survey and comments)

Fees: 2500 INR/Paper

Number of Actual Exam Questions may vary. (Around 58 questions)

Good way:

  1. Read each question carefully.
  2. Eliminate the wrong answers.
  3. Select the correct ones (or at least the nearest guess)
  4. Mark the questions which you don’t know the answers (With this, you can estimate the possibility of passing the test before hand) to review them later

Useful Links:

Reference Books:

1.Microsoft Press/PHI MOC Books on Web/Windows etc

2.ADO.NET Step by Step by Rebecca

3.Advanced .NET Remoting – Ingo Rammer

4.Windows-Based Applications with and Ms-VB.NET.

5.Web-Based Applications with and Ms-VB.NET.

6.Professional C# Wrox.

7.Xml WebServices by Scott

8..Net Remoting -By Jason Bock, Pete Stromquist, Tom Fischer, Nathan Smith

9.Com + (o’riely )

Father of C#

January 26th, 2005 | Posted by Vidya Vrat in C# - (0 Comments)

Name: Anders Hejlsberg

Designation: Microsoft Distinguished Engineer and chief architect of C#.

* He is one of the most successful developers in the IT cosmos in recent times.
* He stands among one of the Borland Corporation’s first employees.
* He was the original author of Turbo Pascal.
* He worked as the chief architect of the Delphi product line.

At Microsoft:
In 1996 he joined Microsoft, and played a pivotal role in the development
and design of Visual J++ and the Windows Foundation Classes.
Then he worked on COM+, followed by the VS.NET Framework team.

Over the past 5 years, as one of only 20 Distinguished Engineers at Microsoft, he has distinguished himself still further, as the brains behind the creation of C# the first component-oriented programming language in the C and C++ family to combine the power of those languages with the functional ease of modern, rapid application development tools. Anders, who is Danish, originally studied engineering at the Technical University of Denmark.


Longhorn Screenshots

December 29th, 2004 | Posted by Vidya Vrat in Visual Studio - (0 Comments)

New TaskBar & Desktop Look

New Menu Style

Arranging Windows

What .NET is all about?

October 5th, 2004 | Posted by Vidya Vrat in .NET - (0 Comments)

It’s a new Object Oriented Paradigm from Microsoft.

.NETwas released in July 2000 in a PDC (Professional Developers Conference) Orlando Florida, where Bill Gates revealed the details of their new platform called NGWS (Next Generation Windows Services).

What is .NET?

*  It is a framework, which offers new Object Oriented programming paradigm.
*  Is a layer between the operating system and the programming language
*  It supports many programming languages, including VB.NET, C# , C++ .NETetc.
*  .NET provides a common set of class libraries, which can be accessed from any .net based programming language. The language does not matter, you can write code in any .net language!!

What .NET is Not?

*  .NET is not an operating system.
*  .NET is not a programming language.

“.NET is a framework”

.NET is a common Language Neutral platform for all the supported languages known as .NET compliant language. It gives a common class library known as Base Class Library (BCL) or Framework Class Library (FCL), which can be called from any of the .NET supported languages. So, developers need not to learn many libraries when they switch to a different language like earlier MFC, ATL and Win32 API etc. Microsoft .NET offers common Library (BCL) and only the syntax is different for each language, where as all the languages can share the same features.

When you write code in any language and compile, it will be converted to an ‘Intermediate Language – IL or MicroSoft Intermediate Language – MSIL. So, the compiled executable contains the IL and not really executable machine language. When the .Net application runs, the JIT (Just In-Time) compiler of .NET framework on the target computer take care of the execution. Note: To run a .NET application, the target computer should have .NET framework installed.

What is Visual Studio .NET?

Visual Studio is not a new concept it has been around for many years, Visual Studio 6.0 is a development tool which has fascinated almost every programmer on the planet earth.

Visual Studio .NET is just another version of Visual Studio designed to write .NET applications. VS.NET is not a must to write .NET application. Notepad can be used to write an application and can be compiled by using .NET command line compilers (Csc/Vbc) which are freely available with .NET Framework SDK, after compilation result can be seen on console.

.NET supported languages

Currently .NET supports the following languages:
*  C#
*  Managed C++ .NET
*  J#
*  Jscript .NET

The above languages are known as Microsoft .NET compliant languages. Whereas Many third parties are writing compilers for other languages with .NET support for example COBOl, Pearl, Python etc.

Difference between VB and VB.NET

There is not much in common between VB and VB .NET other than the base name. VB.NET is a totally new programming language. It just retains the syntax of old VB. So, if you are a VB programmer, probably you may like VB .NET than C# just because of the syntax and case sensitive nature.

In addition to this, VB .NET still supports many of the old VB functions just for backward compatibility. Microsoft .NET also provides Upgrade Wizard to migrate VB 6.0 applications to VB .NET.

C# or VB.NET? Which one to choose?

It’s very difficult to state which one to choose, the choice actually depends on an individual’s choice and programming experience.Where as in reality .NET Framework itself has no discrimination between the languages.

VB .NET has backward compatibility with old Visual basic VB 6.0. and C# is a fresh, clean language.

Is .NET platform independent?

No, but it is Language Independent. Microsoft wrote .NET Framework with a vision of Language Independence to be offered to all the programming languages. I.e. all the languages can communicate means interoperable.

As .NET has attracted many programmers from different technical planets, are taking advantage of .NET, Linux has .Net implementation named mono, which met ECMA (European Computer Manufacturers Association) standard what C# is based on.

Future of .NET

As it is an awesome programming paradigm which offers all the features of a language and easy access to OS and machine resources. Many programmers are taking advantage of this new product of Microsoft and shipping their software codes with an increased productivity and ease.

Microsoft is moving all its technologies to be .NET based or .NET related. The next version of SQL Server (code named – Yukon) even supports writing stored procedures in .NET languages. The .NET runtime will be part of all Operating Systems by default. Like already it has been shipped with Windows 2003. There are some other great .NET products about to ship, code named Whidbey (Visual Studio .NET 2005), Longhorn and Orcas (Visual Studio .NET for Longhorn).

Q/A: What .NET Means

September 29th, 2004 | Posted by Vidya Vrat in .NET | Visual Studio - (0 Comments)

What is Microsoft .NET?


. NET is the Microsoft solution for XML Web services, the next generation of software that connects our world of information, devices, and people in a unified, personalized way.

. NET technology enables the creation and use of XML-based applications, processes, and Web sites as services that share and combine information and functionality with each other by design, on any platform or smart device, to provide tailored solutions for organizations and individual people.

. NET is a comprehensive family of products, built on industry and Internet standards, that provide for each aspect of developing (tools), managing (servers), using (building block services and smart clients) and experiencing (rich user experiences) XML Web services. .NET will become part of the Microsoft applications, tools, and servers you already use today—as well as new products that extend XML Web service capabilities to all of your business needs.

What is a .NET experience?


The Microsoft .NET experience is a dramatically more personal, integrated computing experience using connected XML Web services delivered through smart devices.

  • Personal and integrated experience. In contrast to silos of information divided by provider, .NET experiences are centered around the user, integrating their data and preferences into a single application.
  • Connected XML Web services. Through the use of XML and SOAP, a range of services tailored to the needs of the user can be fed into a single, integrated experience.
  • Interactions delivered through smart devices. Users experience .NET through their interactions with smart devices. Smart devices are Web enabled appliances, such as personal computers, handheld computers, and smart phones, with software that makes them more intelligent in their interactions with users, the network, information, other devices, and services.

What is an example of a .NET experience?

A .NET experience is analogous to a user’s interaction with a current standalone application, with three important differences, described through this example:

Imagine you wanted to turn up the heat in your house while you were away from home. You could use a .NET experience that controls your household utilities through a smart device. The device you use could be your desktop computer while you were at the office, your smart phone while you were driving to the grocery store, or a kiosk while you were shopping for dinner ingredients.

The uniqueness of the .NET experience in this example is:

  • Each of these devices generates a different interface for the .NET experience. The desktop computer might present a graphical map and accept mouse input. The smart phone could give you verbal options and ask you to push a button to specify your choice. The kiosk may have a touch screen and a small set of temperature options. You’re using the same .NET experience to perform the same task, but you see a distinct interface, which is appropriate to the device.
  • .NET experiences are location-independent. Taking advantage of the strengths of both locally-installed and Web-based applications, .NET experiences can be accessed both online and offline. In the previous example, you could use a .NET experience no matter where you are: at work, in the car, or at the store.
  • .NET experiences are personalized. .NET experiences read a user’s preferences and profile information, stored in building block services, and automatically incorporate the user’s information and preferences into what’s being presented. In the previous example, when you’re turning on the heat, the .NET experience already knows where you live, based on your log-in ID. You don’t need to enter an address.

How manageable is .NET?


Microsoft has many tools and technologies designed to make .NET technology manageable—now and as applications evolve. The reliance of XML and SOAP as underlying technologies for .NET ensures greater system interoperability between systems, improving the management of applications and services.

Current technologies and products include:

  • Microsoft Windows® 2000 Server to manage directory, events, and distributed clients.
  • Windows 2000 Datacenter Server for guaranteed reliability.
  • Microsoft SQL Server® 2000 to manage XML data.
  • Microsoft BizTalk™ Server to manage events, processes, and contracts across diverse systems.
  • Microsoft Application Center Server to manage clusters.
  • Digital Rights Management (DRM) for managing authorization of content.
  • Universal Description, Discovery, and Integration (UDDI) to promote XML Web services to third parties.

How scalable is .NET?

Through the use of .NET server technology—the ability to reuse and update XML Web services on the fly as well as distributing computing power across multiple devices—.NET offers a highly scalable solution.

  • Scale out with Windows 2000 Server, SQL Server 2000, and Application Center 2000.
  • Scale up with Windows 2000 Server and SQL Server 2000.
  • Use smart devices and XML Web services to break the linear scaling dynamic. By distributing computing to the edge of the network (where there is an abundance of computing power), the bottleneck of server processing power can be removed. By making it simple for the services which are the building blocks of applications to be distributed anywhere on the network, other bottlenecks can be eliminated or minimized, as well.

How does .NET address security and privacy concerns?


.NET will provide strong privacy protection by placing users in control of their own data. Users will dictate which people and applications can access or alter particular pieces of their personal data. These permissions are associated with binding privacy policies which outlive specific transactions.

Effective security requires a combination of secure software and good operational practices, physical security, and license agreements. Some of the current and upcoming software security programs and technologies that are part of the .NET solution include:

  • Windows 2000 for Kerberos, the Microsoft Active Directory® service, PKI, EFS, and IP Sec.
  • Building block services for simple, private, and secure experiences with full user control of the data they own.
  • XML messaging interfaces on the building block services, which enable auditing and accountability.
  • Digital Rights Management (DRM) for authorization of content.

Why should developers choose .NET instead of other XML solutions?

Microsoft .NET technology delivers the following unique benefits to developers:

  • It’s easier, faster, and less expensive to build and integrate XML Web services through .NET tools (.NET Framework and Microsoft Visual Studio® .NET).
  • The user experience is richer and more compelling because of smart devices and information agents.
  • The .NET experience is personal and manageable because of identity-centric building block services.
  • It’s built from the ground-up for the next generation of software with XML at the core.

What are the benefits of the .NET programming model and tools?


.NET Framework offer the following benefits to developers:

  • Best, fastest and least expensive way to build XML Web services
  • Programming model designed from the ground up for XML Web services
  • High productivity, multi-language environment for building and running XML Web services
  • Secure, scalable, high-performance execution
  • Multi-device support. Through Visual Studio .NET and the .NET Compact Framework, developers can use existing skills to create solutions for a wide range of devices.

Why does .NET employ XML?


XML is the common language of data exchange on the Internet. It provides a widely-embraced, open standard technology for data exchange and transformation, overcoming barriers to application and service interoperability and integration.

What’s the difference between an XML Web service and a Web site?


Unlike Web sites, which are pictures of data designed to be viewed in a browser by a person, an XML Web service is designed to be accessed directly by another service or software application.

XML Web services are reusable pieces of software that interact programmatically over the network through industry recognized standards (XML and SOAP). XML Web services can be combined with each other and other applications to build intelligent interactive .NET eperiences.

What are “smart devices”?


.NET uses software for smart devices to enable PCs, laptops, workstations, smart phones, handheld computers, Tablet PCs, game consoles, and other smart devices to operate in the .NET universe. A smart device is:

  • Smart about you. A smart device uses your .NET identity, profile, and data to simplify your experience and is smart about your presence, allowing tailoring of notifications in response to your presence or absence.
  • Smart about the network. A smart device is responsive to bandwidth constraints, provides support for both online and offline use of applications, and understands which services are available.
  • Smart about information. A smart device allows you to access, analyze, and act on data anywhere anytime.
  • Smart about other devices. A smart device discovers and announces PCs, other smart devices, servers, and the Internet; knows how to provide services to other devices; smart about accessing information from the PC.
  • Smart about software and services. A smart device presents applications and data optimally for form factor; enables input methods and connectivity appropriate for great end-user interaction; consumes Web services using XML, SOAP, and UDDI; and programmable and extensible by developers.

How do servers fit into .NET?

Microsoft offers an integrated suite of servers that provide secure, scalable high-performance execution for the Enterprise and XML Web services. Because they are designed for deep level support of XML, they offer the best and least expensive way to run and manage XML Web services.

What is the role of Windows in .NET?

Microsoft Windows currently powers the ultimate smart device: the personal computer. Microsoft Windows XP will be able to consume XML Web services, such as photo services, as well as utilize XML Web services to publish to the Web. It will act as a hub for smart devices and interact in the next generation of peer-to-peer computing, real-time communications, and media services.

Microsoft Windows .NET Server 2003 will include built-in support for XML and SOAP and will ship with the .NET Framework.



Trap #1: Nondeterministic finalization and the C# destructor

The biggest difference in C# for most C++ programmers will be garbage collection. You will no longer have to worry about memory leaks and ensuring that pointers are deleted, but you also give up precise control over when your objects will be destroyed.

If you control an unmanaged resource, however, you will need to explicitly free that resource when you are done with it. Implicit control over unmanaged resources is provided by a destructor, which will be called by the garbage collector when your object is destroyed.

The destructor should only release unmanaged resources that your object holds on to, and it should not reference other objects. If you have only managed references you do not need to (and should not) implement a destructor. You want this only for handling unmanaged resources. Because there is some cost to having a destructor, you ought to implement this only on methods that consume valuable, unmanaged resources.

You never call an object’s destructor directly. The garbage collector will call it for you.

How destructors work

The garbage collector maintains a list of objects that have a destructor. This list is updated every time such an object is created or destroyed.

When an object on this list is first collected, it is placed on a queue with other objects waiting to be destroyed. After the destructor executes, the garbage collector then collects the object and updates the queue, as well as its list of destructible objects.

The C# destructor

C#’s destructor looks, syntactically, much like a C++ destructor, but it behaves quite differently. You declare a C# destructor with a tilde as follows: ~MyClass(){}

In C#, however, this syntax is simply a shortcut for declaring a Finalize() method that chains up to its base class. Thus, when you write:

~MyClass() { // do work here }

the C# compiler translates it to:

protected override void Finalize()




// do work here







Trap #2: Finalize versus Dispose

It is not legal to call a destructor explicitly. Your destructor will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface. The IDisposable interface requires its implementers to define one method, named Dispose(), to perform whatever cleanup you consider to be crucial. The availability of Dispose() is a way for your clients to say, “Don’t wait for the destructor to be called; do it right now.”

If you provide a Dispose() method, you should stop the garbage collector from calling your object’s destructor. To stop the garbage collector, you call the static method, GC.SuppressFinalize(), passing in this reference for your object. Your destructor can then call your Dispose() method. Thus, you might write:

using System;

class Testing : IDisposable


bool is_disposed = false;

protected virtual void Dispose(bool disposing)


if (!is_disposed) // only dispose once!


if (disposing)


Console.WriteLine(“Not in destructor, OK to referenceother objects”); }

// perform cleanup for this object



this.is_disposed = true;


public void Dispose()



// tell the GC not to finalize






Console.WriteLine(“In destructor.”);



Implementing the Close method

For some objects, you’d rather have your clients call the Close() method. (For example, Close makes more sense than Dispose() for file objects.) You can implement this by creating a private Dispose() method and a public Close() method and having your Close() method invoke Dispose().

Trap #3: C# distinguishes between value types and reference types

Like C++, C# is a strongly typed language, and like C++, C# divides types into two sets: intrinsic (built-in) types offered by the language, and user-defined types that are defined by the programmer.

In addition to intrinsic types and user-defined types, C# differentiates between value types and reference types. Value types hold their value on the stack, like variables in C++, unless they are embedded within a reference type. Reference-type variables sit on the stack, but they hold the address of an object on the heap, much like pointers in C++. Value types are passed to methods by value (a copy is made) while reference types are effectively passed by reference.

Classes and interfaces create reference types, but note carefully that structs are value types, as are all the intrinsic types (see Trap #5).

Trap #4: Watch out for implicit boxing

Boxing and unboxing are the processes that enable value types (for example, integers) to be treated as reference types (objects). The value is “boxed” inside an object, and subsequently “unboxed” back to a value type. Every type in C#, including the intrinsic types, derive from Object and may be implicitly cast to an object. Boxing a value allocates an instance of Object and copies the value into the new object instance. Boxing is implicit, so when you provide a value type where a reference is expected the value is implicitly boxed. Boxing brings some performance overhead, so avoid boxing where possible, especially in large collections.

To return the boxed object back to a value type you must explicitly unbox it. The unboxing occurs in two steps: Check the object instance to make sure it is a boxed value of the given value type. Copy the value from the instance to the value-type variable. In order for the unboxing to succeed, the object being unboxed must be a reference to an object that was created by boxing a value of the value type.

using System;

public class UnboxingTest


public static void Main()


int i = 123;

object o = i; //Boxing

int j = (int) o; // unboxing (must be explicit)

Console.WriteLine(“j: {0}”, j);



If the object being unboxed is null or a reference to an object of a different type, an InvalidCastException is thrown.

Trap #5: Struct is very different in C#

In C++ a struct is nearly identical to a class. In C++, the only difference is that a struct has public access as its default (rather than private) and its inheritance is public by default (again, rather than private). Some C++ programmers use structs as data-only objects, but that is a convention not supported by the language and discouraged by many object-oriented designers.

In C#, a struct is a simple user-defined type, a lightweight alternative that is quite different from a class. While structs do support properties, methods, fields, and operators, structs don’t support inheritance or destructors.

More importantly, while a class is a reference type, a struct is a value type (see Trap #3). Thus, structs are useful for representing objects that do not require reference semantics. Structs are somewhat more efficient in their use of memory in arrays, however, they may be less efficient when used in collections. Collections expect references, and structs must be boxed (see Trap #4). There is overhead in boxing and unboxing, and classes may be more efficient in large collections.

Trap #6: Virtual methods must be explicitly overridden

In C#, the programmer’s decision to override a virtual method must be made explicit with the override keyword.

To see why this is useful, assume that a Window class was written by Company A, and that ListBox and RadioButton classes were written by programmers from Company B, using a purchased copy of the Company A Window class as a base. The programmers in Company B have little or no control over the design of the Window class, including future changes that Company A might choose to make.

Now suppose that one of the programmers for Company B decides to add a Sort method to ListBox:

public class ListBox : Window


public virtual void Sort() {…}


This presents no problems until Company A, the author of Window, releases version 2 of its Window class. It turns out that the programmers in Company A also added a Sort method: public class Window


// …

public virtual void Sort()



In C++ the new virtual Sort method in Window would now act as a base method for the virtual Sort method in ListBox. The compiler would call the Sort method in ListBox when you intend to call the Sort in Window. In C#, a virtual function is always considered to be the root of a virtual dispatch, that is, once C# finds a virtual method, it looks no further up the inheritance hierarchy. If a new virtual Sort Employee::Employee(int theAge, int theSalaryLevel):

Person(theAge) // initialize base

salaryLevel(theSalaryLevel) // initialize member variable


// body of constructor


This construct is not legal in C#. While you can still initialize the base, the initialization of the member variable as shown here would cause a compile error. You can, however, set the initial value for the member variable in C# when you declare it: Class Employee : public Person{ // declarations here private salaryLevel = 3; // initialization}

Note also that you do not add a semicolon after the class declaration, and that each member must have its access declared explicitly.

Trap #8: Boolean values do not convert to integers

In C#, Boolean values (true, false) do not equate to integer variables. Thus, you may not write: if ( someFuncWhichReturnsAValue() )

and count on the idea that if someFuncWhichReturnsAValue returns a zero it will evaluate false, otherwise true. The good news is that the old error of using assignment versus equality is no longer a problem. Thus, if you write:

if ( x = 5 )

you will not inadvertently assign 5 to x, you will get a compile error, since x = 5 evaluates to 5, which is not a Boolean value.

Trap #9: You may not “fall through” in switch statements

In C#, a switch statement may not “fall through” to the next statement if it does any work. Thus, while the following is legal in C++, it is not legal in C#:

switch (i)


case 4:


case 5: // error, no fall through



To accomplish this, you need to use an explicit Go To statement:

switch (i)


case 4:


goto case 5;

case 5:



If the case statement does no work (has no code within it) then you can fall through: switch (i)


case 4: // fall through

case 5: // fall through

case 6:



Trap #10: C# requires definite assignment

C# imposes definite assignment, which requires that all variables be assigned a value before they are used. Thus, you can declare a variable without initializing it, but you may not pass it to a method until it has a value.

This raises a problem with values you create simply to pass them to a method by reference, to act as “out” parameters. For example, suppose you have a method that returns the current hour, minute, and second. If you were to write: int theHour;int theMinute;int theSecond;timeObject.GetTime( ref theHour, ref theMinute, ref theSecond)

You would get a compile error for using theHour, theMinute, and theSecond without initializing them:

Use of unassigned local variable ‘theHour’

Use of unassigned local variable ‘theMinute’

Use of unassigned local variable ‘theSecond’

You can initialize them to zero or some other innocuous value to quiet the pesky compiler:

int theHour = 0;

int theMinute = 0;

int theSecond = 0;

timeObject.GetTime( ref theHour, ref theMinute, ref theSecond)

But that is too silly. The point of these variables is to pass them by reference into GetTime, where they’ll be changed. C# provides the out parameter modifier for this situation. The out modifier removes the requirement that a reference parameter be initialized. The parameters to GetTime, for example, provide no information to the method; they are simply a mechanism for getting information out of it. Thus, by marking all three as out parameters, you eliminate the need to initialize them outside the method. Out parameters must be assigned a value before the method they are passed into returns. Here are the altered parameter declarations for GetTime: public void GetTime(out int h, out int m, out int s)


h = Hour;

m = Minute;

s = Second;


and here is the new invocation of the GetTime method:

timeObject.GetTime( out theHour, out theMinute, out theSecond);