Introducing Visual C .NET


Introducing Visual C# .NET

As you browse the Microsoft Visual Studio .NET documentation, Microsoft s MSDN Web site, or even Fujitsu s NetCOBOL for .NET sample applications, you will often come across sample applications written in Visual C# .NET. Typically, you will see this language s name abbreviated down to just C# (pronounced "C sharp"). Arguably, C# is an improved addition to the "C" family of languages.

Tip  

At the end of this appendix, I have included two references to Web sites that offer a free C#-to-VB .NET translation service. You may find this type of service to be helpful during the early stages of your C# learning experience.

In this section, I cover some of the basic syntax rules of C#. At the end of this appendix, you will find several references in the "To Learn More" section that you can use to further explore the C# language.

Note  

As I mentioned in Chapter 5, the C# language is one of the available language choices bundled with most of the Visual Studio .NET (VS .NET) editions.

Coming from a COBOL/mainframe background, you are likely to notice two characteristics of C# first:

  • The C# language uses punctuation symbols, bracket symbols {}, and trailing semicolons (;).

  • The C# language is on the opposite end of the verboseness spectrum.

Let s take closer look at these two C# characteristics.

Bracket Symbols and Semicolons

The first time you look at C# code, the use of punctuation symbols may look strange. As strange as the use of punctuation symbols first appears to be, however, their use will actually be the first thing that a COBOL developer will find to be the most familiar. Once you realize that the punctuation symbols are simply defining the scope for each significant code instruction/section, you will quickly be reminded of COBOL scope terminators.

I was always a fan of COBOL scope terminators. I was one of the mainframe developers who quickly adapted to the COBOL scope terminators as they were introduced in the COBOL ISO/ANSI 85 standard. I recall going through my mainframe COBOL programs happily replacing periods (.) with scope terminators.

I recall looking for conditional statements (e.g., IF, EVALUATE, PERFORM, and so on), arithmetic statements (e.g., ADD, COMPUTE, DIVIDE, and so on), input/ output statements (e.g., READ, DELETE, START, and so on), and other statements (e.g., STRING, CALL, and so on). I left no stone unturned. I updated my mainframe COBOL programs with scope terminators everywhere possible. I added END-IF, END-EVALUATE, END-COMPUTE, END-READ, and END-STRING statements like you would not believe.

As you know, the removal of the periods from most COBOL code routines meant fewer coding bugs when code blocks were moved around. It meant that you could easily nest code statements and use inline techniques, cutting down on the "Go To/Branching" code styles. Yes, I quickly fell in love with COBOL scope termi nators and the COBOL ISO/ANSI 85 standard at that time. The fact that one COBOL period (.) was still required to "terminate the scope" of most COBOL sections was something I learned to live with.

Now you have C# using bracket symbols. The C# open bracket symbol ({) begins scope. Of course, the C# close bracket symbol (}) ends scope. In C# code, the trailing semicolon (;) is closely analogous to the COBOL period (.).

Are you ready to look at some C# code? Great! Using C# as my language choice and the VS .NET Console Application project template, I ve created a simple console application (MyFirstCSharpApplication). Listing B-1 shows a C# code snippet taken from this sample application.

Listing B-1: Code Snippet from the MyFirstCSharpApplication Sample Application
start example
 using System;       /// <summary>       /// This is my first C# Application. Coding in C# is easy.       /// </summary> namespace MyFirstCSharpApplication  {       /// <remarks>The use of three slashes ("///") denotes        /// the use of C#'s XML Documentation feature.        /// Notice that this entire comment block appears inside of an XML       /// element called "remarks". There are other XML elements that you        /// can use (e.g. summary, example, etc.).        /// You can display these XML Documentation blocks by       /// navigating to the VS.NET Main Toolbar, clicking Tools and then clicking       /// the "Build Comment Web Pages" menu option.        /// After building the Comment Web Page you can save the page        /// as part of the applications documentation.       /// </remarks>       class Class1       {            /// <summary>            /// The main entry point for the application.            /// </summary>            [STAThread]            static void Main(string[] args)            {            // Use two slash symbols ("//") for a single line comment            /* Optionally, you can create a multi-line comment block             * by using a single slash followed by an asterisk ("/*").            * The end the comment block, use an asterisk followed by a slash            */                 Console.WriteLine("Hello, .NET World.");                 Console.WriteLine("I cannot believe how simple C# is!");                 Console.WriteLine("Press Enter to Exit.");                 Console.ReadLine();            }       }  } 
end example
 
Note  

The code used in this portion of the sample application is based on the sample applications (COBOL .NET and VB .NET) originally built in Chapter 5.

Looking at the sample application in Listing B-1, you will notice the use of the trailing semicolon (;). The C# using statement, as well as the Console.Writeline and Console.Readline method statements require the trailing semicolon as a statement terminator.

Note  

When the MyFirstCSharpApplication sample application is run, two lines are displayed in a console window. Pressing the Enter key will end the application and close the console window.

Additionally, you will notice that there are three pairs of bracket symbols used in the sample application. A pair of bracket symbols is recognized as one open bracket symbol ({) and one close bracket symbol (}). In the sample application, the first bracket symbol pair is used to define the scope of the MyFirstCSharpApplication namespace. The second bracket symbol pair is used for the Class1 class. The last bracket symbol pair is used to define the scope of the Main subprocedure.

Tip  

I have added comments in the C# code in Listing B-1 to introduce the C# XML documentation feature. Additional comments in the code sample explain the syntax used for normal inline comments.

Let s take a look at more C# code.

C#: A Terse Syntax

As previously mentioned, it s reasonable to recognize C# s syntax as being terse. The degree to which you agree with this observation will depend on your back ground. If you ve only coded COBOL programs on the mainframe, you might consider C# very terse. In fact, you might even look at VB .NET as less than verbose. On the other hand, if you re one of those mainframe developers who has coded using the assembler language, the slight terseness of the C# language syntax will hardly be apparent.

Note  

You can decide for yourself if C# is that terse or not. Frankly, you may not even care. Just know that there are those who spend hours debating this point.

I ve added some code ( specifically , the procedures DefineDataTypesSample and LogicSample) to the sample C# application to help demonstrate the essence of C# code. The additional code that I ve added in MyFirstCSharpApplication is based on the (COBOL .NET and VB .NET) samples originally built for Chapter 6. I encourage you to refer back to the sample applications in Chapter 6 for line-by-line , language-to-language code comparisons.

Take a look at the code snippet in Listing B-2.

Listing B-2: Code Snippet from MyFirstCSharpApplication Showing the Procedures DefineDataTypesSample and LogicSample
start example
 using System;  . . . namespace MyFirstCSharpApplication  { . . .       class Class1       {       . . .            static void Main(string[] args)            {            . . .       //Execute Procedures                 DefineDataTypesSample();                 LogicSample();                    Console.WriteLine("Press Enter to Exit.");                 Console.ReadLine();            . . .          }          static void DefineDataTypesSample()          {       //Declare Data Items using C# Data Types                 short MyFirstNumberCsharp;                 int MySecondNumberCsharp;                 double MyThirdNumberCsharp;           //Declare Data Items using Native .NET Data Types            System.Int16 MyFirstNumberNative;            System.Int32 MySecondNumberNative;            System.Double MyThirdNumberNative;           //Place a numeric literal in Data Item            MyFirstNumberCsharp = 32767;            MySecondNumberCsharp = 32767;            MyThirdNumberCsharp = 32767;                MyFirstNumberNative = 32767;            MySecondNumberNative = 32767;            MyThirdNumberNative = 32767;         //Write out contents of each variable             Console.WriteLine("MyFirstNumberCsharp= {0}",                  MyFirstNumberCsharp);            Console.WriteLine("MySecondNumberCsharp= {0}",                  MySecondNumberCsharp);            Console.WriteLine("MyThirdNumberCsharp= {0}",                  MyThirdNumberCsharp);            Console.WriteLine("MyFirstNumberNative= {0}",                  MyFirstNumberNative);            Console.WriteLine("MySecondNumberNative= {0}",                  MySecondNumberNative);            Console.WriteLine("MyThirdNumberNative= {0}",                  MyThirdNumberNative);       }       static void LogicSample()       {  //*** Declare Data Items using .NET Data Types            System.String MYString;            System.Int32 MYInteger;            System.Boolean MYBoolean = false;            System.DateTime systemDate;      //*** Declare Data Items with C# Data Types            int MyIndex = 0;            int MySecondIndex;            int MyAccum = 0;            bool MyFlag = false;            string MyFixedLengthString;      //*** Demonstrate creation of String Array             string[] MonthValues =              {"January", "February", "March",                 "April", "May", "June",             "July", "August", "September",                  "October", "November", "December"};      //*** Demonstrate Intrinsic Function accessing System Date            systemDate = System.DateTime.Now;                 Console.WriteLine("Today is {0}" ,                   systemDate.ToShortDateString());      //*** Demonstrate Booleans, Constants, and Conditional/Computational Logic              do               {                   MyIndex += 1;                   if (MyIndex > 12)                   {                         MYBoolean = true;                         MyFlag = MYBoolean;                   }             } while (MyFlag != true);                if (MyFlag == true)             {            MYString = "The Boolean is now set to TRUE";            MyFixedLengthString = MYString;            Console.WriteLine(MyFixedLengthString);             }      //*** Demonstrate usage of Conditional and Computational Logic       for (MySecondIndex = 1; MySecondIndex <= MyIndex; MySecondIndex++)       {            MyAccum = MySecondIndex += 1;       }        MYInteger = MyAccum;      //*** Demonstrate Intrinsic Functions, Conditional/Computational Logic                MyIndex = 1;            MyFixedLengthString = String.Empty;            for (int x = 0; x <= 11; x++)            {                   switch (MonthValues[x])                    {                         case "December":                         case "January":                         case "February":                              Console.WriteLine                              (string.Concat(MonthValues[x],                                     " is ","Winter"));                               break;                         case "March":                         case "April":                         case "May":                               Console.WriteLine                               (string.Concat(MonthValues[x],                                      " is ","Spring"));                                break;                    case "June":                    case "July":                    case "August":                          Console.WriteLine                           (string.Concat(MonthValues[x],                                   " is ","Summer"));                          break;                    case "September":                    case "October":                    case "November":                          Console.WriteLine                          (string.Concat(MonthValues[x],                                   " is ","Autumn"));                          break;                    default:                             Console.WriteLine                                      ("A logic exception");                          break;              }           }        }     }  } 
end example
 

So, what do you think? Does C# deserve its "terse" syntax reputation? Perhaps.

Please take a moment to read through the code snippet in Listing B-2. As men tioned earlier, the C# implementation mimics that of Chapter 6 s sample (COBOL .NET and VB .NET) applications. Keep this in mind. If you were to do a line-by-line, language-to-language comparison (comparing this C# sample application with the sample applications coded for Chapter 6), you would observe at least the fol lowing differences:

  • C# is case sensitive. All C# reserved words are lowercase.

  • C# has new operators for equals (==) and not equals (!=) comparisons.

  • C# uses a statement called switch to implement a case logic feature.

  • C# has a jump statement specified as either break or continue.

  • C# has loop logic features (e.g., for , do/while , and so on).

  • C# has a unique, three-part parameter syntax for its looping for statement.

  • C# has an increment operator [1] (++) that increments its operand by 1.

  • C# has a decrement operator (--) that decrements its operand by 1.

  • C# uses square brackets [] for arrays instead of parentheses ().

  • C# allows intrinsic and alias named types (e.g., int versus System.Int32 ).

  • C# introduces other access modifiers ( static void versus Shared Sub ).

  • C# uses the word "void" to describe methods that do not return values.

You may have made other observations noting those C# syntax rules that are either familiar or new. As you further explore C#, experimenting with its powerful feature set, you will certainly accumulate more observations. Here are a few addi tional points that may be of interest to you:

  • C# creates an application icon (app.ico) automatically by default. You will notice this file in the VS .NET Solution Explorer. The project property pages [2] expose an option to use the application icon file.

  • C# will warn you if you declare a variable but fail to include code that actually uses the variable.

  • C# does not use the word "NEW" for its class constructor method. Instead, the C# constructor is recognized as a method that has exactly the same name as the class itself.

  • C# uses square brackets for its attribute syntax (e.g., [STAThread] ). VB .NET uses the greater-than (>) and less-than (<) symbols.

  • C# uses the colon (:) to indicate that one class is inheriting another (e.g., myderivedclassname : mybaseclassname ) and/or that one class is implementing an interface.

  • C# introduces the ref and out parameters to use when passing variable values into a called method. Using the ref parameter requires the calling program to initialize the variable before calling the method and passing the variable value.

  • C# offers a foreach statement as an alternative to implement looping logic.

  • C# has a unique syntax for explicit type casting. You do this by first placing the desired type inside parentheses. Immediately following the close parenthesis, you then code the targeted class/method/type.

  • C# program files use ".cs" as a suffix. As you know, COBOL .NET uses ".cob" and VB .NET uses ".vb".

    Caution  

    The asterisk (*) in C# code has two uses. Usually, you will use it when you want to multiply two values in a typical arithmetic expression. Although it is not advisable, [3] the other use for the asterisk is to create a pointer that stores address locations. (Usually the ampersand [&] operator is used to provide the address value.) The C# coding convention directs that code blocks using address pointers should be marked unsafe . The use of address pointers is considered unsafe due to the GC s inability to collect pointers that exist on the heap. Be sure that when you use the asterisk, you are using it for multiplication.

Obviously, these observations deserve much more explanation. I ve included them here to give you a general idea of what to expect coming from COBOL .NET or VB .NET heading into C#. Consider taking advantage of the references at the end of this appendix in the "To Learn More" section. They should point you in the right direction.

Tip  

Consider using the ILDASM.exe command-line tool to view the assembly MSIL for the MyFirstCSharpApplication sample application. This will provide to you a lower-level perspective ”a chance to better understand the C# implementation.

To wrap up this appendix s discussion about C#, I thought it would be inter esting to explore one additional side of C#. I have heard rumor that the "C# language looks like Java language syntax." Just for fun, let s take a look at how true that statement actually is.

C# Looks Like Java

I removed a Java textbook (which is based on Java 2, JDK 1.2) from my book shelf. I purchased this book a couple of years ago and never read it. Java is a lan guage that I have yet to code in. Now I sensed a good excuse to finally get my hands dirty. I wanted to know exactly what the Java language syntax looked like from the original source. After blowing the dust off my Java textbook, I browsed through its chapters and noticed the following:

  • Java ( also ) uses the bracket symbols {} for logic block definition.

  • Java ( also ) uses the semicolon (;) to terminate statements.

  • Java ( also ) uses simple variable declaration syntax (e.g., int myint; ).

That was certainly enough to capture my interest. I refilled my coffee cup and decided to read my Java textbook from cover to cover. I made the following obser vations during that enjoyable read:

  • Java ( also ) is case sensitive. All Java reserved words are ( also ) lowercase.

  • Java ( also ) has unique operators for equals (==) and not equals (!=) comparisons.

  • Java ( also ) uses a statement called swtch to implement a case logic feature.

  • Java ( also ) has a jump statement specified as either break or continue.

  • Java ( also ) has loop logic features (e.g., for , do/while , and so on).

  • Java ( also ) has a unique, three-part parameter syntax for its looping for statement.

  • Java ( also ) has an increment operator (++) that increments its operand by 1.

  • Java ( also ) has a decrement operator (--) that decrement s its operand by 1.

  • Java ( also ) uses two forward slashes (//) for comment lines.

  • Java ( also ) uses square brackets [] for arrays instead of parentheses.

  • Java ( also ) introduces other access modifiers ( static void versus Shared Sub ).

  • Java ( also ) uses the word "void" to describe methods that do not return values.

Interesting, right? Each Java language syntax observation should remind you of the observations I made earlier during the C# discussion. Suffice it to say that there is merit to the rumors stating that C# was created using Java language syntax. Just in case you are really curious , here are two more Java observations:

  • Java ( also ) does not use the word "NEW" for its class constructor method. Instead, the Java constructor is ( also ) recognized as a method that has exactly the same name as the class itself.

  • Java ( also ) has a unique syntax for explicit type casting. You do this by first placing the desired type inside parentheses. Immediately following the close parenthesis, you then code the targeted class/method/type.

As you will see in the next section, the other .NET "sharp" language, J#, con tinues in the same direction of looking like Java. However, in the case of J#, it is not a rumor. Microsoft actually states [4] that J# "integrates the Java language syntax into the Visual Studio .NET shell."

[1] Notice that the (++) operator is used in the for loop statement.

[2] C# and VB .NET expose this option on the project property pages. According to Fujitsu s documentation, you can use the command-line compile option cobolc /win32icon:app.ico/ main:Main /out:yourprogramname.exe program1.cob when you want to include an application icon file in your COBOL .NET application.

[3] Not advisable? One of the reasons for using .NET in the first place is to take advantage of the CLR and GC features. Once you start messing around with coding techniques that get around the protection provided by the CLR, you are asking for trouble. The fact that Microsoft has labeled this feature "unsafe" should be warning enough.

[4] After you install the J# product, take a look at the document located at <your installed hard drive> :\Program Files\Common Files\Microsoft Visual J# .NET Setup\ VJSharpRME1033.htm.




COBOL and Visual Basic on .NET
COBOL and Visual Basic on .NET: A Guide for the Reformed Mainframe Programmer
ISBN: 1590590481
EAN: 2147483647
Year: 2003
Pages: 204

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net