Quick Search for:  in language:    
tutorial,will,started,with,introducing,very,s
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
.Net Stats

 Code: 140,189. lines
 Jobs: 376. postings

 How to support the site

 
Sponsored by:

 
You are in:
 

Does your code think in ink?
Login





Latest Code Ticker for .Net.
Click here to see a screenshot of this code!Ray Picking for 3d Objects
By Jay1_z on 11/23

(Screen Shot)

Embed Images into Xml Files
By Chris Richards on 11/23


Encryption and Alternate Data Stream
By Philip Pierce on 11/23


Click here to see a screenshot of this code!AddressBook
By Ekong George Ekong on 11/23

(Screen Shot)

Click here to see a screenshot of this code!Command Line Redirection
By kaze on 11/23

(Screen Shot)

Fader
By Ahmad Hammad on 11/23


Click here to see a screenshot of this code!Get content of a web page (simple)
By Tin Trung Dang on 11/22

(Screen Shot)

Retrieve the long path name for a short path name.
By Özgür Aytekin on 11/22


Easy Randomizer
By Christian Müller on 11/22


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites



 
 
   

Your First C# Programs

Print
Email
 

Submitted on: 2/26/2002 7:19:17 AM
By: Pankaj Nagar  
Level: Beginner
User Rating: By 9 Users
Compatibility:C#

Users have accessed this article 10638 times.
 
(About the author)
 
     This tutorial will get you started with C# by introducing a few very simple programs. Please vote if it is useful You will 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).

This article has accompanying files
 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
New Page 1

Your first C# Programs

This tutorial will get you started with C# by introducing a few very simple programs. You will

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. A Simple Welcome Program: Welcome.cs

// Namespace Declaration
using System;
// Program start class
class Welcome {
// Main begins program execution.
public static void Main() {
// Write to console
Console.WriteLine("Welcome to the PSC!");
}
}

The program in Listing 1 has 4 primary elements, a namespace declaration, a class, a "Main" method, and a program statement.
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 pre-pending the word "System" to every reference.
The class declaration, "class Welcome", contains the data and method definitions that your program uses to execute. It is one of a few different types of elements your program can use to describe objects, such as interfaces and structures. 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 Welcome 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. 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 it's name with zero or more parameters between parenthesis.
The "Main" method specifies it's 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 PSC!" 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.
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 lifetime and visibility) of program elements.
Many programs are written to accept command-line input. Collection of command-line input occurs in the "Main" method. Listing 2 shows a program which accepts a name from the command line and writes it to the console.

Listing 2. Getting Command-Line Input: Greet.cs

// Namespace Declaration
using System;
// Program start class
class Greet {
// Main begins program execution.
public static void Main(string[] args) {
// Write to console
Console.WriteLine("Hello, {0}!", args[0]);
Console.WriteLine("Welcome to the PSC!");
}
}

Remember to add your name to the command // -line, i.e. "Greet Pankaj". If // you don't, your program will crash unless you detect and avoid such error conditions.
In Listing 2, you'll notice an entry in the "Main" method's parameter list. The parameter name is "args". It's 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.
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 "Greet Pankaj" on the command-line, the value of "args[0]" would be "Pankaj".
Now about the embedded "{0}" parameter in the formatted string. Since "args[0]" is the first argument, after the formatted string, of the "Console.WriteLine()" statement, it's 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 "Pankaj" will replace "{0}" in the formatted string. Upon execution of the command-line with "Greet Pankaj", the output will be as follows:

>Hello, Pankaj!
>Welcome to the PSC!

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

Listing 3. Getting Interactive Input: GreetMe.cs

// Namespace Declaration
using System;
// Program start class
class GreetMe {
// 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 PSC!");
}
}

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 it's 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.
The last statement writes to the console as described earlier. Upon execution of the command-line with "GreetMe", the output will be as follows:

>What is your Name? <type your name here>
>Hello, <your name here>! Welcome to the PSC!

So now you know the basic structure of a C# program. You have become familiar with namespaces and classes. You know the "Main" method is your entry point to start a C# program and how to capture command-line input and perform interactive I/O.
 

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.

Virus note:All files are scanned once-a-day by Planet Source Code for viruses,but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:
1)Re-scan downloaded files using your personal virus checker before using it.
2)NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

If you don't have a virus scanner, you can get one at many places on the net including:McAfee.com

 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.


Other 13 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
2/27/2002 1:02:54 AM:Nick
Excellent for beginners who are starting to learn C# Like Me!!!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
2/27/2002 6:01:04 PM:Manas Mukherjee
Dear Pankaj Good job, keep it up. But did you try to compile it from the command prompt using csc ? Add Readline // Namespace Declaration using System; // Program start class class Welcome { // Main begins program execution. public static void Main() { // Write to console Console.WriteLine("Welcome to the PSC!"); // Add this line Console.ReadLine(); } } I have Net Beta 1 and Beta 2 I usually compile with VC++6.0 (edditing extension cs)and C:\Folder> csc file.cs to create exe. Now file.exe is ready to run and display your message. C:\Folder>Welcome.exe Your version of Net please.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
2/28/2002 12:07:21 AM:Pankaj Nagar
All files included in download have been succesfully compiled using .Net Framework SDK Beta 2. There should not be problems compiling it with Visual Studio Beta 2 or above... but I have not tested it.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
2/28/2002 2:14:47 AM:Manas Mukherjee
What do you mean compiling with visual studio beta sdk 2, if you did not test it yet?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
2/28/2002 6:50:14 AM:Pankaj Nagar
I am talking of .net Framework SDK which included csc compiler and of course via command line. What I have not tested is within Visual Studio .Net IDE.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/31/2002 2:18:08 AM:
I also get this article from another site. This is: http://www.csharp-station.com/Tutor ials/Lesson01.aspx I think this article is from here! And the author is by Joe Mayo, 8/20/00, updated 9/24/01. This article is very clearly and helpful!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
2/24/2003 3:05:14 PM:nfs
C# is the future.Nice work. Hi, Do you want to make money with your programming skills ? Software Objects provide following services : 1)Sell your software. 2)Post a software to be done. 3)Bid on the software projects. 4)Buy software Thanks and have a nice day. Software Objects http://www.thesoftwareobjects.c om
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/10/2003 1:00:08 PM:
How do you compile a C# program. I do not have the 'cs' command in my default .net installation. Is it necessary to use the C++ compiler?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | .Net Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.