1 / 58

Odds and Ends

From Debugging to Data Conversion Operations. Odds and Ends. Collapsing Code. #region … #endregion. Code Outlining. Code files may contain definitions for one or more classes , structures , interfaces , or other code entities

grayc
Télécharger la présentation

Odds and Ends

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. From Debugging to Data Conversion Operations Odds and Ends Odds and Ends

  2. Collapsing Code #region … #endregion Odds and Ends

  3. Code Outlining • Code files may contain definitions for one or more classes, structures, interfaces, or other code entities • The files may become quite large, ranging into the hundreds or thousands of lines of code • When they do become this long, programmers often find it tedious to “find” or “navigate” to the right place in the file on which to work • Moving back and forth between locations can become tedious • For example, moving between the definition of an item and a place at which it is referenced may involve scrolling hundreds or thousands of lines Odds and Ends

  4. Code Outlining • Visual Studio provides a number of features that can help navigation in a large source file • Visual Studio allows you to bookmark individual lines of code Can jump to previous or next bookmark Bookmark Odds and Ends

  5. Code Outlining • Another feature that aids developers in navigating large code files is code outlining • Regions of code may be designated • Each region maybe collapsed into a singleline in the code editor • Collapsed regionsmay be expanded to reveal their detail whenever the detail is needed • Some regions are “automatically” designated for you including • Method definitions • XML comment blocks • Classes • Namespaces • and more Odds and Ends

  6. Code Outlining Region designators Region designators Odds and Ends

  7. Code Outlining • Clicking on one of the minus signs will collapse the associatedregion and replace the minus with a plus (for later expansion) Note that the namespace and class may also be collapsed Each collapsed region becomes a single line Odds and Ends

  8. Designating Other Regions • The developer may use #region and #endregionpreprocessor directives to mark the beginning and end of a region that is not automatically so designated by Visual Studio • For example, in a large class, there may be several overloaded constructor methods (the String class has 8 overloaded constructor methods) • One may use the #region … #endregiondirectives to designate all of them as one large region • One can then collapse or expandallconstructors at once Odds and Ends

  9. #region … #endregion • The syntax of these preprocessor commands is #region Title Phrase . . . #endregion • The #region and #endregion commands must be paired • Regions may be nested but notoverlapping • The Title Phrase will be displayed when the region is collapsed • One is not limited to using regions that correspond to large blocks of code such as methods or classes • One may use these commands anywhere within reason – including turning a logical segment of a method into its own region • One may use the Surrounds With … capability discussed earlier to embed a selected existing segment of code with #region … #endregion Odds and Ends

  10. Example Three new regions added, each of which has two or three regions already collapsed inside it Can be collapsed to this small segment Odds and Ends

  11. Regions • It is usually considered to be good practice to use nested regions in a reasonable way to allow developers to • See the big picture when all are collapsed • Expand only what we need to work on now • Obviously, this can be taken too far … • One doesn’t want to nest so deeply one has to spend excessive time collapsing and expanding • Don’t create a region for each line of code or anything nearly that excessive Odds and Ends

  12. Reference Highlighter When one instance of an identifier is selected … … others are highlighted too Odds and Ends

  13. Named and Optional Parameters in C# 4.0 New in Visual Studio 2010, .NET 4.0 Odds and Ends

  14. Passing Parameters • When passing parameters to a method, one must usually pass all of them in exactly the same order as specified by the method definition • When the number of parameters is large, this requirement is a source of errors, and it is tedious to the developer – even though Intellisense is great helper Odds and Ends

  15. Named Parameters • Named parameters allow you to call a method by specifying which argument in a method call refers to which formal parameter. Example: public static int Subtract (int left, int right) { return (left – right); } • All three of these calls are equivalent: result = Subtract (7, 5); // left is 7, right is 5 result = Subtract (left: 7, right: 5); // left and right result = Subtract (right: 5, left: 7);// are clearly designated • If you don't specify a name, the normal order is used • Parameters can be specified by name in any order Odds and Ends

  16. Optional Parameters • Optional parameters enable you to specify a default value for a parameter in a method • Omitting a parameter with a defaultvalue in a methodcall results in the defaultvalue being used • Providing a value for a defaultparameter when calling a method overrides the defaultvalue • Any parameters that have default values must be at the right end of the argument list • The first parameter with a default value must follow all parameters that do not have default values • The default values for optional parameters must be compile-time constants • One may not create new objects, use static variables, or use method returns as a default parameter value Odds and Ends

  17. Optional Parameters • You specify a defaultvalue for an optionalparameter by declaring its value in the method definition • For example, one might update the Subtract method to have a default behavior of subtracting 1 public static int Subtract (int left, int right = 1) { return left - right; } • The following call decrements count count = Subtract (count); • Optional and named parameters work together to provide a richer calling sequence. Callers can specify none, any, or all of the optional parameters by name. Odds and Ends

  18. Example Note default parameters: customer, description, and p If description is null, set Description property to emptystring – else set it to description Odds and Ends

  19. Type conversion Casting and conversion methods Odds and Ends

  20. Data Types and Conversions • Two items may be of compatible or incompatible types • An integer is compatible with a double because both are numeric and an integer can be converted into a double without loss of data • “Ken” is a string that cannot be converted into a double in any intuitive way; the two types are not compatible Odds and Ends

  21. Implicit/Explicit Conversions • For compatible types, there may or may not be implicitconversions from one type to another • Depends on whether the compiler knows how to make the conversion • Depends on whether there is a potential for loss of data • Example, the following produces an implicit conversion from the integer on the right-hand-side to the double on the left. No data loss is possible. • If there is a possibility of data loss, an explicit operation is required: the programmer must ask for a conversion Odds and Ends

  22. Explicit Conversions • One way to request a conversion is to cast between compatible types • A cast operationmaybean acknowledgement of possible data loss and “it is OK with me” • May be a statement that “I know the object is really of this other type and it is OK to treat it that way” Casting as string means we can use stringmethods and stringproperties Odds and Ends

  23. Casting • The form for requesting a cast is (new type) item • Itemmust be of a type compatible with the requested type so that a conversion is possible • If, at run time, it is determined that one cannot make the requested conversion, an exception is thrown • For example, an array of Object may contain any types of items such as strings, doubles, PigLatin objects, Employee objects, etc. If we try to cast and use one of the items as a string, that will work only if that particular item is a string rather than one of the other types of items; it will fail for a double or an Employee object. Odds and Ends

  24. Casting • Casting is a “temporary” operation • It does not permanently change the type of data being cast • Internally, C# makes a temporary variable of the convertedtype and converts the item being cast into the temporary variable • The value in the temporary is used for the rest of the operation – at which time it ceases to exist Odds and Ends

  25. Casting • An object of a derived class isaobject of its base class (an Employee isa Person), but the reverse is not true (some Persons are notEmployees) • Castingis required when an object is defined to be of a base type, but it actually refers to a derivedtype of object • To use the methods and properties of the derivedtype, one must first cast the object to that type • The casting is OK because the object really is of the derived type • See the Object array exampleseveral slides back. Odds and Ends

  26. Using “as” to Cast to a Different Type

  27. The as Keyword • The as operator provides a type of casting operation • Ordinary cast operations throw an exception if the cast is not valid • If the conversion is not possible, as returns null instead of raising an exception Use of the as keyword Check to see if the as cast was successful

  28. Another as Example Trying to cast as a string. It works on those items that are strings, but returns null otherwise Was the as cast successful? Results

  29. Other Explicit Conversions • Casting can only be used in cases in which the types are compatible and the compiler knows how to do the conversion • There are cases in which a conversion is needed but a cast cannot be done • Example: To input a salary from the keyboard, one may use Console.ReadLine ( ); • This inputs a string, hopefully the string representation of a number such as “123456.78” • We cannot cast this string as a Decimal or a Double however since they are incompatible types Odds and Ends

  30. Explicit Conversions • ExplicitConversions that cannot be done by casting require the programmer to invoke a method to do the conversion • Example 1: char [ ] cArray = strVowels.ToCharArray ( ); is used to convert a string into an array of characters • Example 2: string strLine = MyTrip.ToString ( ); may convert a decimal MilesPerGallon object to a string • Any class may have methods that convert objects of some other type to its type or vice versa Odds and Ends

  31. String to Numeric Conversions • The standard .NET numeric data types such as Int32, Double, Decimal, and so forth have static methods named Parse • Each takes a string argument – the string representation of a number of that type • Method converts the value argument to the appropriate numerictype • Example: • Throws exception if the stringcannot be parsed as the specified type Odds and Ends

  32. String Conversions • To avoid exceptions in cases where the Parse argument is invalid, use TryParse public static bool TryParse ( string s,outdoubleresult ) • Works similar to Parse, but returns true or false to indicate whether it was successful • If it was successful, the secondargument has the result in it out specifies that the argument need not have a value going in because the method will assign one to be returned Odds and Ends

  33. Example: String Conversions Odds and Ends

  34. Conversion between numeric types • Conversion from one numeric type to another is typically done implicitly (if appropriate) or by casting (if needed) • However, .NET numeric structs have conversion methods • Example: Decimal has the following methods Odds and Ends

  35. Visual Studio Debugger Elementary Debugging Tools in VS Odds and Ends

  36. Debugging • Three types of errors that developers see frequently • Syntax errors: compile time issues • Execution time program crashes • Program logic errors – program runs successfully but does not produce desired results • The debugger is a setoftools that can be used to • monitora running program • inspectobjectvaluesduringexecution • collectexecutionhistory so that at any point we know how we got to that point • and more • The debugger may be used to help the developer gather information need to deal with runtime errors, not syntax errors Odds and Ends

  37. VS Debugger • The debugger can be used for some quite sophisticated debugging situations such as • Distributed solutions with parts running on separatecomputers in diverselocations • Parallelalgorithms running on multipleprocessors within a singlecomputer (or supercomputer) • Debug suspected bugs within VS itself • Monitor memory, registers, and other hardware features • The discussion here is limited to much more commondebuggingscenarios Odds and Ends

  38. “Watching Code Run” • To use the debugger’s features, execution must be started with “Start Debugging” Start Debugging Odds and Ends

  39. Code Breakpoints • In debug mode, one may pause program execution at a specified point called a breakpoint • Once paused, one can inspect the current values of variables, properties, and so forth • One may stepthroughsubsequentinstructionsoneat a time • One may inspectprogramhistory to determine what execution path led to this point (a method may have been called from many different places, for example, and it may be helpful to where it was called this time) • One may even modify something and continue Odds and Ends

  40. Breakpoints • The easiest way to set a breakpointon or off is to click in the margin to the left of the line number Click here to toggle the breakpoint on/off Odds and Ends

  41. Breakpoints • One may set as many breakpoints as desired • When execution reaches a breakpoint • Execution pauses at that line (it hasnot been executed - yet) • Program runs fullspeed up to the first breakpoint • At the breakpoint, one may inspectthevaluesofobjects as they are at that point in the program • Easiest way to do this is to hover over the object with the cursor, and a tool tip will reveal the value • For a complexobject such as an array, one may have to expand the tool tip to see the details Odds and Ends

  42. Yellow arrow marks place where execution is paused Example Tooltip shows current value of strFrom – line 20 has not been executed yet. Hovering over a different variable shows its value – as of line 20 Odds and Ends

  43. Debugging Toolbar Stop debugging and resume editing Continue to next breakpoint Restart the debugging session Highlight next instruction to be executed Odds and Ends

  44. Debugging Toolbar, cont. Step Into – a method one is trying to execute on this line – to watch it run, a line at a time Step over – execute the line at full speed but pause on the following line Step Out Of – execute rest of this method and return to the calling method; most useful when in code you did not write Display a value in hexadecimal so one can see its internal form Odds and Ends

  45. Step Through Code and Watch it Run • Execution point moves to next line and result of the executed line can be observed Odds and Ends

  46. Call Stack • The Call Stack shows the program’s execution history • For example: • This shows we got to the MilesPerGallon constructor from a call to it on Line 17 of Main Where we are now Where that method was called Odds and Ends

  47. Locals Watch • The Locals Watch window shows values of all locally defined variables at the point in time where execution is temporarily frozen • Stepping through allows one to watch these values change Odds and Ends

  48. Autos Watch • The Autos Watch Window shows information similar to the Locals Watch Window Odds and Ends

  49. Disassembly • One can even see the pseudo assembly language code that has been generated … Odds and Ends

  50. More On Breakpoints • Right-clicking on a breakpoint brings up a context menu that allows one to make breakpoints work in more sophisticated ways Odds and Ends

More Related