SlideShare une entreprise Scribd logo
1  sur  7
A-PDF WORD TO PDF DEMO: Purchase from www.A-PDF.com to remove the watermark




              B     E     G     I     N       N       E      R    S   ’   S

              C#              TUTORIAL
              1. A S I M P L E W E L C O M E P R O G R A M




                                (Centre for Knowledge Transfer)




                                              1
This lesson will get you started with C# by introducing a few very simple programs. Here are the objectives of
this lesson:


          Understand the basic structure of a C# program.
          Obtain a basic familiarization of what a "Namespace" is.
          Obtain a basic understanding of what a Class is.
          Learn what a Main method does.
          Learn how to obtain command-line input.
          Learn about console input/output (I/O).



Listing 1-1. A Simple Welcome Program: Welcome.cs
// Namespace Declaration
using System;

// Program start class
class WelcomeCSS
{
   // Main begins program execution.
   public static void Main()
   {
      // Write to console
      Console.WriteLine("Welcome to the C# Station Tutorial!");
   }
}


The program in Listing 1-1 has 4 primary elements, a namespace declaration, a class, a
Main method, and a program statement. It can be compiled with the following command
line:

    csc Welcome.cs

This produces a file named Welcome.exe, which can then be

executed. Other programs can be compiled similarly by substituting their file
name instead of Welcome.cs. For more help about command line options,
type "csc -help" on the command line. The file name and the class name can
be totally different.


Note for VS.NET Users: The screen will run and close quickly when launching this program from
Visual Studio .NET. To prevent this add the following code as the last line in the Main method:

// keep screen from going away
// when run from VS.NET
Console.ReadLine();


The namespace declaration indicates that you are referencing the System
namespace. Namespaces contain groups of code that can be called upon by
C# programs. With the using System; declaration, you are telling your
program that it can reference the code in the System namespace without




                                                          2
pre-pending the word System to every reference. I'll discuss this in more detail in a later lesson, dedicated
specifically to namespaces.

The class declaration, class WelcomeCSS, contains the data and method
definitions that your program uses to execute. A class is one of a few
different types of elements your program can use to describe objects, such
as interfaces and structures, which will be discussed in more detail in a later
lesson. This particular class has no data, but it does have one method. This
method defines the behavior of this class (or what it is capable of doing).


The one method within the WelcomeCSS class tells what this class will do
when executed. The method name, Main, is reserved for the starting point of
a program. Before the word Main is a static modifier. The static modifier
explains that this method works in this specific class only, rather than an
instance of the class. This is necessary, because when a program begins,
no object instances exist. Classes, objects, and instances will be covered in
more detail in a later lesson.
Every method must have a return type. In this case it is void, which means
that Main does not return a value. Every method also has a parameter list
following its name with zero or more parameters between parenthesis. For
simplicity, we did not add parameters to Main. Later in this lesson we'll show
what type of parameter the Main method can have.


The Main method specifies its behavior with the Console.WriteLine(...)
statement. Console is a class in the System namespace. WriteLine(...) is a
method in the Console class. We use the ".", dot, operator to separate
subordinate program elements. It should be interesting to note that we could
also write this statement as System.Console.WriteLine(...). This follows the
pattern "namespace.class.method" as a fully qualified statement. Had we left
out the using System declaration at the top of the program, it would have
been mandatory for us to use the fully qualified form
System.Console.WriteLine(...). This statement is what causes the string,
"Welcome to the C# Station Tutorial!" to print on the console screen.


Observe that comments are marked with "//". These are single line comments, meaning
that they are valid until the end-of-line. If you wish to span multiple lines with a
comment, begin with "/*" and end with

"*/". Everything in between is part of the comment. You may place a single
line comment within a multi-line comment. However, you can't put multi-line
comments within a multi-line comment. Comments are not considered when
your program is compiled. They are there to document what your program
does in plain English (or the native language you speak with every day).
All statements end with a ";", semi-colon. Classes and methods begin with "{", left curly
brace, and end with a "}", right curly brace. Any statements within and including "{" and
"}" define a block. Blocks define scope (or




                                                           3
lifetime and visibility) of program elements, which will be discussed in a later lesson.


Many programs are written to accept command-line input. Collection of
command-line input occurs in the Main method. Listing 1-2 shows a
program which accepts a name from the command line and writes it to the
console.

Listing 1-2. Getting Command-Line Input: NamedWelcome.cs
        // Namespace Declaration
        using System;

        // Program start class
        class NamedWelcome
        {
          // Main begins program execution.
          public static void Main(string[] args)
          {
             // Write to console
             Console.WriteLine("Hello, {0}!", args[0]);
             Console.WriteLine("Welcome to the C# Station Tutorial!");
          }
        }

Remember to add your name to the command-line, i.e. "NamedWelcome Joe". If you
don't, your program will crash. I'll show you in a later lesson how to detect and avoid
such error conditions.


In Listing 1-2, you'll notice an entry in the Main method's parameter
list. The parameter name is args. It is what you use to refer to the
parameter later in your program. The string[] expression defines the
type of parameter that args is. The string type holds characters.
These characters could form a single word, or multiple words. The
"[]", square brackets denote an Array, which is like a list. Therefore,
the type of the args parameter, is a list of words from the command-
line.


You'll also notice an additional Console.WriteLine(...) statement within the Main
method. The argument list within this statement is different than before. It has a
formatted string with a "{0}" parameter embedded in

it. The first parameter in a formatted string begins at number 0, the second is
1, and so on. The "{0}" parameter means that the next argument following the
end quote will determine what goes in that position. Hold that thought, and
now we'll look at the next argument following the end quote.


This is the args[0] argument, which refers to the first string in the args array.
The first element of an Array is number 0, the second is number 1, and so
on. For example, if I wrote "NamedWelcome Joe" on the command-line, the
value of args[0] would be "Joe".




                                              4
Now we'll get back to the embedded "{0}" parameter in the formatted string.
Since args[0] is the first argument, after the formatted string, of the
Console.WriteLine() statement, its value will be placed into the first embedded
parameter of the formatted string. When this command is executed, the value
of args[0], which is "Joe" will replace "{0}" in the formatted string. Upon
execution of the command-line with "NamedWelcome Joe", the output will be
as follows:

          >Hello, Joe!
          >Welcome to the C# Station Tutorial!


Another way to provide input to a program is via the console. Listing 1-3 shows how to obtain interactive input
from the user.


Listing 1-3. Getting Interactive Input: InteractiveWelcome.cs

          // Namespace Declaration
          using System;

          // Program start class
          class InteractiveWelcome
          {
             // Main begins program execution.
             public static void Main()
             {
                // Write to console/get input
                Console.Write("What is your name?: ");
                Console.Write("Hello, {0}! ", Console.ReadLine());
                Console.WriteLine("Welcome to the C# Station Tutorial!");
             }
          }


This time, the Main method doesn't have any parameters. However, there are now three statements and the first
two are different from the

third. They are Console.Write(...) instead of Console.WriteLine(...). The
difference is that the Console.Write(...) statement writes to the console and
stops on the same line, but the Console.WriteLine(...) goes to the next line
after writing to the console.

The first statement simply writes "What is your name?: " to the console.


The second statement doesn't write anything until its arguments are properly
evaluated. The first argument after the formatted string is
Console.ReadLine(). This causes the program to wait for user input at the
console, followed by a Return or Enter. The return value from this method
replaces the "{0}" parameter of the formatted string and is written to the
console. This line could have also been written like this:


string name = Console.ReadLine();
Console.Write("Hello, {0}! ", name);




                                                          5
The last statement writes to the console as described earlier. Upon execution
of the command-line with "InteractiveWelcome", the output will be as follows:

       >What is your Name? <type your name here>
       >Hello, <your name here>! Welcome to the C# Station Tutorial!


By now you know the basic structure of a C# program. using statements let
you reference a namespace and allow code to have shorter and more
readable notation. The Main method is the entry point to start a C# program.
Interactive I/O can be performed with the ReadLine, Write and WriteLine
methods of the Console class.




                                        6
7

Contenu connexe

Plus de Dr. C.V. Suresh Babu

Diagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AIDiagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AIDr. C.V. Suresh Babu
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”Dr. C.V. Suresh Babu
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”Dr. C.V. Suresh Babu
 
A study on “the impact of data analytics in covid 19 health care system”
A study on “the impact of data analytics in covid 19 health care system”A study on “the impact of data analytics in covid 19 health care system”
A study on “the impact of data analytics in covid 19 health care system”Dr. C.V. Suresh Babu
 
A study on the impact of data analytics in COVID-19 health care system
A study on the impact of data analytics in COVID-19 health care systemA study on the impact of data analytics in COVID-19 health care system
A study on the impact of data analytics in COVID-19 health care systemDr. C.V. Suresh Babu
 
A study on the impact of new normal in learning &amp; teaching processes chem...
A study on the impact of new normal in learning &amp; teaching processes chem...A study on the impact of new normal in learning &amp; teaching processes chem...
A study on the impact of new normal in learning &amp; teaching processes chem...Dr. C.V. Suresh Babu
 
A Study on the “Virtual education in teaching chemistry”
A Study on the “Virtual education in teaching chemistry”A Study on the “Virtual education in teaching chemistry”
A Study on the “Virtual education in teaching chemistry”Dr. C.V. Suresh Babu
 
Developing a Map Reduce Application
Developing a Map Reduce ApplicationDeveloping a Map Reduce Application
Developing a Map Reduce ApplicationDr. C.V. Suresh Babu
 

Plus de Dr. C.V. Suresh Babu (20)

Mycin
MycinMycin
Mycin
 
Expert systems
Expert systemsExpert systems
Expert systems
 
Dempster shafer theory
Dempster shafer theoryDempster shafer theory
Dempster shafer theory
 
Bayes network
Bayes networkBayes network
Bayes network
 
Bayes' theorem
Bayes' theoremBayes' theorem
Bayes' theorem
 
Knowledge based agents
Knowledge based agentsKnowledge based agents
Knowledge based agents
 
Rule based system
Rule based systemRule based system
Rule based system
 
Formal Logic in AI
Formal Logic in AIFormal Logic in AI
Formal Logic in AI
 
Production based system
Production based systemProduction based system
Production based system
 
Game playing in AI
Game playing in AIGame playing in AI
Game playing in AI
 
Diagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AIDiagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AI
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”
 
A study on “the impact of data analytics in covid 19 health care system”
A study on “the impact of data analytics in covid 19 health care system”A study on “the impact of data analytics in covid 19 health care system”
A study on “the impact of data analytics in covid 19 health care system”
 
A study on the impact of data analytics in COVID-19 health care system
A study on the impact of data analytics in COVID-19 health care systemA study on the impact of data analytics in COVID-19 health care system
A study on the impact of data analytics in COVID-19 health care system
 
A study on the impact of new normal in learning &amp; teaching processes chem...
A study on the impact of new normal in learning &amp; teaching processes chem...A study on the impact of new normal in learning &amp; teaching processes chem...
A study on the impact of new normal in learning &amp; teaching processes chem...
 
A Study on the “Virtual education in teaching chemistry”
A Study on the “Virtual education in teaching chemistry”A Study on the “Virtual education in teaching chemistry”
A Study on the “Virtual education in teaching chemistry”
 
Features of Hadoop
Features of HadoopFeatures of Hadoop
Features of Hadoop
 
Developing a Map Reduce Application
Developing a Map Reduce ApplicationDeveloping a Map Reduce Application
Developing a Map Reduce Application
 
Min-Max algorithm
Min-Max algorithmMin-Max algorithm
Min-Max algorithm
 

Dernier

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 

Dernier (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 

Introduction to C# in .NET Framework

  • 1. A-PDF WORD TO PDF DEMO: Purchase from www.A-PDF.com to remove the watermark B E G I N N E R S ’ S C# TUTORIAL 1. A S I M P L E W E L C O M E P R O G R A M (Centre for Knowledge Transfer) 1
  • 2. This lesson will get you started with C# by introducing a few very simple programs. Here are the objectives of this lesson: Understand the basic structure of a C# program. Obtain a basic familiarization of what a "Namespace" is. Obtain a basic understanding of what a Class is. Learn what a Main method does. Learn how to obtain command-line input. Learn about console input/output (I/O). Listing 1-1. A Simple Welcome Program: Welcome.cs // Namespace Declaration using System; // Program start class class WelcomeCSS { // Main begins program execution. public static void Main() { // Write to console Console.WriteLine("Welcome to the C# Station Tutorial!"); } } The program in Listing 1-1 has 4 primary elements, a namespace declaration, a class, a Main method, and a program statement. It can be compiled with the following command line: csc Welcome.cs This produces a file named Welcome.exe, which can then be executed. Other programs can be compiled similarly by substituting their file name instead of Welcome.cs. For more help about command line options, type "csc -help" on the command line. The file name and the class name can be totally different. Note for VS.NET Users: The screen will run and close quickly when launching this program from Visual Studio .NET. To prevent this add the following code as the last line in the Main method: // keep screen from going away // when run from VS.NET Console.ReadLine(); The namespace declaration indicates that you are referencing the System namespace. Namespaces contain groups of code that can be called upon by C# programs. With the using System; declaration, you are telling your program that it can reference the code in the System namespace without 2
  • 3. pre-pending the word System to every reference. I'll discuss this in more detail in a later lesson, dedicated specifically to namespaces. The class declaration, class WelcomeCSS, contains the data and method definitions that your program uses to execute. A class is one of a few different types of elements your program can use to describe objects, such as interfaces and structures, which will be discussed in more detail in a later lesson. This particular class has no data, but it does have one method. This method defines the behavior of this class (or what it is capable of doing). The one method within the WelcomeCSS class tells what this class will do when executed. The method name, Main, is reserved for the starting point of a program. Before the word Main is a static modifier. The static modifier explains that this method works in this specific class only, rather than an instance of the class. This is necessary, because when a program begins, no object instances exist. Classes, objects, and instances will be covered in more detail in a later lesson. Every method must have a return type. In this case it is void, which means that Main does not return a value. Every method also has a parameter list following its name with zero or more parameters between parenthesis. For simplicity, we did not add parameters to Main. Later in this lesson we'll show what type of parameter the Main method can have. The Main method specifies its behavior with the Console.WriteLine(...) statement. Console is a class in the System namespace. WriteLine(...) is a method in the Console class. We use the ".", dot, operator to separate subordinate program elements. It should be interesting to note that we could also write this statement as System.Console.WriteLine(...). This follows the pattern "namespace.class.method" as a fully qualified statement. Had we left out the using System declaration at the top of the program, it would have been mandatory for us to use the fully qualified form System.Console.WriteLine(...). This statement is what causes the string, "Welcome to the C# Station Tutorial!" to print on the console screen. Observe that comments are marked with "//". These are single line comments, meaning that they are valid until the end-of-line. If you wish to span multiple lines with a comment, begin with "/*" and end with "*/". Everything in between is part of the comment. You may place a single line comment within a multi-line comment. However, you can't put multi-line comments within a multi-line comment. Comments are not considered when your program is compiled. They are there to document what your program does in plain English (or the native language you speak with every day). All statements end with a ";", semi-colon. Classes and methods begin with "{", left curly brace, and end with a "}", right curly brace. Any statements within and including "{" and "}" define a block. Blocks define scope (or 3
  • 4. lifetime and visibility) of program elements, which will be discussed in a later lesson. Many programs are written to accept command-line input. Collection of command-line input occurs in the Main method. Listing 1-2 shows a program which accepts a name from the command line and writes it to the console. Listing 1-2. Getting Command-Line Input: NamedWelcome.cs // Namespace Declaration using System; // Program start class class NamedWelcome { // Main begins program execution. public static void Main(string[] args) { // Write to console Console.WriteLine("Hello, {0}!", args[0]); Console.WriteLine("Welcome to the C# Station Tutorial!"); } } Remember to add your name to the command-line, i.e. "NamedWelcome Joe". If you don't, your program will crash. I'll show you in a later lesson how to detect and avoid such error conditions. In Listing 1-2, you'll notice an entry in the Main method's parameter list. The parameter name is args. It is what you use to refer to the parameter later in your program. The string[] expression defines the type of parameter that args is. The string type holds characters. These characters could form a single word, or multiple words. The "[]", square brackets denote an Array, which is like a list. Therefore, the type of the args parameter, is a list of words from the command- line. You'll also notice an additional Console.WriteLine(...) statement within the Main method. The argument list within this statement is different than before. It has a formatted string with a "{0}" parameter embedded in it. The first parameter in a formatted string begins at number 0, the second is 1, and so on. The "{0}" parameter means that the next argument following the end quote will determine what goes in that position. Hold that thought, and now we'll look at the next argument following the end quote. This is the args[0] argument, which refers to the first string in the args array. The first element of an Array is number 0, the second is number 1, and so on. For example, if I wrote "NamedWelcome Joe" on the command-line, the value of args[0] would be "Joe". 4
  • 5. Now we'll get back to the embedded "{0}" parameter in the formatted string. Since args[0] is the first argument, after the formatted string, of the Console.WriteLine() statement, its value will be placed into the first embedded parameter of the formatted string. When this command is executed, the value of args[0], which is "Joe" will replace "{0}" in the formatted string. Upon execution of the command-line with "NamedWelcome Joe", the output will be as follows: >Hello, Joe! >Welcome to the C# Station Tutorial! Another way to provide input to a program is via the console. Listing 1-3 shows how to obtain interactive input from the user. Listing 1-3. Getting Interactive Input: InteractiveWelcome.cs // Namespace Declaration using System; // Program start class class InteractiveWelcome { // Main begins program execution. public static void Main() { // Write to console/get input Console.Write("What is your name?: "); Console.Write("Hello, {0}! ", Console.ReadLine()); Console.WriteLine("Welcome to the C# Station Tutorial!"); } } This time, the Main method doesn't have any parameters. However, there are now three statements and the first two are different from the third. They are Console.Write(...) instead of Console.WriteLine(...). The difference is that the Console.Write(...) statement writes to the console and stops on the same line, but the Console.WriteLine(...) goes to the next line after writing to the console. The first statement simply writes "What is your name?: " to the console. The second statement doesn't write anything until its arguments are properly evaluated. The first argument after the formatted string is Console.ReadLine(). This causes the program to wait for user input at the console, followed by a Return or Enter. The return value from this method replaces the "{0}" parameter of the formatted string and is written to the console. This line could have also been written like this: string name = Console.ReadLine(); Console.Write("Hello, {0}! ", name); 5
  • 6. The last statement writes to the console as described earlier. Upon execution of the command-line with "InteractiveWelcome", the output will be as follows: >What is your Name? <type your name here> >Hello, <your name here>! Welcome to the C# Station Tutorial! By now you know the basic structure of a C# program. using statements let you reference a namespace and allow code to have shorter and more readable notation. The Main method is the entry point to start a C# program. Interactive I/O can be performed with the ReadLine, Write and WriteLine methods of the Console class. 6
  • 7. 7