Download presentation
Presentation is loading. Please wait.
1
From Debugging to Data Conversion Operations
Odds and Ends Odds and Ends December 1, 2018
2
Collapsing Code #region … #endregion Odds and Ends December 1, 2018
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 December 1, 2018
4
Can jump to previous or next bookmark
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 December 1, 2018
5
Code Outlining Another feature that aids developers in navigating large code files is code outlining Regions of code may be designated Each region may be collapsed into a single line in the code editor Collapsed regions may 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 December 1, 2018
6
Code Outlining Region designators Region designators Odds and Ends
December 1, 2018
7
Code Outlining Clicking on one of the minus signs will collapse the associated region 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 December 1, 2018
8
Designating Other Regions
The developer may use #region and #endregion preprocessor 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 … #endregion directives to designate all of them as one large region One can then collapse or expand all constructors at once Odds and Ends December 1, 2018
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 not overlapping 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 December 1, 2018
10
Can be collapsed to this small segment
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 December 1, 2018
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 December 1, 2018
12
Reference Highlighter
When one instance of an identifier is selected … … others are highlighted too Odds and Ends December 1, 2018
13
Named and Optional Parameters in C# 4.0
New in Visual Studio 2010, .NET 4.0 Odds and Ends December 1, 2018
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 December 1, 2018
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 December 1, 2018
16
Optional Parameters Optional parameters enable you to specify a default value for a parameter in a method Omitting a parameter with a default value in a method call results in the default value being used Providing a value for a default parameter when calling a method overrides the default value 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 December 1, 2018
17
Optional Parameters You specify a default value for an optional parameter 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 December 1, 2018
18
Note default parameters: customer, description, and p
Example Note default parameters: customer, description, and p If description is null, set Description property to empty string – else set it to description Odds and Ends December 1, 2018
19
Type conversion Casting and conversion methods Odds and Ends
December 1, 2018
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 December 1, 2018
21
Implicit/Explicit Conversions
For compatible types, there may or may not be implicit conversions 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 December 1, 2018
22
Explicit Conversions One way to request a conversion is to cast between compatible types A cast operation may be an 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 string methods and string properties Odds and Ends December 1, 2018
23
Casting The form for requesting a cast is (new type) item
Item must 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 December 1, 2018
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 converted type 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 December 1, 2018
25
Casting An object of a derived class isa object of its base class (an Employee isa Person), but the reverse is not true (some Persons are not Employees) Casting is required when an object is defined to be of a base type, but it actually refers to a derived type of object To use the methods and properties of the derived type, 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 example several slides back. Odds and Ends December 1, 2018
26
Using “as” to Cast to a Different Type
27
Check to see if the as cast was successful
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
Was the as cast successful?
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 “ ” We cannot cast this string as a Decimal or a Double however since they are incompatible types Odds and Ends December 1, 2018
30
Explicit Conversions Explicit Conversions 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 December 1, 2018
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 numeric type Example: Throws exception if the string cannot be parsed as the specified type Odds and Ends December 1, 2018
32
String Conversions To avoid exceptions in cases where the Parse argument is invalid, use TryParse public static bool TryParse ( string s, out double result ) Works similar to Parse, but returns true or false to indicate whether it was successful If it was successful, the second argument 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 December 1, 2018
33
Example: String Conversions
Odds and Ends December 1, 2018
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 December 1, 2018
35
Visual Studio Debugger
Elementary Debugging Tools in VS Odds and Ends December 1, 2018
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 set of tools that can be used to monitor a running program inspect object values during execution collect execution history 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 December 1, 2018
37
VS Debugger The debugger can be used for some quite sophisticated debugging situations such as Distributed solutions with parts running on separate computers in diverse locations Parallel algorithms running on multiple processors within a single computer (or super computer) Debug suspected bugs within VS itself Monitor memory, registers, and other hardware features The discussion here is limited to much more common debugging scenarios Odds and Ends December 1, 2018
38
“Watching Code Run” To use the debugger’s features, execution must be started with “Start Debugging” Start Debugging Odds and Ends December 1, 2018
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 step through subsequent instructions one at a time One may inspect program history 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 December 1, 2018
40
Click here to toggle the breakpoint on/off
Breakpoints The easiest way to set a breakpoint on 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 December 1, 2018
41
Breakpoints One may set as many breakpoints as desired
When execution reaches a breakpoint Execution pauses at that line (it has not been executed - yet) Program runs full speed up to the first breakpoint At the breakpoint, one may inspect the values of objects 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 complex object such as an array, one may have to expand the tool tip to see the details Odds and Ends December 1, 2018
42
Example Yellow arrow marks place where execution is paused
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 December 1, 2018
43
Debugging Toolbar Continue to next breakpoint
Stop debugging and resume editing Restart the debugging session Highlight next instruction to be executed Odds and Ends December 1, 2018
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 December 1, 2018
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 December 1, 2018
46
Where that method was called
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 December 1, 2018
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 December 1, 2018
48
Autos Watch The Autos Watch Window shows information similar to the Locals Watch Window Odds and Ends December 1, 2018
49
Disassembly One can even see the pseudo assembly language code that has been generated … Odds and Ends December 1, 2018
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 December 1, 2018
51
Conditional Breakpoints
Sometimes, a breakpoint may be in a loop and you may not want to pause every time through the loop, but you do want to break on specific passes Specify a condition that determines when to break User-specified condition Odds and Ends December 1, 2018
52
Conditional Breakpoints
You may want to stop after the breakpoint is hit a certain number of times Odds and Ends December 1, 2018
53
Conditional Breakpoints
You may also specify action other than pausing when a breakpoint is hit Odds and Ends December 1, 2018
54
Intellitrace Using the techniques described so far, one may watch a program run, examining variable values as the program advances One can only go forward in execution or quit debugging after a pause One cannot go backward if the result of some previous step has been forgotten Intellitrace is a new feature of VS2010 that allows one to move backwards as well as forward Intellitrace “records” the state of the program as it executes One may “back up” and review a previously recorded state Odds and Ends December 1, 2018
55
Using Intellitrace Only available for x86 target output
To set the target, right click on project and choose Properties from the context menu On the Build tab, choose x86 CPU target Choose x86 Odds and Ends December 1, 2018
56
Open the Intellitrace Window
Using Intellitrace Open the Intellitrace Window Odds and Ends December 1, 2018
57
Intellitrace Event Window
Hit breakpoint line 32 in Main Stepped to next line Entered ctor on line 54 Stepping one line at a time … at line 60 now Now we can click on any line here to review the state at that point in the execution Odds and Ends December 1, 2018
58
Current line where execute is paused
Icons Intellitrace Icons Current line where execute is paused Odds and Ends December 1, 2018
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.