Programming/C Sharp: Difference between revisions

From Dev Wiki
Jump to navigation Jump to search
(Add class section)
m (Minor formatting)
Line 2: Line 2:


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.
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 ==
== Comments ==
Line 25: Line 26:
   
   
  #endregion MyRegionName
  #endregion MyRegionName


== Variables ==
== Variables ==
Line 47: Line 49:
  bool a_bool = true;
  bool a_bool = true;
  int converted_bool = Convert.ToInt32(a_bool);
  int converted_bool = Convert.ToInt32(a_bool);


== If Statements ==
== If Statements ==
Line 84: Line 87:
         break;
         break;
  }
  }


== Classes ==
== Classes ==

Revision as of 10:54, 6 May 2020

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;
}


Classes

Classes are generally defined in new, separate files. A good rule of thumb is to only include multiple classes in one file if they are nested, inner subclasses within the first class.

Note that in C#, class variables and methods are often called with this.<value>, to help differentiate between local and class level values. However, this is optional and will not always be followed.

Class Variables

To declare class level variables, declare the variable name and type in the class, but don't assign to it.

For organization, it's recommended to do this at the very top of the class, and enclose it within a region.

class MyClass
{
    #region Variables
     
    bool test_bool;
    int test_int;
    string test_string;
     
    #endregion Variables
     
    ...
}

Constructor

A constructor is essentially the logic that's ran on class instantiation.

To declare a constructor, declare a method with the same name as the class and public accessibility.

If your class needs to be able to handle multiple possible sets of passed arguments, then create one constructor for each.

For example, this is a constructor for a class that takes 0 arguments.

class MyClass
{
    ...
     
    public MyClass()
    {
         // Constructor logic here.
    }
     
    ...
}

Properties

Properties are a "safer" way to read (get) and update (set) class variables.

Effectively, properties are functions that handle a single variable, and allow for custom logic to clean/validate your variable before saving it to the class or returning it for use outside of the class.

Minimum property syntax (to both set and get) is as follows:

class MyClass
{
    #region Variables
     
    string test_string;
     
    #endregion Variables
     
    ...
     
    public string TestString
    {
        get { return this.test_string; }
        set { this.test_string = value; }
    }
     
    ...
}

If we want to expand this to show how it can be useful, we can validate our value first.

class MyClass
{
    #region Variables
     
    string test_string;
     
    #endregion Variables
     
    ...
     
    public string TestString
    {
        get
        {
            // First check if our string is a known bad value.
            if (this.test_string == "I'm an invalid value, ohno!")
            {
                // Invalid value detected! Return something else as a fallback.
                return "Default string value."
            } else
            {
                // If we got here, then the string is valid. Return that.
                return this.test_string;
            }
        }
        set
        {
            // Check if our provided value is valid before setting.
            // In this case, we simply make sure it's 3 characters or greater.
            if (this.test_string.length > 2)
            {
                this.test_string = value;
            }
        }
    }
     
    ...
}

Class Functions

Class functions are declared and handled the same way as any other C# function. See functions section.