90 likes | 106 Views
Learn how to write a basic C# application in this tutorial. We will cover the comment class definition, method usage, and using the System.Console class to display text on the console.
E N D
CSC 298 Writing a C# application
A first C# application comment class definition class method use the System.Console class to write some text to the console every C# statement ends with a semi colon ; // Display Hello, world on the screen public class HelloWorld { public static void Main() { System.Console.WriteLine("Hello, world") ; } }
Code organization • In C# (as in Java), no stand alone function • Code is written inside of blocks {} that are class definitions • public class HelloWorld { // my code is here … } • for now always write public class. More on this later • Good habits from Java (not required in C#) • Name the file that contains the definition of the public class HelloWorld: HelloWorld.cs • Write only onepublic class per C# file
Comments • Ignored by the computer. Essential for the reader. • 2 types of comments: // and /* */ • Everything between // and the end of the line is a comment • Everything between /* and */ is a comment. It can be used on several lines. You can't nest these comments (/* blabla /* blabla */ blabla */ gives an error) • Examples • // this is a comment • /* this is a comment that can be written on several lines */ • Also XML comments /// (see VS.NET doc)
The Main method • An application always start executing with the Main method (note the capital M) • The Main method must be static • It can be of type void or return an int • It can take no arguments or an array of strings • It can be of any visibility (public, private…) • public static int Main() • static void Main(String[] args) • // default to private
Console Input/Output in C# • Console: a class to access I/O functionalities for the console (=DOS window) • In: input stream, Out: output stream • important static methods: • Write, WriteLine, ReadLine • Console is available in the namespace System Console.Write ("Enter your name: ");String name = Console.ReadLine();Console.WriteLine("Welcome " + name);
System.Windows.Forms • A namespace that contains many classes to build graphical user interfaces • We will see many examples • Here is a simple example MessageBox.Show("Hello, world!", "Message");
The using statement • Define a shortcut to write the names of classes of the FCL in our programs. • using System.Windows.Forms means: • get access to all of the classes in the namespace System.Windows.Forms • In the program, to access the class • System.Windows.Forms.MessageBox just type • MessageBox
Formatting output • To concatenate strings (=sequence of characters), use + • Write("Hello, " + "World") prints • Hello, World • Write(""+1+2) is not the same as Write(1+2). Why? • For tabs and newlines, use '\t' and '\n' • Write("Hello\tWorld") prints Hello World • Write("Hello\nWorld") prints • Hello • World • See later for other ways