Programming/C Sharp

From Dev Wiki
< Programming
Revision as of 10:10, 6 May 2020 by Brodriguez (talk | contribs) (Add if statements)
Jump to navigation Jump to search

C# is a higher level version of C. It was designed by Microsoft, and for the longest time, was generally only supported on Windows.

It's used often in large, enterprise/business scale projects, due to having solid scaffolding for enforcing consistency through the project, which allows many people to work on a given project with less maintenance overhead. This is accomplished via things like required strong typing and good support for the interface class structure.

Comments

Inline Comments

// This is an inline comment.

Block Comments

Because there is minimal difference in C# between inline and block comments, these are really only useful when declared above a class or function declaration line.

This is because C# knows to treat this as documentation and adds special logic around it. For example, hovering over a class instantiation will display the block comment data for that class.

/// This is a block comment.
/// Comment line 2.
/// Another block comment line.

Block/Region Declaration

Regions are used for organizational purposes, and allow for code folding at the click of a button. To be useful, both the start and end must be declared.

#region MyRegionName
 
...
 
#endregion MyRegionName

Variables

Variables are strongly typed in C#. That means that you must declare the type (bool, int, string, etc) as well as the variable name.

Variable Definition

bool a_bool = true;
bool b_bool = false;
string my_var_1 = "This is ";
string my_var_2 = "a string.";

Variable Usage

Console.WriteLine("Printing variable values.");
Console.WriteLine(a_bool);
Console.WriteLine(b_bool);
Console.WriteLine(my_var_1 + my_var_2);

Variable Casting

Variables will be treated as the originally indicated type until a cast statement is used.

For example, to convert a boolean to an int, use:

bool a_bool = true;
int converted_bool = Convert.ToInt32(a_bool);

If Statements

Basic If

if (x == y)
{
    // Logic if true.
}

Full If

if (x == y)
{
    // Logic if true.
} else if ( x && (y || z) )
{
    // Logic for "else if" true.
} else
{
    // Logic for false.
}

Switch/Case Statements

switch (my_var)
{
    case "1":
        // Logic for case value of "1".
        break;
    case "a":
        // Logic for case value of "a".
        break;
    case "test":
        // Logic for case value of "test".
        break;
    default:
        // Logic for no match.
        break;
}