c# Programming
c# Programming
Inside a C# Program
Hello World -- Your First Program
General Structure of a C# Program
Identifier names
C# Coding Conventions
Inside a C# program
8/19/2019 • 2 minutes to read • Edit Online
The section discusses the general structure of a C# program, and includes the standard "Hello, World!" example.
In this section
Hello World -- Your First Program
General Structure of a C# Program
Identifier names
C# Coding Conventions
Related sections
Getting Started with C#
C# Programming Guide
C# Reference
Samples and tutorials
C# language specification
For more information, see the C# Language Specification. The language specification is the definitive source for C#
syntax and usage.
See also
C# Programming Guide
Hello World -- Your first program
9/14/2019 • 4 minutes to read • Edit Online
In this article, you'll use Visual Studio to create the traditional "Hello World!" program. Visual Studio is a
professional Integrated Development Environment (IDE ) with many features designed for .NET development.
You'll use only a few of the features in Visual Studio to create this program. To learn more about Visual Studio, see
Getting Started with Visual C# and Visual Basic.
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 Personalizing the IDE.
Select Create a new project in the lower right corner of the image. Visual Studio displays the New Project
dialog:
NOTE
If this is the first time you've started Visual Studio, the Recent project templates list is empty.
On the new project dialog, choose "Console App (.NET Core)" and then press Next. Give your project a name,
such as "HelloWorld", then press Create.
Visual Studio opens your project. It's already a basic "Hello World!" example. Press Ctrl + F5 to run your
project. Visual Studio builds your project, converting the source code into an executable. Then, it launches a
command window that runs your new application. You should see the following text in the window:
Hello World!
Elements of a C# program
Let's examine the important parts of this program. The first line contains a comment. The characters // convert
the rest of the line to a comment.
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. */
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 static 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 . That means your program doesn't return a value.
It can also return an integer. The integer is the exit code for your application.
-or-
The parameter of the Main method, args , is a string array that contains the command-line arguments used to
invoke the program.
For more information about how to use command-line arguments, see the examples in Main() and Command-Line
Arguments.
Console.WriteLine("Hello World!");
See also
C# Programming Guide
Samples and tutorials
Main() and Command-Line Arguments
Getting Started with Visual C# and Visual Basic
General Structure of a C# Program (C# Programming
Guide)
8/19/2019 • 2 minutes to read • Edit Online
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
{
}
enum YourEnum
{
}
namespace YourNestedNamespace
{
struct YourStruct
{
}
}
class YourMainClass
{
static void Main(string[] args)
{
//Your program starts here...
}
}
}
Related Sections
For more information:
Classes
Structs
Namespaces
Interfaces
Delegates
C# Language Specification
For more information, see Basic concepts in the C# Language Specification. The language specification is the
definitive source for C# syntax and usage.
See also
C# Programming Guide
Inside a C# Program
C# Reference
Identifier names
8/19/2019 • 2 minutes to read • Edit Online
An identifier is the name you assign to a type (class, interface, struct, delegate, or enum), member, variable, or
namespace. Valid identifiers must follow these rules:
Identifiers must start with a letter, or _ .
Identifiers may contain Unicode letter characters, decimal digit characters, Unicode connecting characters,
Unicode combining characters, or Unicode formatting characters. For more information on Unicode categories,
see the Unicode Category Database. You can declare identifiers that match C# keywords by using the @ prefix
on the identifier. The @ is not part of the identifier name. For example, @if declares an identifier named if .
These verbatim identifiers are primarily for interoperability with identifiers declared in other languages.
For a complete definition of valid identifiers, see the Identifiers topic in the C# Language Specification.
Naming conventions
In addition to the rules, there are a number of identifier naming conventions used throughout the .NET APIs. By
convention, C# programs use PascalCase for type names, namespaces, and all public members. In addition, the
following conventions are common:
Interface names start with a capital I .
Attribute types end with the word Attribute .
Enum types use a singular noun for non-flags, and a plural noun for flags.
Identifiers should not contain two consecutive _ characters. Those names are reserved for compiler generated
identifiers.
C# Language Specification
For more information, see the C# Language Specification. The language specification is the definitive source for C#
syntax and usage.
See also
C# Programming Guide
Inside a C# Program
C# Reference
Classes
Structs
Namespaces
Interfaces
Delegates
C# Coding Conventions (C# Programming Guide)
8/19/2019 • 8 minutes to read • Edit Online
Naming Conventions
In short examples that do not include using directives, 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.
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 Options, Text Editor, C#, Formatting.
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.
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.
Language Guidelines
The following sections describe practices that the C# team follows to prepare code examples and samples.
String Data Type
Use string interpolation to concatenate short strings, as shown in the following code.
To append strings in loops, especially when you are working with large amounts of text, use a StringBuilder
object.
// 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 var when the type is not apparent from the right side of the assignment.
// 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.
// Naming the following variable inputInt is misleading.
// It is a string.
var inputInt = Console.ReadLine();
Console.WriteLine(inputInt);
// Preferred syntax. Note that you cannot use var here instead of string[].
string[] vowels1 = { "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.
// First, in class Program, define the delegate type and a method that
// has a matching signature.
Simplify your code by using the C# using statement. If you have a try-finally statement in which the only
code in the finally block is a call to the Dispose method, use a using statement instead.
New Operator
Use the concise form of object instantiation, with implicit typing, as shown in the following declaration.
// Object initializer.
var instance3 = new ExampleClass { Name = "Desktop", ID = 37414,
Location = "Redmond", Age = 2.3 };
Event Handling
If you are defining an event handler that you do not need to remove later, use a lambda expression.
public Form2()
{
// You can use a lambda expression to define an event handler.
this.Click += (s, e) =>
{
MessageBox.Show(
((MouseEventArgs)e).Location.ToString());
};
}
Static Members
Call static 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.
Use aliases to make sure that property names of anonymous types are correctly capitalized, using Pascal
casing.
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 and ID in the result,
rename them to clarify that Name is the name of a customer, and ID is the ID of a distributor.
var localDistributors2 =
from customer in customers
join distributor in distributors on customer.City equals distributor.City
select new { CustomerName = customer.Name, DistributorID = distributor.ID };
Use implicit typing in the declaration of query variables and range variables.
var seattleCustomers = from customer in customers
where customer.City == "Seattle"
select customer.Name;
Align query clauses under the from clause, as shown in the previous examples.
Use where clauses before other query clauses to ensure that later query clauses operate on the reduced,
filtered set of data.
Use multiple from clauses instead of a join clause to access inner collections. For example, a collection of
Student 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.
// 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 };
Security
Follow the guidelines in Secure Coding Guidelines.
See also
Visual Basic Coding Conventions
Secure Coding Guidelines