Top ten traps in C# for C++ programmers: Jesse liberty... liberty assocs. (Monograph).In a recent article I mentioned that the syntax of C# is very similar to that of C++, and that the difficult part of the transition was not the language itself, but getting comfortable with the managed enviromnent of .NET and understanding the extensive .NET Framework-. I've begun to compile a list of the syntax differences that do exist between C++ and C# (the list is available on my Web site. Click on Books navigate to Programming C# and click on the FAO FAO, n See Food and Agriculture Organization. ). As you might expect, most of the syntactic changes To the extent that a language is vocabulary cast into the mould of a particular syntax and that the basic structure of the sentence is held together by functional items, with the lexical items filling in the blanks, syntactic change is no doubt what modifies most deeply the physiognomy of are small and nearly trivial. There are a few changes that are potential traps for the unwary C++ programmer, however, and this article will focus on the ten most dangerous. Trap #1: Nondeterministic finalization Writing the table of contents (TOC) on a recordable CD or DVD disc. The finalization process ensures that the disc can be played back on most CD and DVD players. See disc-at-once. and the C# destructor (programming) destructor - A function provided by a class in C++ and some other object-oriented languages to delete an object, the inverse of a constructor. . Almost certainly, the biggest difference in C# for most C++ programmers will be garbage collection A software routine that searches memory for areas of inactive data and instructions in order to reclaim that space for the general memory pool (the heap). Operating systems may or may not provide this feature. . While this means you no longer have to worry about memory leaks A condition caused by a program that does not free up the extra memory it allocates. In programming languages, such as C/C++, the programmer can dynamically allocate additional memory to hold data and variables that are required for the moment, but not used throughout the program. and ensuring that pointers are deleted, you also give up precise control over when your objects will be destroyed. In fact, there is no explicit destructor in C#. If you do control an unmanaged resource, however, you will need to explicitly free that resource when you are done with it. Implicit control over a resource is provided with a Finalize fi·nal·ize tr.v. fi·nal·ized, fi·nal·iz·ing, fi·nal·iz·es To put into final form; complete or conclude: "They have jointly agreed ... method (called a finalizer In object-oriented programming languages that use garbage collection, a finalizer is a special method that is executed when an object is garbage collected. It is similar in function to a destructor. ), which will be called by the garbage collector when your object is destroyed. The finalizer should only release unmanaged resources that are held by your object, and should not reference other objects. Note that if you have only managed references you do not need to and should not implement the Finalize method; you want this only for handling unmanaged resources. Because there is some cost to having a finalizer, you ought to implement this only on methods that require it (that is, methods that consume valuable unmanaged resources). You must never call an objects Finalize method directly (except that you should call your base class's Finalize method in your own Finalize)., The garbage collector will call Finalize for you. C#s destructor looks, syntactically syn·tac·tic or syn·tac·ti·cal adj. Of, relating to, or conforming to the rules of syntax. [Greek suntaktikos, putting together, from suntaktos, constructed, from much like a C++ destructor, but it is totally different. The C# destructor is simply shortcut (1) In Windows, a shortcut is an icon that points to a program or data file. Shortcuts can be placed on the desktop or stored in other folders, and double clicking a shortcut is the same as double clicking the original file. for declaring a Finalize method that chains up to its base class. Thus writing:
~MyClass ()
{
// do work here
}
is identical to writing
MyClass.Finalize ()
{
// do work here
base.Finalize () ;
}
Trap #2: Finalize versus Dispose. It is not legal to call a finalizer explicitly. Your Finalize method will be called by the garbage collector. If you do handle limited 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. This interface has one method, Dispose, which will perform your cleanup. Your clients are then responsible for calling Your Dispose method explicitly. Dispose is the way for your clients to say "don't wait for Finalize to be called, do it right now." If you provide a Dispose method, you ought to stop the garbage collector from calling Finalize on your object; since the clean up will be provided explicitly. To do so, you call the static method GC. SuppressFinalize, passing this the pointer for your object. Your Finalize method can then call your Dispose method.
Thus you might write: public void Dispose()
{
// perform clean up
// tell the GC not to finalize
GC.SuppressFinalize (this);
}
public override void Finalize()
{
Dispose ();
base .Finalize ();
}
For some objects, you'd rather have your clients call Close (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 have your Close method invoke Dispose. Because you can not be certain that your client will call Dispose reliably, and because finalization is nondeterministic (you can't control when the GC will run), C# provides a Using statement which ensures that Dispose Will be called at the earliest possible time. The idiom is to declare which objects you are using, and then to create a scope for these objects with curly braces In programming, curly braces (the characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the are executed if the variable mouseDOWNinText is true. . When the close brace is reached the Dispose method will be called on the object automatically:
using System. Drawing;
class Tester
{
public static void Main()
{
using (Font the Font = new Font ("Arial", 10.0f))
{
// use theFont
} // compiler will call Dispose on theFont
Font anotherFont = new Font("Courier",12.0f);
using (anotherFont)
{
// use anotherFont
} // compiler calls Dispose on anotherFont
}
}
In the first part of this example, the Font object is created within the Using statement. When the Using statement ends, Dispose is called on the Font Object. In the second part of the example, a Font object is created outside of the Using statement. When you decide to use that font, you put it inside the Using statement and when that statement ends, once again Dispose is called. The Using statement also protects you against unanticipated exceptions. NO matter how control leaves the Using statement Dispose is called. It is as if there were an implicit try-catch-finally block. Trap #3: C# distinguishes between value types and reference types. Like C++, C# is a strongly typed strongly typed - strong typing 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 Inserted into. See embedded system. 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 (see trap #5 structs are value types as are all the intrinsic types. Trap #4: Watch out for implicit boxing. Boxing and unboxing are the processes that enable value types (e.g., 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;
//Boxing
object o = i;
// unboxing (must be explicit)
int j = (int) o;
Console.WriteLine("j: {O}", j);
}
}
If the object being unboxed is null A character that is all 0 bits. Also written as "NUL," it is the first character in the ASCII and EBCDIC data codes. In hex, it displays and prints as 00; in decimal, it may appear as a single zero in a chart of codes, but displays and prints as a blank space. 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 See object technology and object-oriented programming. 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 semantics [Gr.,=significant] in general, the study of the relationship between words and meanings. The empirical study of word meanings and sentence meanings in existing languages is a branch of linguistics; the abstract study of meaning in relation to language or . 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 An arrangement whereby commissions are made by sales managers based upon the sales made by their subordinate sales representatives. A term found in an agreement between a real estate agent and a property owner whereby the agent keeps the right to receive a commission for the sale of a virtual method must be made explicit with the override keyword. To see why this is useful, assume that a Window class is 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 class Window
{
// "
public virtual void Sort () {"}
}
In C++ the new virtual Sort method in Windows 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 he the root of virtual dispatch, that is, once C# finds a virtual method, it looks no further up the inheritance hierarchy If a new virtual Sort function is introduced into Window the run-time behavior of ListBox is unchanged. When ListBox is compiled again, however, the compiler generates a warning: "\class1.cs(54,24): warning cs0114: 'ListBox.Sort()' hides inherited member 'Window.Sort()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. To remove the warning, the programmer must indicate what he intends. He can mark the ListBox Sort method new to indicate that it is not an override of the virtual method in Window:
public class ListBox : Window
{
public new virtual void Sort() {"}
This action removes the warning. If on the other hand, the programmer does want to override the method in Window, he need only use the override keyword to make that intention explicit. Trap #7. You may not initialize To start anew, which typically involves clearing all or some part of memory or disk. in the header. Initialization in·i·tial·ize tr.v. in·i·tial·ized, in·i·tial·iz·ing, in·i·tial·iz·es Computer Science 1. To set (a starting value of a variable). 2. To prepare (a computer or a printer) for use; boot. 3. works differently in C# than it does in C++. Suppose you have a class Person with a private member variable age, and a derived class (programming) derived class - (Or "subclass") In object-oriented programming, a class that is derived from a base class by inheritance. The derived class contains all the features of the base class, but may have new features added or redefine existing features. Employee with a private member variable salaryLevel. In C++ you might initialize salaryLevel in the initialization part of the Employee constructor, like this:
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 ~ still initialize the base, the initialization f 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 semi-colon 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 e·quate v. e·quat·ed, e·quat·ing, e·quates v.tr. 1. To make equal or equivalent. 2. To reduce to a standard or an average; equalize. 3. to integer integer: see number; number theory 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 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 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 goto statement:
switch (i)
{
case 4:
CallFuncOne () ;
goto case 5;
case 5:
CallSomeFunc () ;
}
If the case statement does not 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" parameter., 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 sonic other innocuous in·noc·u·ous adj. Having no adverse effect; harmless. innocuous (i·näˈ·kyōō· 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 for words. The entire point of these variables is to pass them by reference into GetTime where they'll be changed. To solve this problem, C# provides the out parameter modifier (programming) modifier - An operation that alters the state of an object. Modifiers often have names that begin with "set" and corresponding selector functions whose names begin with "get". 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 in to 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 invocation, n a prayer requesting and inviting the presence of God. of the GetTime method: timeObject.GetTime( out theHour, out theMinute, out theSecond); www.Liberty Associates.com RELATED ARTICLE: SUPPORTING LITERATURE "C# ESSENTIALS" UPDATED FOR THE FINAL RELEASE OF C# For more than a year, Microsoft has heavily promoted C# as a language that embraces many of the best features of each of the Visual C++, Visual Basic, and Visual J++ languages and development environments. Created with web services (1) Loosely, any online service delivered over the Web. Such usage appears in articles from non-technical sources, but not in IT-oriented publications, because definition #2 below describes the correct use of the term. and applications in mind, C# was designed to combine the rapid development benefits of Visual Basic' with the power and control of C and C++. "C# Essentials' Second Edition" by Ben Albahari, Peter Drayton & Brad Merrill provides a succinct suc·cinct adj. suc·cinct·er, suc·cinct·est 1. Characterized by clear, precise expression in few words; concise and terse: a succinct reply; a succinct style. 2. but thorough overview of the language to help programmers quickly grasp the fundamentals of C# programming. The new edition of "C# Essentials" has been updated to cover the final release of the C# language. Its efficient presentation of key concepts serves as a roadmap to the online documentation for the language, while the many examples included in the book provide much needed context for would-be C# programmers. In addition to overviews of C#, the Common Language Runtime See CLR. (CLR (Common Language Runtime) The runtime engine in Microsoft's .NET platform. The CLR compiles and executes programs in Microsoft Intermediate Language (MSIL). The counterpart to the CLR for the Common Language Infrastructure (CLI), ECMA's standard version of . ), and the NET Framework Class Libraries (FCL FCL Facility (Security) Clearance FCL Full Container Load FCL Framework Class Library (Microsoft .NET) FCL Fault Current Limiter FCL Forecastle (ship's hull) ), this new edition of "C# Essentials" covers: this new edition of "C# Essentials" covers * Every C# language element and its syntax, in reference format, including new keywords. * The major C# datatypes, with code examples -Common C# programming tasks. * Interoperation with legacy Win32 APIS Apis (ā`pĭs), in Egyptian religion, sacred bull of Memphis, said to be the incarnation of Osiris or of Ptah. His worship spread throughout the Mediterranean world and was particularly important during the time of the Roman Empire. and COM components, and the use of CIC CIC circulating immune complexes. CIC Circulating immune complexes. See Immune complexes. ++ style pointers within the managed context of the CLR -Common development issues. www.oreilly.com EASING TUE Tu´e n. 1. (Zool.) The parson bird. Tue, Tues abbr (= Tuesday) → ma TRANSITION FROM VB 6 TO VB .NET IF all goes as Microsoft has planned, sometime in the next year or so more than five million (and up to eight million) Visual Basic developers will make the move to VB NET. Visual Basic is currently the most widely used programming language around, its success owing to owing to prep. Because of; on account of: I couldn't attend, owing to illness. owing to prep → debido a, por causa de its simplicity and ease of use. The new VB, that is, Visual Basic.NET See VB.NET. , is a from-the-ground-up rewrite re·write v. re·wrote , re·writ·ten , re·writ·ing, re·writes v.tr. 1. To write again, especially in a different or improved form; revise. 2. of the language that not only adds a number of new features, but also from previous versions of Visual Basic. According to according to prep. 1. As stated or indicated by; on the authority of: according to historians. 2. In keeping with: according to instructions. 3. Steven Roman, coauthor of IIVB NET Language in a Nutshell nut·shell n. The shell enclosing the meat of a nut. Idiom: in a nutshell In a few words; concisely: Just give me the facts in a nutshell. Adv. 1. " (Roman, Petrusha & Lomax, O'Reilly, [pounds sterling]24.95), sooner or later all Visual Basic programmers are going to have to wrestle with the decision to upgrade to VB.NET (Visual Basic .NET) An object-oriented programming language from Microsoft. It is the .NET version of the Visual Basic (VB) programming language. Like all .NET languages, VB.NET uses the Common Language Runtime (CLR) for program execution. VB. . VB.NET appears to offer many changes that VB programmers will welcome. In addition to being a streamlined and modernized mod·ern·ize v. mo·dern·ized, mo·dern·iz·ing, mo·dern·iz·es v.tr. To make modern in appearance, style, or character; update. v.intr. To accept or adopt modern ways, ideas, or style. language, VB.NET is fully object-oriented, with the long inclusion of class inheritance and other OOP See object-oriented programming. OOP - object-oriented programming features. "VB.NET Language in a Nutshell" goes beyond the bare details provided in the official documentation to provide the inside information that programmers will need to solve programming problems or use particular elements effectively. The book provides complete documentation for the VB.NET language, including all of the new language elements. The first part of the book focuses on the important areas of programming VB.NET, including variables and data types, an introduction to object oriented programming, .NET Framework general concepts, the .NET Framework Class Library, delegates and events, and error handling. The bulk of the book then consists of an alphabetical reference to the functions, statements, directives, objects, and object members that make up the VB.NET language. www.oreilly.com "PROGRAMMING C#" Jesse Liberty, the author of the new edition of "Programming C#", describes C# (pronounced C Sharp) as a language that draws on the lessons of the past three decades. He says: "In much the way that you can see in young children the features and personalities of their parents and grandparents grandparents npl → abuelos mpl grandparents grand npl → grands-parents mpl grandparents grand npl , you can easily see in C# the influence of Java, C++, Visual Basic, and other languages.' Announced by Microsoft more than a year ago as part of the unveiling of the NET platform, C# was designed to combine the high performance of C, the object-oriented structure of C++, the security of Java, and the rapid development of Visual Basic in a language especially for .NET development. Microsoft did a radical thing with NET," says Liberty. "Rather than starting with a language, they started with a Common Language Specification (CLS (Common Language Specification) The structure and syntax of .NET and CLI programming languages. See .NET. ). Any language that complies with the CLS is able to run on the .NET platform. What is more, if you comply with the CLS and you use only types defined by the Common Type System (CTS (1) (Clear To Send) The RS-232 signal sent from the receiving station to the transmitting station that indicates it is ready to accept data. Contrast with RTS. (2) (Common Type System) The data typing used in . ) then your object s can interoperate See interoperable. with (and derive from and be derived from) any other CLS language. That means that you can create a class in VB.NET, derive from it in C#, and then derive from that C# class back in VB.NET! To accomplish this, they created a whole new language, and then implemented that language with two syntaxes. One syntax is C# and it looks a lot like C++ and Java. The other syntax is VB.NET and it looks a lot like VB. In essence, both C# and VB.NET are the same language with different syntactic sugar Certain coding rules in a programming language that make it easier for a person to write a program. For example, in Perl, the double dot operator is used to create multiple values. Writing ('A' .. 'Z') declares a range of values from "A" to "Z. ." "Programming C#" was written for programmers who want to develop applications for the .NET platform and assumes some previous programming experience, most likely C++, Java, or VB. This new book teaches C# in a way that experienced programmers will appreciate--by grounding its applications firmly in the context of Microsoft's .NET platform and the development of desktop and Internet applications. As Liberty explains: "You learn C# specifically to create .NET applications. Pretending otherwise would miss the point of the language. This book does not consider C# in a vacuum but places the language in the context of Microsoft's .NET platform. Microsoft says it is devoting eighty percent of its research and development budget to .NET and its associated technologies--that is a few billion dollars of R&D every year. The results of this commitment are impressive, to say the least. NET is huge. Frankly, I think C# is one of the most important developments in ten years. I expect C# to become the development language of choice for Windows development, and one of the two most important languages (alongside Java) for web development." www.o'reilly.com www.libertyassociates.com Benefits Of Testing A new survey has shown that, the number of companies recognising the benefits of testing has risen from 59% (in 2000) to 95% (in 2002) The survey of UK IT directors explored attitudes towards system testing (testing) system testing - (Or "application testing") A type of testing to confirm that all code modules work as specified, and that the system as a whole performs adequately on the platform on which it will be deployed. and IT performance and showed that huge investments in e-business, CRM (Customer Relationship Management) An integrated information system that is used to plan, schedule and control the presales and postsales activities in an organization. and ERP (Enterprise Resource Planning) An integrated information system that serves all departments within an enterprise. Evolving out of the manufacturing industry, ERP implies the use of packaged software rather than proprietary software written by or for one customer. applications over recent years, and the need to measure return on investment (ROI (Return On Investment) The monetary benefits derived from having spent money on developing or revising a system. In the IT world, there are more ways to compute ROI than Carter has liver pills (and for those of you who never heard of that expression, it means a lot). ), have meant that IT directors are increasingly aware of the, importance of a test strategy. However, despite this increased awareness of the benefits of comprehensive automated testing (testing) automated testing - Software testing assisted with software tools that require no operator input, analysis, or evaluation. of all corporate IT networks and infrastructure, many companies are in the early stages of adopting thorough testing and performance management strategy Comment: This is the third year that we this research has been conducted and the results of this year's survey have shown that many businesses in the UK still appear to be taking a fingers crossed approach to ensuring the reliability and performance of their business applications. This is somewhat surprising when a major system failure or Web site crash can make headline news and have a serious impact on a company's bottom- line. However, what is encouraging is the change. in attitude from two years ago when this survey was last conducted, when levels of awareness of the benefits of testing were 59%. www.mercuryinteractive.co.uk |
|
||||||||||||||||||

Printer friendly
Cite/link
Email
Feedback
Reader Opinion