C# Programming Guide - Inside a C# Program 프로그래밍/C#2017. 5. 10. 15:51
- Inside a C# Program
- Hello World -- Your First Program
- General Structure of a C# Program
- C# Coding Conventions
https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/inside-a-program/
Inside a C# Program
The section discusses the general structure of a C# program, and includes the standard "Hello, World!" example.
In This Section
Related Sections
Hello World -- Your First Program
The following procedure creates a C# version of the traditional "Hello World!" program. The program displays the string Hello World!
For more examples of introductory concepts, see
.Note
Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see
.To create and run a console application
Start Visual Studio.
On the menu bar, choose File, New, Project.
The New Project dialog box opens.
Expand Installed, expand Templates, expand Visual C#, and then choose Console Application.
In the Name box, specify a name for your project, and then choose the OK button.
The new project appears in Solution Explorer.
If Program.cs isn't open in the Code Editor, open the shortcut menu for Program.cs in Solution Explorer, and then choose View Code.
Replace the contents of Program.cs with the following code.
C#// A Hello World! program in C#. using System; namespace HelloWorld { class Hello { static void Main() { Console.WriteLine("Hello World!"); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } }
Choose the F5 key to run the project. A Command Prompt window appears that contains the line
Hello World!
Next, the important parts of this program are examined.
Comments
The first line contains a comment. The characters //
convert the rest of the line to a comment.
// A Hello World! program in C#.
You can also comment out a block of text by enclosing it between the /*
and */
characters. This is shown in the following example.
/* A "Hello World!" program in C#.
This program displays the string "Hello World!" on the screen. */
Main Method
A C# console application must contain a Main
method, in which control starts and ends. The Main
method is where you create objects and execute other methods.
The Main
method is a method that resides inside a class or a struct. In the previous "Hello World!" example, it resides in a class named Hello
. You can declare the Main
method in one of the following ways:
It can return
void
.C#static void Main() { //... }
It can also return an integer.
C#static int Main() { //... return 0; }
With either of the return types, it can take arguments.
C#static void Main(string[] args) { //... }
-or-
C#static int Main(string[] args) { //... return 0; }
The parameter of the Main
method, args
, is a string
array that contains the command-line arguments used to invoke the program. Unlike in C++, the array does not include the name of the executable (exe) file.
For more information about how to use command-line arguments, see the examples in
and .The call to Main
method prevents the console window from closing before you have a chance to read the output when you run your program in debug mode, by pressing F5.
Input and Output
C# programs generally use the input/output services provided by the run-time library of the .NET Framework. The statement System.Console.WriteLine("Hello World!");
uses the method. This is one of the output methods of the class in the run-time library. It displays its string parameter on the standard output stream followed by a new line. Other methods are available for different input and output operations. If you include the using System;
directive at the beginning of the program, you can directly use the classes and methods without fully qualifying them. For example, you can call Console.WriteLine
instead of System.Console.WriteLine
:
using System;
Console.WriteLine("Hello World!");
For more information about input/output methods, see
.Command-Line Compilation and Execution
You can compile the "Hello World!" program by using the command line instead of the Visual Studio Integrated Development Environment (IDE).
To compile and run from a command prompt
Paste the code from the preceding procedure into any text editor, and then save the file as a text file. Name the file
Hello.cs
. C# source code files use the extension.cs
.Perform one of the following steps to open a command-prompt window:
In Windows 8, on the Start screen, search for
Developer Command Prompt
, and then tap or choose Developer Command Prompt for VS2012.A Developer Command Prompt window appears.
In Windows 7, open the Start menu, expand the folder for the current version of Visual Studio, open the shortcut menu for Visual Studio Tools, and then choose Developer Command Prompt for VS2012.
A Developer Command Prompt window appears.
Enable command-line builds from a standard Command Prompt window.
See
.
In the command-prompt window, navigate to the folder that contains your
Hello.cs
file.Enter the following command to compile
Hello.cs
.csc Hello.cs
If your program has no compilation errors, an executable file that is named
Hello.exe
is created.In the command-prompt window, enter the following command to run the program:
Hello
+
For more information about the C# compiler and its options, see
.General Structure of a C# Program
C# programs can consist of one or more files. Each file can contain zero or more namespaces. A namespace can contain types such as classes, structs, interfaces, enumerations, and delegates, in addition to other namespaces. The following is the skeleton of a C# program that contains all of these elements.
// A skeleton of a C# program
using System;
namespace YourNamespace
{
class YourClass
{
}
struct YourStruct
{
}
interface IYourInterface
{
}
delegate int YourDelegate();
enum YourEnum
{
}
namespace YourNestedNamespace
{
struct YourStruct
{
}
}
class YourMainClass
{
static void Main(string[] args)
{
//Your program starts here...
}
}
}
C# Coding Conventions
The does not define a coding standard. However, the guidelines in this topic are used by Microsoft to develop samples and documentation.
Coding conventions serve the following purposes:
They create a consistent look to the code, so that readers can focus on content, not layout.
They enable readers to understand the code more quickly by making assumptions based on previous experience.
They facilitate copying, changing, and maintaining the code.
They demonstrate C# best practices.
Naming Conventions
In short examples that do not include
, use namespace qualifications. If you know that a namespace is imported by default in a project, you do not have to fully qualify the names from that namespace. Qualified names can be broken after a dot (.) if they are too long for a single line, as shown in the following example.C#var currentPerformanceCounterCategory = new System.Diagnostics. PerformanceCounterCategory();
You do not have to change the names of objects that were created by using the Visual Studio designer tools to make them fit other guidelines.
Layout Conventions
Good layout uses formatting to emphasize the structure of your code and to make the code easier to read. Microsoft examples and samples conform to the following conventions:
Use the default Code Editor settings (smart indenting, four-character indents, tabs saved as spaces). For more information, see
.Write only one statement per line.
Write only one declaration per line.
If continuation lines are not indented automatically, indent them one tab stop (four spaces).
Add at least one blank line between method definitions and property definitions.
Use parentheses to make clauses in an expression apparent, as shown in the following code.
C#if ((val1 > val2) && (val1 > val3)) { // Take appropriate action. }
Commenting Conventions
Place the comment on a separate line, not at the end of a line of code.
Begin comment text with an uppercase letter.
End comment text with a period.
Insert one space between the comment delimiter (//) and the comment text, as shown in the following example.
C#// The following declaration creates a query. It does not run // the query.
Do not create formatted blocks of asterisks around comments.
Language Guidelines
The following sections describe practices that the C# team follows to prepare code examples and samples.
String Data Type
Use the
+
operator to concatenate short strings, as shown in the following code.C#string displayName = nameList[n].LastName + ", " + nameList[n].FirstName;
To append strings in loops, especially when you are working with large amounts of text, use a
object.C#var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala"; var manyPhrases = new StringBuilder(); for (var i = 0; i < 10000; i++) { manyPhrases.Append(phrase); } //Console.WriteLine("tra" + manyPhrases);
Implicitly Typed Local Variables
Use
for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.C#// When the type of a variable is clear from the context, use var // in the declaration. var var1 = "This is clearly a string."; var var2 = 27; var var3 = Convert.ToInt32(Console.ReadLine());
Do not use
when the type is not apparent from the right side of the assignment.C#// When the type of a variable is not clear from the context, use an // explicit type. int var4 = ExampleClass.ResultSoFar();
Do not rely on the variable name to specify the type of the variable. It might not be correct.
C#// Naming the following variable inputInt is misleading. // It is a string. var inputInt = Console.ReadLine(); Console.WriteLine(inputInt);
Avoid the use of
var
in place of .Use implicit typing to determine the type of the loop variable in
and loops.The following example uses implicit typing in a
for
statement.C#var syllable = "ha"; var laugh = ""; for (var i = 0; i < 10; i++) { laugh += syllable; Console.WriteLine(laugh); }
The following example uses implicit typing in a
foreach
statement.C#foreach (var ch in laugh) { if (ch == 'h') Console.Write("H"); else Console.Write(ch); } Console.WriteLine();
Unsigned Data Type
- In general, use
int
rather than unsigned types. The use ofint
is common throughout C#, and it is easier to interact with other libraries when you useint
.
Arrays
Use the concise syntax when you initialize arrays on the declaration line.
C#// Preferred syntax. Note that you cannot use var here instead of string[]. string[] vowels1 = { "a", "e", "i", "o", "u" }; // If you use explicit instantiation, you can use var. var vowels2 = new string[] { "a", "e", "i", "o", "u" }; // If you specify an array size, you must initialize the elements one at a time. var vowels3 = new string[5]; vowels3[0] = "a"; vowels3[1] = "e"; // And so on.
Delegates
Use the concise syntax to create instances of a delegate type.
C#// First, in class Program, define the delegate type and a method that // has a matching signature. // Define the type. public delegate void Del(string message); // Define a method that has a matching signature. public static void DelMethod(string str) { Console.WriteLine("DelMethod argument: {0}", str); }
C#// In the Main method, create an instance of Del. // Preferred: Create an instance of Del by using condensed syntax. Del exampleDel2 = DelMethod; // The following declaration uses the full syntax. Del exampleDel1 = new Del(DelMethod);
try-catch and using Statements in Exception Handling
Use a
statement for most exception handling.C#static string GetValueFromArray(string[] array, int index) { try { return array[index]; } catch (System.IndexOutOfRangeException ex) { Console.WriteLine("Index is out of range: {0}", index); throw; } }
Simplify your code by using the C#
. If you have a statement in which the only code in thefinally
block is a call to the method, use ausing
statement instead.C#// This try-finally statement only calls Dispose in the finally block. Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) { ((IDisposable)font1).Dispose(); } } // You can do the same thing with a using statement. using (Font font2 = new Font("Arial", 10.0f)) { byte charset = font2.GdiCharSet; }
&& and || Operators
To avoid exceptions and increase performance by skipping unnecessary comparisons, use
instead of and instead of when you perform comparisons, as shown in the following example.C#Console.Write("Enter a dividend: "); var dividend = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter a divisor: "); var divisor = Convert.ToInt32(Console.ReadLine()); // If the divisor is 0, the second clause in the following condition // causes a run-time error. The && operator short circuits when the // first expression is false. That is, it does not evaluate the // second expression. The & operator evaluates both, and causes // a run-time error when divisor is 0. if ((divisor != 0) && (dividend / divisor > 0)) { Console.WriteLine("Quotient: {0}", dividend / divisor); } else { Console.WriteLine("Attempted division by 0 ends up here."); }
New Operator
Use the concise form of object instantiation, with implicit typing, as shown in the following declaration.
C#var instance1 = new ExampleClass();
The previous line is equivalent to the following declaration.
C#ExampleClass instance2 = new ExampleClass();
Use object initializers to simplify object creation.
C#// Object initializer. var instance3 = new ExampleClass { Name = "Desktop", ID = 37414, Location = "Redmond", Age = 2.3 }; // Default constructor and assignment statements. var instance4 = new ExampleClass(); instance4.Name = "Desktop"; instance4.ID = 37414; instance4.Location = "Redmond"; instance4.Age = 2.3;
Event Handling
If you are defining an event handler that you do not need to remove later, use a lambda expression.
C#public Form2() { // You can use a lambda expression to define an event handler. this.Click += (s, e) => { MessageBox.Show( ((MouseEventArgs)e).Location.ToString()); }; }
C#// Using a lambda expression shortens the following traditional definition. public Form1() { this.Click += new EventHandler(Form1_Click); } void Form1_Click(object sender, EventArgs e) { MessageBox.Show(((MouseEventArgs)e).Location.ToString()); }
Static Members
- Call members by using the class name: ClassName.StaticMember. This practice makes code more readable by making static access clear. Do not qualify a static member defined in a base class with the name of a derived class. While that code compiles, the code readability is misleading, and the code may break in the future if you add a static member with the same name to the derived class.
LINQ Queries
Use meaningful names for query variables. The following example uses
seattleCustomers
for customers who are located in Seattle.C#var seattleCustomers = from cust in customers where cust.City == "Seattle" select cust.Name;
Use aliases to make sure that property names of anonymous types are correctly capitalized, using Pascal casing.
C#var localDistributors = from customer in customers join distributor in distributors on customer.City equals distributor.City select new { Customer = customer, Distributor = distributor };
Rename properties when the property names in the result would be ambiguous. For example, if your query returns a customer name and a distributor ID, instead of leaving them as
Name
andID
in the result, rename them to clarify thatName
is the name of a customer, andID
is the ID of a distributor.C#var localDistributors2 = from cust in customers join dist in distributors on cust.City equals dist.City select new { CustomerName = cust.Name, DistributorID = dist.ID };
Use implicit typing in the declaration of query variables and range variables.
C#var seattleCustomers = from cust in customers where cust.City == "Seattle" select cust.Name;
Align query clauses under the
clause, as shown in the previous examples.Use
clauses before other query clauses to ensure that later query clauses operate on the reduced, filtered set of data.C#var seattleCustomers2 = from cust in customers where cust.City == "Seattle" orderby cust.Name select cust;
Use multiple
from
clauses instead of a clause to access inner collections. For example, a collection ofStudent
objects might each contain a collection of test scores. When the following query is executed, it returns each score that is over 90, along with the last name of the student who received the score.C#// Use a compound from to access the inner sequence within each element. var scoreQuery = from student in students from score in student.Scores where score > 90 select new { Last = student.LastName, score };
'프로그래밍 > C#' 카테고리의 다른 글
C# Programming Guide - Strings (0) | 2017.05.10 |
---|---|
C# Programming Guide - Types (0) | 2017.05.10 |
C# Programming Guide - Statements, Expressions, and Operators (0) | 2017.05.10 |
C# Programming Guide - Arrays (0) | 2017.05.09 |
Tuple Class (0) | 2017.05.08 |