Page 1 of 1

Hello World: Your First C# Program

#1 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4490
  • View blog
  • Posts: 7,822
  • Joined: 08-June 10

Posted 21 March 2011 - 09:02 AM

*
POPULAR

Learning C# Series
Hello World: Your First C# Program

Watch the screencast here!

Hello World is traditionally the first program a learner will write. It's simple, basic, and also verifies that your environment is set up correctly. It's important to start somewhere, so we'll start here.

Why is this important to learn about?

This is the basic introduction to a language; specifically: C#. If you don't start with a good foundation, you risk learning bad habits that are almost impossible to break later.

Definitions of terms used.




Note: All examples were created using Visual Studio 2010, targetting the .NET Framework 4.0. We'll do our best to point out anything that might not work in older versions.

Hello World

Getting Started

We'll start at the very beginning. Open up Visual Studio. Again, I'm using Visual Studio 2010, but for a program like this, any version all the way back to Visual Studio.NET will work, including Express Editions (the freeware versions).

Here's what you should see (or something similar to it).

Attached Image

Let's make a new project. There's a button on the toolbar, or we can do this through the File menu. Choose a Windows Console Application, and name it HelloWorld.

Attached Image

It should take a moment or two to create the project for you. It should finish, and then open up a file named Program.cs with some code already added.

Attached Image

This is your basic console application template. If you ran this code right now, the console would appear and quickly disappear, since you haven't written anything. That's what a basic console application will do: start and finish. You have to provide all the stuff in between.

The Default Template Explained

So, before we write any code, let's take a look at each part that was already included. The first line is:

using System;


This is what is known as a using directive. The .NET Framework is broken up across several libraries into what are called namespaces. These namespaces are used for logical grouping of types. For instance, you'll find tools to write and read from files in System.IO, or tools for network communication in System.Net.

Using directives tell the compiler to look in these namespaces to find the tools we're using. We don't have to use these using directives. We could fully qualify all the types we use (it's just plainly inconvenient). The most important one for this example: System. It contains basic tools, classes, and exceptions. In this example, we'll use it to write text to the console.

The other using directives are not important for this example. They're included automatically because they are frequently used, but we don't care about them at the moment.

Next, we see a namespace declared. As we mentioned before, these are to create logical groupings of scopes. You'll notice that this namespace is the same name as our project: HelloWorld.

Next, the line class Program. This line begins our class definition. Classes are a construct that can contain properties and methods. We'll learn more about them later in the series. For now, just understand that our program exists inside this class named Program.

Next, the line static void Main(string[] args). This is what is known as the Main method. This is the entry point of the application; this is where the program starts when it is run. Methods (also known as functions) are effectively blocks of code created to do something. You can create more than one, and call them repeatedly. Main is a special one. When the computer runs the program, Main is where it always starts.

After that, all there are are closing braces. Braces in C# define scopes. We'll cover scope more deeply in later tutorials. For now, notice how for every open brace {, there's a closing brace }. And notice that the braces correspond with the constructs we've already discussed: methods, classes and namespaces. There are several others, but again, we'll cover them more deeply in later tutorials.

Adding Our Own Code!

C# is a fairly semantic language, and the "Hello World" program is a great example of this. Let's think what we want to do. We want to write a line of text to the console. To do that, we use Console.WriteLine().

Add this in the Main method, in between the braces:
Console.WriteLine("Hello World");


Attached Image

Now you have a complete program. If you run it now, it will print what's in the quotation marks out to the console. Let's run it now. Press F5, or click the green right-facing triangle on the toolbar. You can also go to the Debug menu and choose "Start Debugging".

What happened?! The console popped up and disappeared too quickly to read! Why did it do that? Well, it's just the nature of the windows console. If a program that runs in the console opened the console, the console will be closed when the program exits. And our program exits immediately after it prints. So the console exits too, faster than we can read it.

There's a simple way to solve this. We add one more line of code: one that waits for user input:

Console.ReadKey();


Attached Image

That code takes in the next key that the user presses. It "blocks" the program until that key is pressed. So when it gets to that line, everything stops and waits. Which works perfectly for our purposes. Run the program again. This time, the console will appear and wait for you to push a key before it goes away.

Attached Image

That's it! You've just written your first C# application. Not too hard, right? Visual Studio does most of the work for you.

On that note, I'd like to start now impressing upon you the importance of trusting Visual Studio's tools. This is not a low level language with tools that don't help much. Visual Studio is a very well designed IDE, with excellent auto-completion features (known as IntelliSense) and great error checking. If you're trying to use a name and IntelliSense is trying to correct it into something else, either you've misspelled it, or there's a compilation error preventing it from finding what you want. If there's a red squiggly line under some code, it means that there's an error there or somewhere near it. Trust your tools, and your work will go much faster and easier. Don't try to fight against it.

In Conclusion

To wrap all this up, don't be afraid of trying stuff. Change the code a bit, and see what happens. See what happens when you add more WriteLines. Experiment. Read the MSDN, and the rest of our tutorials. Look up more tutorials. Learning how to program is great fun!

See all the C# Learning Series tutorials here!

This post has been edited by insertAlias: 22 March 2011 - 09:52 PM


Is This A Good Question/Topic? 10
  • +

Replies To: Hello World: Your First C# Program

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5529
  • View blog
  • Posts: 11,843
  • Joined: 02-June 10

Posted 21 March 2011 - 11:08 AM

Nicely done. Going on my Newbie link list.
Was This Post Helpful? 0
  • +
  • -

#3 TMKCodes  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 48
  • View blog
  • Posts: 440
  • Joined: 21-March 09

Posted 22 March 2011 - 02:12 AM

Weee! You got me to install monodevelop and test my first C# code. xD
Was This Post Helpful? 0
  • +
  • -

#4 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4490
  • View blog
  • Posts: 7,822
  • Joined: 08-June 10

Posted 22 March 2011 - 05:34 PM

Glad I could. C# is a wonderful language. I've never actually used MonoDevelop before; I might have to. My laptop is a mac (though I've got it bootcamped.)
Was This Post Helpful? 0
  • +
  • -

#5 muffinman8641  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 121
  • Joined: 17-March 11

Posted 24 March 2011 - 08:22 AM

Do you guys think C++ or C# is better to learn? I think C++ is more of a standard but C# might be more advanced/modern...
Was This Post Helpful? 0
  • +
  • -

#6 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4490
  • View blog
  • Posts: 7,822
  • Joined: 08-June 10

Posted 24 March 2011 - 09:12 AM

That 100% depends on what you're going to be doing with it. Anyway, here's a discussion we recently had with over 100 responses to a very similar question.

http://www.dreaminco...-for-beginners/
Was This Post Helpful? 0
  • +
  • -

#7 mitultechs  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 18-October 11

Posted 18 October 2011 - 05:19 AM

Good Information regarding the C#. I have started to learn the C# program. Please Anybody can share me the jobs on C#.net. What are the requirement? What need to know? What is the importance? Soon wanna apply for the jobs.
Was This Post Helpful? 0
  • +
  • -

#8 DarenR  Icon User is offline

  • D.I.C Lover

Reputation: 463
  • View blog
  • Posts: 3,171
  • Joined: 12-January 10

Posted 18 October 2011 - 05:30 AM

@Curtis

you should collect all your snippets into a book and sell it to colleges because your tutorials are much more user friendly than that of current college text books. Professors when they write books forget that beginners do not understand the jargon they place in books. At least yours are easy to follow.

Nicely done
Was This Post Helpful? 0
  • +
  • -

#9 zofi51  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 02-October 12

Posted 30 October 2012 - 07:48 AM

what the 4 namespaces at top of code will do?
Was This Post Helpful? 0
  • +
  • -

#10 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4490
  • View blog
  • Posts: 7,822
  • Joined: 08-June 10

Posted 30 October 2012 - 07:59 AM

Quote

Using directives tell the compiler to look in these namespaces to find the tools we're using. We don't have to use these using directives. We could fully qualify all the types we use (it's just plainly inconvenient). The most important one for this example: System. It contains basic tools, classes, and exceptions. In this example, we'll use it to write text to the console.

The other using directives are not important for this example. They're included automatically because they are frequently used, but we don't care about them at the moment.


To explain in a bit more detail: in .NET, classes, structs, and interfaces are all grouped under what is called a Namespace. Namespaces are a logical organization construct, not a physical one. One namespace may have components spread across dozens of DLLs, or one DLL may contain a dozen namespaces. Usually, the ones from Microsoft will be organized sanely. The ones you make or get from someone else...who knows.

When you add a using directive to your code page, what you're telling the compiler is that we want to be able to use components from that namespace without having to type the whole namespace each time.

For example, String belongs to the System namespace. If we don't include using System; at the top, every time we wanted to use a String, we'd have to type System.String. That's not so bad, but some namespaces may be several layers deep.

To explain what the default template namespaces actually do:

System includes all the basic classes, like String and Int32 (which have keywords like string and int aliased to them). It's something that should almost always be included, because it includes the most basic functionality.

System.Text includes resources that make text formatting and editing easier, like the StringBuilder class.

System.Collections.Generic includes the Generic Collections, like List<T> and IEnumerable<T>. They're quite helpful to deal with different kinds of sets of data. There's a tutorial on Generics that you can look up later once you know more about what's going on.

System.Linq includes the LINQ classes and extension methods. It's an advanced topic that won't do you much good at this stage to get wrapped up with. Simple explanation: LINQ is a set of tools for querying and manipulating collections.

Hope that helps.
Was This Post Helpful? 0
  • +
  • -

#11 zofi51  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 02-October 12

Posted 31 October 2012 - 09:51 PM

here we r dealing with just text,not with lists,generics and query or linq.so why 2nd n 3rd namespaces have been declared?
Was This Post Helpful? 0
  • +
  • -

#12 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4490
  • View blog
  • Posts: 7,822
  • Joined: 08-June 10

Posted 01 November 2012 - 06:17 AM

Because it's part of the default template Visual Studio uses to create a Console Application project. It's added for you. I didn't want to remove them, because I didn't want my project to look different from a new person's project; they might not understand the difference.

Also, we're not using anything from System.Text either. We're not doing any encoding changes, or using a StringBuilder. So, technically, the only namespace this project needs is System.
Was This Post Helpful? 0
  • +
  • -

#13 AntonB  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 05-November 12

Posted 06 November 2012 - 08:15 AM

Thanks for this great tutorial. I learned very much out of it. I have seen another tutorial,but your tutorial makes VERY more sence for me! So thanks for that help!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1