C Sharp Development 101 – Part 1: Hello World

In this tutorial we are going to get up close with the Visual Studio 2010 environment. We will learn how to make a console application as well as a form to display our hello world applications.  This will give us an opportunity to view 2 types of solutions of the many available in Visual Studio.  We will start making the console application first then progress to the forms application.

First we must  understand the development environment we are going to use.  On the far left side is the toolbox panel.  This panel gives us access to a lot of controls  that can be used by the Windows Forms.  Next is the Solution Explorer that will allow us to navigate the projects and files we are going to create in this Solution.  The Properties panel is directly under my Solution Explorer and will allow us to change properties of controls and of the form we will create later on.  If any of these are not being displayed they can be retrieved from the View menu at the top under Other Windows.  For more information on the Visual Studio IDE visit MSDN and search for the specific questions you are having.

Then we need to start the Visual Studio environment and create a new project.  To do this we will go to File then navigate to New Project and click it.  A dialog box will appear and ask you which project you would like to include in your solution that will be automatically created for your project.  We need to use the Console Application.  Next we need to replace the box at the bottom where it says ConsoleApplication1 with HelloWorldConsole and then after the project and solution is created press CTRL-S to change the name of the solution file to HelloWorld in the box under the project name box and press OK.  This will create a project inside a Solution file. The solution file acts like the glue that binds all projects included in the solution file together.  Later on we will discover how this is beneficial for creating projects and making class files that reference DLL’s that we will code.

Once the project is created we are going to edit the program.cs file.  After you have open the program.cs we are going to add the text necessary to have the program output “Hello World” to the console.  To do this we will need to add the line Console.Out.WriteLine(“Hello World!”); inside the static void main curly brackets.  After this is complete we can now build and attempt to build our solution.  To build the solution we need to press CTRL + SHIFT + B and the build process will being.  After the build is a success we can now run the Console Application by pressing CTRL + F5. This will display a command prompt with “Hello World!”.

Here is the source code for program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorldConsole
{
class Program
{
static void Main(string[] args)
{
Console.Out.WriteLine("Hello World!");
}
}
}

We can now move on to the windows forms application of Hello World.  To do this, we need to go to the solution and Right Click, then go to Add then click New Project.  For the project we will name it HelloWorldForms.  After the project is created we are going to delete the Form1.cs and we are going to create a new form by Right Clicking the HelloWorldForms Project, Navigating to Add then to New Item,  and when the dialog box appears we are going to pick Windows Form.

The name we are going to use is main.cs and press Add.  We now edit the program.cs to change the Form1 that can be found in the file to main.  After the Windows Form is created we can start adding in Controls from the Toolbox.
We are going to drag a label and a button onto the form portrayed in the middle of the program.  We are going to edit the properties here to make the text inside the label blank and the name of the label lbHelloWorld instead of label1.  After this is done we are going to want to edit the button we dropped onto the form earlier.  We will change the name of the button to btnHelloWorld and the Text of the button to Click Me!.  After this is done we are going to want to use an event handler to tie the button and the label together, so when the button is clicked “Hello World!” will appear in the label.

To make an event handler for the button we are going to go to the Properties panel and click the button on the top that looks like a lightning bolt.  This will take us to all o the event handlers that this button can handle.  We want the Click event handler, this will create the code required to handle a click event in the main.cs.  Now that the wrapper is there we can code the output to the label when the button is clicked.  Inside the curly brackets of “private void btnHelloWorld_Click” in main.cs input the following line of code to link the two Controls:


lbHelloWorld.Text = “Hello World!”;

This will make the main.cs look like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HelloWorldForms
{
 public partial class main : Form
 {
 public main()
 {
 InitializeComponent();
 }

 private void btnHelloWorld_Click(object sender, EventArgs e)
 {
 lbHelloWorld.Text = "Hello World!";
 }
 }
}

The program.cs should look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace HelloWorldForms
{
 static class Program
 {
 /// <summary>
 /// The main entry point for the application.
 /// </summary>
 [STAThread]
 static void Main()
 {
 Application.EnableVisualStyles();
 Application.SetCompatibleTextRenderingDefault(false);
 Application.Run(new main());
 }
 }
}

After all of this is completed we need to run the program by pressing CTRL + F5 again. The screen that should appear should be something like this:

The screen after the button has been pressed should look like this:

Now that we have completed the next tutorial you should be able to move through the Visual Studio IDE to make multiple projects under one solution, delete files within a project and create new forms and classes, and modify source code within event handlers.  The next tutorial will go more in depth with the Visual Studio Toolbox and make a form with controls on it with minimal backbone code, as well as review some of the common files created and what is automatically included for you.  For more information on Toolbox Controls you can check out Microsoft MSDN article on Toolbox Controls. If you are having any trouble with this project feel free to comment and I will help to try and resolve the issue.  Until next tutorial, Happy Hacking!

Comments

  1. PhilKll says:

    Thanks for the tutorial, I was worried, having previous done a few things in C# it would take a few of these before it got to anything new for me, but the explanation of Solutions and Projects, was very helpful, wasn’t quite sure what the difference was.

  2. M4CGYV3R says:

    Are you covering Windows Forms Designer too or just console-type work?

    The .NET suite really shines when you get to the rapid prototyping steps, specifically the forms designer.

  3. dan says:

    If you’re covering UI development at all, please introduce people to WPF! WPF and databinding is fantastic.

  4. Matthew says:

    Soo… Remind me what this is doing on Hack A Day exactly?

  5. Mike says:

    Thank you for posting this! More!

  6. coreyl says:

    C# is a perfectly serviceable language for IT grunt work. Has fuckall to do with hacking though.

  7. Merlin051 says:

    Please can you do a section on Web Services and SOAP calls?

  8. Trollicus says:

    C#??? sorry, the whole IDEA of the C language and it’s decedents is portability of code. By making a proprietary version of C dependent on the proprietary .NET protocol MS has produced a product that is the antithesis of all Hacking. Why would the hacking community want to develop in a language that locks you in worse than an un-jailbroken Iphone?

    Please read the MS document called the “halloween letters” where MS discribes their strategy of market dominance through the control of Protocols, then think about .NET and even DirectX and how it’s implemented in Vista and windows 7. where OpenGL calls go through DirectX.(slowing down OpenGL)

  9. Matthew says:

    Guys! There are plenty of newbie C# tutorials elsewhere, we don’t need them on our favourite hardware hacking websites!

  10. PhilKll says:

    Never used it for hacking exactly, but I have used it to create a dll that interfaced with a micro and an LCD. Which was a super easy way to create a couple other apps in C# which used the LCD screen. As code behind in ASP.NET, web interfaces should be pretty easy to build also. I also built a conversion program, that goes between ascii,hex,binary,decimal which has come in as a handy tool. Not exactly hacking, but useful in the process.

  11. clutchdude says:

    Nice but I gotta echo others: what’s this have to do with hacking?

  12. Fallen says:

    Wouldn’t C be a little more appropriate than C# for a hacking blog? Or Java…something we can port to hardware…

  13. Karl says:

    @Trollicus

    C# is an open standard, and it does have portability. These aspects are most prominantly displayed in the Mono Project and Silverlight. The .NET Framework is what is locked down, but it has some very broad application (ASP.NET, Silverlight, Desktop applications, Windows Phone 7).

    Also, Microsoft open sourced the .NET Micro Framework which is perfect for hacking with C#. The Netduino is a great example of this in practice.

  14. PhilKll says:

    I would agree, I use C or Assembly for micro controller programming, more than I use C# for anything resembling what would be considered HaD material. But there is the C# micro framework, for this purpose, never used it myself, but its out there.

    http://www.microsoft.com/netmf/default.mspx

    Not trying to be a fan boy, I’ve just found it useful and easy to use for certain things. I’d love to see a C tutorial for micro controllers too as I’ve recently started using it, and its more complicated to understand.

  15. r_d says:

    IMHO, nothing this editor has posted is worth reading.
    A list of Twitter clients and junk regurgitated from the _very_ comprehensive Android/C#+.NET docs. How useful. :/
    Even if this stuff did belong on HaD, which it doesn’t, it has nothing to add over the official sources.

  16. Whoever says:

    C#??? sorry, the whole IDEA of the C language and it’s decedents is portability of code. By making a proprietary version of C dependent on the proprietary .NET protocol MS has produced a product that IS THE ANTITHESIS OF ALL HACKING.

    Why would the hacking community want to develop in a language that locks you in worse than an un-jailbroken Iphone?

    Please read the MS document called the “halloween letters” where MS discribes their strategy of market dominance through the control of Protocols, then think about .NET and even DirectX and how it’s implemented in Vista and windows 7. where OpenGL calls go through DirectX.(slowing down OpenGL)
    ———————————–

    That comment was worth repeating. (Some emphasis mine).

  17. Bluechip says:

    I can’t understand the choice of C# for this either. It’s actually quite bizarre that someone would think C# was a better choice for a tutorial series than C/C++.

  18. Osgeld says:

    “”Guys! There are plenty of newbie C# tutorials elsewhere””

    yea I know, after 27 days of having extra stuff installed on my machine I went elsewhere to learn how to make it do something

    cant wait for Halloween for number 2 in the series

    (if you cant tell by the tone in my text… pick up the pace if you insist on doing this please)

  19. r_d says:

    “Proprietary versiion of C”
    Someone has clearly never used C. C# has as much to do with C as software “engineering” has to do with engineering. The similarities are only in the names.

  20. NP says:

    I am sorry to say that this is the worst article I’ve ever read on this site. If Hack a Day continues marketing proprietary technology and encourages (many first-time) programmers to become part of this culture, this website will suffer bad from decreasing visitors.

    (Still I admit that the language and the IDE provide a practical “click-and-play” methodology that serves well for prototyping and have used it professionally, but I think people can read about this elsewhere.)

    Hack a Day: listen to your faithful readers or you will make a big mistake.

  21. Mastro Gippo says:

    Stop bitchin, guys… C# is the Arduino of C, and is really usefull to quickly test some code, mostly for the awesome ability to edit code while debugging and moving around the pointer as you please. It makes a lot of tasks completly trivial, and is very easy to learn and use.
    I’m pretty sure HaD will add a nice tutorial on hacking c# programs with Refractor too, right?

  22. pRoFlT says:

    Damn, everyone is hating today. Apply for a job @ HAD and write the articles you think should be on hear. Stop bitchin!

    Hacking is not only hardware. You can use C# to create windows hacks. Or even talk to hacked hardware. A good hacker should understand the need for multiple programming languages and skill sets to be a great one man hacker. (cough cough, like me) :)

    Okay my turn to gripe, I think an Assembly 101 lesson would be great. It can be used on many micro processors to get the speed you need out of them. The Arduino may be easy to use but can you get it to do time sensitive control? digitalwrite does take some time to do.

  23. edonovan says:

    @M4CGYV3R: I have to agree with you. Rapid prototyping is really the only reason I use C#

    I would like to see this series transition into something more useful (hardware interfacing), instead of repeating the hundreds of other C# tutorials that are around.

  24. response.write “Hello World”

    I prefer this.

  25. Amtal says:

    People have to start programming somewhere, and I guess C# is better than C/C++. Beginners that start with those tend to get locked into a certain mindset…

    The folks screaming in rage have a point though. Python or Perl or Lisp or assembler wouldn’t dilute the spirit of hacking the way this does.

  26. Amtal says:

    (C# could be justified due to its ease of GUI creation, but this tutorial doesn’t make a GUI so…)

  27. whilehigh says:

    To heck with the debbie-downers.

    Keep posting tutorials.

    One needs to learn in order to hack.

  28. Tachikoma says:

    If you hate C#, use C++ CLI instead. The latter allows you to use std libraries as well as .NET shit.

    But whatever.

    .NET is fucking awesome for Windows GUI programming, which I think is essential if you want to make a decent front-end for your Windows projects. Of course, it’s completely useless for portability, which in that case you should be looking at other options anyway.

    I wish Microsoft would ditch MSIL and its JIT compiler, and compile .NET directly to native code instead.

  29. j00lz says:

    I am currently using a combination of MS VS10/.Net and MonoDevelop/Mono to write a Winforms based application that talks to x0xb0xes via the serial port.

    .Net & C# are great for productivity (I achieve more with less code), and port well (with a few gotchas) to Mac OS X and Linux.

  30. Paradox says:

    @Tachikoma,

    you haven’t done much coding with anything besides .net have you. windows GUIs are simple to do in ASM or C.

    i have to agree with r_d.. nothing this editor has posted is worth reading. on top of that almost everything posted has been *borrowed* and reworked from other sites. the original content posted is is at such a low level i doubt 5th grader might find intellectually challenging.

    This is HAD one of the few sites that actually posts about hardware hacks, if i wanted poorly done hello world examples i would go to one of the thousands of programming tutorials on the web.

  31. Luke says:

    C# can be used for embedded development. Scott Hanselman blog has some details on it.

    http://www.hanselman.com/blog/TheNETMicroFrameworkHardwareForSoftwarePeople.aspx

    NetDuino (runs tiny CLR)

    http://www.makershed.com/ProductDetails.asp?ProductCode=MKND01

    .NET micro framework

    http://blogs.msdn.com/b/netmfteam/archive/2010/07/19/netmf-versions-4-1-released-to-web.aspx

    Not tried it myself, but it is probably worth investigating.

  32. namochan says:

    Wow, this I didn’t expect.

    Did you get sponsored by Microsoft to spread this disease?

    Please make some more, so I can finally shorten my RSS-Feed list.

  33. Rollyn01 says:

    @Tachikoma( a fellow GITS fan myself, so I love the name.)

    It would be ill-advised to give Microsoft any suggestion that a direct compile of .NET to native code( even if it’s through an expansion of commands using .dll files) is a good thing. As far as all things are considered, much of the code itself is very unstable/disruptive to many internet-based protocols. All you’ll end up with is another broken language that allows Microsoft to point the finger at various internet protocols while they tried to showcase a “better” solution to a non-existent problem.

  34. Shield says:

    @Mathew

    We get it, you don’t like tutorial on HAD. The great thing is nobody care what you think.

  35. Tachikoma says:

    Hmm, I’m not sure if I’m following you… A great portion of .net libs in C# and C++ CLI has nothing to do with networking. I just don’t see how an executable in MSIL or x86 binary has anything to do with standardisation of protocols?

    My gripe is that the whole thing appears to be a wrapper for WIN32 and MFC APIs, which get called via JIT compiled code. If you are going to develop a standalone windows application, why not compile it to native x86 binary straight away?

    • Caleb Kraft says:

      @everyone asking why:
      Hacking isn’t just robotics and microcontroller projects. We feel that C# has its place in our tutorial line up. However, we plan on doing much more. C# is what we have available right now. We are currently putting together other tutorial series as well as hiring to expand our capabilities. stay tuned, or even better, contribute!

      What languages would you like to see in the software development tutorials? Email your suggestions to me caleb@ or the tip line instead of filling this thread please.

      —-edit—
      re-reading that, it seems like I’m being short and lecturing… I’m not.

      in short: great feedback guys, we’re giving you what we can, let us know what else you want!

  36. antonye says:

    > using System.Collections.Generic;
    > using System.Linq;

    If you’re going to write a tutorial, please at least understand the source material – none of these libraries are required for the code you’ve written!

    It would be a much more valuable exercise to explain some basics as you go, such as what these USING commands are for, and how about some of the additional tools you can use (most for free!) in Visual Studio, such as refactoring programs (JetBrains ReSharper, for example) or even MS’s own FX Cop – all of these can underpin basic, important principles in writing good code and are worthy of using from the start.

  37. frozenlazer says:

    I’m conflicted on this one. I earn my living developing in C# so this is of little use to me, but I’m all for sharing information.

    I have to agree with the posts that indicate that are 1000’s of C# starter tutorials.

    Perhaps instead of writing their own Hello World tutorial, HAD should find some good ones and link to them for the beginning stuff (to get people up to speed), and then write a tutorial on how we can apply .Net to some hardware projects. For example integrating with a microcontroller. Click a GUI button to start/stop some blinkenlights or something.

  38. smoker_dave says:

    Guys lets see how the series pans out before getting worked up.

    In a few tutorials time the author might have us communicating with our AVR projects over USB interface or something similar. This is only beginning and a lot of people don’t know how to do this “simple” stuff already.

    Personally it is no use to me as I work with this kind of thing daily, but I just chose to not look at the posts (unless it is a slow Friday afternoon!).

    Give the author a break man!

  39. terribledamage says:

    I code in C/C++ but not in this object oriented crap. C# is another language what we don’t need. I don’t know it’s story and I don’t care about it either but they probably made it to compete with Java.

    Good C coders dont use lame shits like boost library either but code their own stuff, especially not C#…

    Theres no point of it anyway because everyone is developing apps for the web now, java is perfect for that.

  40. Xympa says:

    I love C#, is use it everyday, it’s my own personal b**ch when i’m messing in windows, although i think Assembly 101, (asm if you will) would suit HaD better, and is something everyone should know. I’m not a fanboy, but i see many hateboys around here, face it if windows wasn’t heavy like a truck, the world wouldn’t know what multi-cores were. It’s heavy software that propels the industry to go further, and you can stick with your linux or whatever suits you, but it’s counter-productive to tear down windows if you want an awesome machine or your room.

  41. steve says:

    WOW, quit crying. If you don’t want to read it, DON’T! It’s the internet, not a newspaper. The article isn’t taking up space that could be used by another story. And C# is great for hacking. I’ve used it to make dozens of little apps to interface with my embedded systems. I don’t care whether or not it’s proprietary, it’s quick and easy.

  42. jtuttle says:

    Good coders use libraries like boost because they know that it will have less bugs than reinventing the wheel and saves time.

  43. megachad says:

    I’m currently in a computer science program in cegep (college) in Canada, and our programming classes are all about C#. I hate it with a passion. I’ve coded in C for quite a long time, more recently in Haskell, but C# makes me wanna cry. Especially when you’re running GNU/Linux. Even more when you have to use XNA on top of that, which has zero compatibility with *nix.

  44. darkstar3d says:

    Why not take a course without C#? Most universities offer courses with C, C#, Java, and others.

    Crazy that this is on Hack a Day, even if it can be used in embedded systems.

  45. pRoFlT says:

    @terribledamage, I just want to say this. I HATE WEB APPS! They are slow and i dont want to have to be on the internet to use them.

    That said, i’ve seen the new web based game streaming service and its awesome. Maybe in a couple more years when everyone is downloading at 20MBs not 20Mbs then it will be okay. Still you rely on the web service to be up and running to use it.

    C# over C++. You can write code faster in C#. Garbage collection in C#. Yes c++ is fast but will you notice the difference?

    not that i use C#, i’ve only played with it. I get paid to use LabView :) and of course RUBY!

  46. k4l says:

    mhhh due to my professional field i just doing some embedded programming during my bsc and private. in my current company we are developing server inprograms mainly with java an spring… it’s a pain in the ass, if you compare it to c# its just bullshit.

    yes, c# is not intended to use for embedded hardware. for using in wcf services or desktop applications, its the most modern language and framework. yes you can write guis in c++ or even in asm, but in professional development speed of development is more honored(time is money) than a c program which is 10% percent faster than the c counterpart.

    dont understand me wrong, I love c(++) but in most cases its not applicable in (very) fast evolving business. Your boss will you fire, if you tell him in the daily scrum “sorry, yesterday ive lost a pointer and this morning i found it…” thats not acceptable in most 08/15 bussiness applications. c# has the big advantage, there is one framework. Have a look at 10 java job offers, you have 20 frameworks. .net doesnt.

    dont curse everything from m$, the os is thrash, but be open to new things…

  47. Tom says:

    Perhaps the author should take a look at the “Console.WriteLine” function. There is nothing wrong in writing directly to the “Out” stream, but the Console.WriteLine function provides some nice overloads for parameters/writing things other than strings.

  48. r_d says:

    @k4l:
    This is a hacking site. We shouldn’t give a fsck what’s “acceptasble in most business applications”.
    We care about whats useful to _us_, and what’s different, interesting, and/or clever.
    Hello world in C# is not useful to me, and it is not different/interesting/clever.

  49. Ugly American says:

    Wow! Now everyone can learn to develop for the new Microsoft Kin phones!

    Oh wait – they’re already discontinued.

    Microsoft constantly targets inexperienced programmers and tries to hook them into proprietary backwaters. Consider all the time and effort squandered learning other proprietary MS stuff like Visual InterDev, Visual J++ and Visual Test only to have them discontinued.

    Consider products like Microsoft Money & Microsoft Office Accounting. Did you use them for your business? They were also discontinued and the file formats are proprietary and undocumented. Of course, the IRS sill holds you liable to provide the information regardless of the MS shrink wrap weasel words. You can lose your business and go to prison because MS won’t support their own old software and won’t release the code.

    The long list of discontinued proprietary platforms from Microsoft won’t even fit in this space. All the .net products are just another dead end proprietary backwater.

    JavaScript runs on every major platform, faces the net and scales. .Net does none of those things. .Net is a waste of time – a strategic distraction by MS and hosting such infomercials is a terrible dis-service to your readers.

  50. Nomad says:

    At first i thought, this would be some nice programming 101…but after going over this post i’m starting to doubt that.

    Here are some things you should consider when posting the next part of this:

    1. Don’t mess with the tabs! They are there for a reason: C# is one of those languages, which needs those brackets pretty much everywhere. If you mess with the tabbing the IDE does, people who don’t know C#, have to put time into understanding which open bracket belongs to a close bracket. Even i for myself was a bit confused when i saw the first code example here.

    2. Don’t make simple things complicated! You used Console.Out.WriteLine, and you could easily have used Console.Writeline…for a newbie less code means he has less to learn. And you don’t need to learn much with the simplest things ever.

    3. Don’t make simple things complicated! (I know it’s the same as 2) Why did you use Ctrl+F5 to run the Program? And why did you build it before that (And used CTRL+SHIFT+B)? There are some nice one-button-shortcuts for this! F6 will build the Project and F5 will run it. Oh and for purposes like learning a new language you don’t need to mess with building, because if you try to run the program with F5 it will be build automagically!

    PS:To all those “hackers” who are trolling around because they don’t like C#, .NET or whatsoever: Where is your problem? Did someone make you read this article against your will? The goal of such a series of tutorials is to show the people, who can’t do anything, how they can do something. And i wouldn’t even think about starting a tutorial about assembler targeted to people who know nothing about programming. And people who already know a programming language wouldn’t read tutorials, but start programming with the new language and look for the things they need.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 93,718 other followers