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()

{

try

{

// do work here

}

finally

{

base.Finalize();

}

}

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

Console.WriteLine(“Disposing…”);

}

this.is_disposed = true;

}

public void Dispose()

{

Dispose(true);

// tell the GC not to finalize

GC.SuppressFinalize(this);

}

~Testing()

{

Dispose(false);

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:

CallFuncOne();

case 5: // error, no fall through

CallSomeFunc();

}

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

switch (i)

{

case 4:

CallFuncOne();

goto case 5;

case 5:

Call

}

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:

CallSomeFunc();

}

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);

Thoughts (Brain Diet) Ver 1.0

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

No Pain, No Gain.

There are no shortcuts to any place, worth going.

A kite rises against, not with the wind.

 

<br>      Stick to the <b>Fight</b>

<br>    When you are hardest <b>Hit</b>

<br>     It’s when things seem <b>Worst</b>

<br>      that you must not <b>Quit</b>.

<br>

 

<br>     Winners don’t do different things,

<br>         they do things differently.

<br>

 

<br>       I slept and dreamt that life was joy,

<br>       I woke and saw that life was duty,

<br>        I acted and behold duty was joy.

<br>

There is no substitute for Prepration,

Practice and Hardwork.

Whidbey and Yukon

This articles reveals all the features of latest upcoming Microsoft Server and Development tools code named Yukon formally known as SQL Server 2005 or SQL Server .NET and Whidbey formally known as Visual Studio .NET 2005.

Introduction to .NET

September 1st, 2004 | Posted by Vidya Vrat in .NET - (0 Comments)

Introduction

The .NET Platform consists of a set of technologies and tools designed to simplify development of distributed applications, including Windows applications, Windows services, console applications, and Web services. The .NET Platform also helps you to build applications using a collection of Web services and supports the existing Internet infrastructure such as Hyper Text Transfer Protocol (HTTP), Extensible Markup Language (XML), and Simple Object Access Protocol (SOAP).

The .NET Platform provides:
• A consistent programming model
• Multi-language support
• Easy migration from existing technologies

Components of .NET Platform

The following are some of the key components of the .NET Platform.
• .NET Framework
• .NET Compact Framework
• Visual Studio .NET
• Visual Studio Tools for the Microsoft Office System (VSTO)
• XML Web services

.NET Framework

The foundation of the .NET Framework is based on the CLR. The CLR manages the execution for all .NET-based applications. The CLR provides a common set of services to the applications that you can develop by using any of the .NET compliant languages. A .NET compliant language adheres to a set of common standards defined by the Common Language Specification (CLS). The CLS standards form the basis on which the common type system provides a set of common data types that can be used across all .NET programming languages.

.NET Compact Framework

The .NET Compact Framework is derived from the .NET Framework architecture. The .NET Compact Framework provides a hardware-independent programming environment to devices that have limited system resources such as pocket PCs and mobile phones, and other custom devices with Windows CE .NET operating system.

Microsoft Visual Studio® .NET

Visual Studio .NET provides an integrated development environment (IDE) and key technologies to simplify the creation and deployment of .NET Framework–based applications. The .NET Framework–based applications are Windows-based applications, Web applications, and Web services.

Visual Studio Tools for the Microsoft Office System (VSTO)

With this new technology, you can write managed code for Microsoft Word and Microsoft Excel®, which responds to events within the automation models. While the Visual Basic for Applications (VBA) and COM-based automation will continue to be supported in the .NET Platform, VSTO provides you the complete power of the .NET Framework, including a familiar coding experience that includes F1 Help support, full-featured debugging, and IntelliSense in the Code Editor. You also get full use of managed controls, improved deployment and maintenance of solutions, improved security, and the ability to consume and expose Web services directly from Office programs.

XML Web services

An XML Web service is a software program that can be accessed by applications locally and remotely. One of the primary advantages of the XML Web services architecture is that it permits programs written in different languages and on different platforms to communicate with each other. This multi-language communication uses unified class libraries, intermediate language and the dynamic execution environment of the CLR. An improvement in the XML Web services now is, that the XML Web services work with standard Web protocols—XML, HTTP and TCP/IP. XML Web services use SOAP as their communication protocol. SOAP is a specification that defines the XML format for messages. XML Web services are described with a Web Services Description Language (WSDL) file to allow interoperability between programs, regardless of the language and the platform. A WSDL file is an XML document that describes a set of SOAP messages and how the messages are exchanged

Abstract

Many technical people have the dilemma at some stage in their technology career, whether they should choose a technological role, like Lead, Architect and so on or Managerial role like PM.

In my view all the roles are good and have many great career opportunities. But it’s up to you do decide what you want to become and what steps you have taken to fulfill your career aspirations.

Define your own Career

In my view, it’s up to an individual to plan his/her career. It may happen that you are influenced to accept the role that you didn’t want to take. I believe that, rather than being influenced by someone, you should develop the skills to influence others and put you into that role.

 Any organization can define your Job, but only you must define your Career

 Job Vs Career

Many people don’t understand the difference between the two and that’s a very common thing. Let me help you.

A career is the pursuit of a lifelong ambition or the general course of progression towards lifelong goals that provides you a sense of fulfillment and comes out of you naturally with all your passion and creativity. Besides, you get paid well while doing that.

A Job is just an activity through which an individual can earn money. It is a regular activity in exchange for payment. But you have no passion for that work, it doesn’t matter if you don’t do that for a few days. You don’t miss it and you don’t seek any areas of improvement in that.

Situation Trap

Many times people are influenced to become what they never wanted to be. In my long tenure in the IT industry I have learned that most people just accept a role because their manager told them to slide into that role and then that becomes their career path.

I am not saying that it’s totally wrong. I have been into such situations and I did all I could to detour from that and return to the right track and keep moving towards where I wanted to be.

“So it’s not always people who drag us into a situation; it’s us who must come out of it.”

How to come out of Trap

I get many emails and messages from people saying that their employer is forcing them to become a test engineer, handle a team, work on maintenance and many other off-track tasks that they have no interest in.

Now, in many situations you can’t avoid it, because you need a job and money and this is a bitter truth of life. However, the key is what steps to take to get out of it.

  1. Before accepting such role/assignment, discuss the duration with your manager and so on.
  2. Provide yourself limited time to come out of that and share that with management; have it in writing and include HR also if you can. In many cases the company will say 2 months but you dragged yourself for 2 years in that.
  3. If nothing works then it’s time to move on.

Deciding Whether to Move On

In general, people look out for options when they are frustrated and not prepared at all. Being not prepared causes a delay in getting shortlisted for jobs in the industry and this causes further frustration. People often end up in the same place and doing the same thing.

In my opinion, changing a job needs to be well-planned, unless you are lucky that you have the tendency to land into the right opportunity every time.

The following procedure will help you.

  1. Your decision to move must be driven by motivation rather than frustration.
    I have observed that many people just wait until appraisal and soon after that they look for a job change. Well, this is right, since as I said above, due to the need for money, but money is not everything all the time.
  2. Always have your resume/cv ready and updated, I still do that. I continually update it for the projects I do and new skills I develop.
  3. Have a LinkedIn profile, you can’t build it overnight. Seek good like-minded connections.
  4. Continue applying for jobs, even when you don’t want to change immediately. So you know if your CV / resume is getting some traction in the job market or not.
  5. Also focus on non-technical skills and continue to refine skills like communication and presentation and so on.

Techniques to work on your career goals

  1. Have a road map in place that defines all that is expected from your desired role.
  2. Think global, people often only focus on job-related skills that are local to their country. This again can’t help you to build a career.
  3. Invest in learning the right technical / non-technical skills.
  4. Find a mentor who can help you elevate yourself, preferably who has done it by him/herself. Learning from people who havn’t experienced what you want to be will lead you nowhere.
  5. Invest in learning, skills building and the right type of social networking.
  6. Your current job is the best place to learn and experiment with new skills you are building.
  7. Make yourself visible at the organizational level.
  8. Have a reputation in your company.
  9. Have a command of the English Language. You must be able to learn, listen, speak, read and write in English. You can read my article on 10 Rule of English Communication for Developers.
  10. Seek for opportunities and meet like-minded people.

What I do to take charge of my career

  1. Always focus on your career goals.
  2. Work on cultivating skills for that role
  3. Invest in learning
  4. Apply your learning and skills
  5. Set Targets

Always focus on your career goals

Let’s say you are a developer and you want to be a Tech Lead, or a Tech Lead wants to be an Architect. Then you need to understand what the industry expects from that role, regardless of what people tell you to be or become.

Work on cultivating skills for that role

You need to understand that each role requires some specific skills and personality traits and that’s why some people are in Sales, Marketing, Management, Technology Leadership and so on. They all have their own place and I believe that is what they always wanted to be.

But at least we need to try what we want to become, after knowing what we want. We need to start working on those skills, whether technical or non-technical. Be aware that each role in the industry expects some different level of technical knowledge and different personality and behavioral traits in a candidate. This is how people are offered positions like a Dev, Lead, Architect, Project Manager and so on. I highly recommend a proper road map for your desired career path.

Invest into Learning 

Investment in learning gives the highest return, not always in terms of salary but how people look at you and what perception they have of you. Every year I spend a good amount of money on books, courses, certificates, conferences and so on and many other things that keep me polished, sharp and competitive with the latest industry trends in my area of technology and career aspirations.

My latest accomplishment was the TOGAF Certified Architect level. This certification exam itself costs anywhere between US $495 – $640. What I want to share is that even after having so many Microsoft and other certificates I didn’t stop. Well, this is my personal thing and perhaps someone will find motivation from it. That’s’ all.

Apply your learning and skills 

After you have learned what the industry seeks in a candidate of your desired career goal then look for such opportunities to apply those skills. For example, a tech lead role demands the following:

  1. Participate in technical discussion with client and onsite manager
  2. Perform code review and resolve the team’s technical queries.

Now, if you are just a developer then start learning these things and see if you can either shadow or pair with your lead or silently observe how someone is doing it. Then look for the opportunity to do this by yourself. Make sure you don’t make a mess of a client call, so take it slowly.

Set Targets

You need to be a goal-oriented person, so set targets for yourself and ensure you are working on those goals, for example:

  1. In the next 30 days I will learn to communicate in English.
  2. In the next 15 days I will learn to kick off client calls.
  3. In the next 30 days I will make a sample application using MVC concepts.
  4. In the next 60 days, I will apply for jobs and see the response from companies/recruiters.

So, now you have a plan but remember “Plans won’t work until you work on the Plan”.

Don’t seek comfort

Sometimes, people think my job is all good and I am all set to be here as long as I want; you feel like you have just settled in. My last job was for 8.7 years in the same company. But I made sure that I kept moving and I made quite a shift in the organization that required similar efforts in terms of learning, applying for a job and being interviewed. I made my own way and made progress towards my career goals.So if you really interested in getting promoted and receive new shiny titles on your promotion letters and experience letters and so on then you must work hard, regardless of whether you are seeking that change within or outside the organization.

So always be restless, seek knowledge and motivation to get closer to your career goals and keep learning.

Best Wishes.