My latest unity game project has gotten to the point where my minimal understanding of C# is a major issue so this is my attempt at addressing it Mainly referenced (and in some cases directly copy-pasted) from https://learn.microsoft.com/en-us/dotnet/csharp/.
C# is a strongly typed language (although I've seen some discourse complaining about this terminology being inexact/misguided?) meaning every declared variable has a known type at compile time. Types are broadly split into value and reference types - a variable of a value type contains an instance of the type. This differs from a variable of a reference type which contains a reference to an instance of the type. Some examples of value types are int
, double
, bool
and some reference types are string
, array
and list
.
You can also create your own types like struct
types for values or class
types that define object-oriented behvaior. You can also define generic types and methods that use type parameters to provide a placeholder for an actual type.
Methods are members of struct
and class
types that define behavior of types. Methods can be overloaded with different numbers or types of parameters.
C# types can have properties which are data elements backed by functions called accessors. C# types can define events, which allow a type to notify subscribers of important actions. C# also supports object-oriented techniques like inheritance and polymorphism for class types.
Language integrated query (LINQ) is a syntax that can query or transform a collection of data. It works with XML, JSON and many other collections.
C# provides pattern matching which can inspect data and make decisions based on its characteristics. Below is an example of how a 'Xor' logic function could be structured:
public static bool Xor(bool left, bool right) =>
(left, right) switch
{
(true, true) => false,
(true, false) => true,
(false, true) => true,
(false, false) => false,
};
Every variable, constant and expression has a type in C#. Every method declaration has a return value and specifies type and kind - value, reference or output, for each parameter passed to it. The compiler makes sure that all performed operations are type safe - it will throw an error if an inappropriate operation is performed on a type, such as attempting to add an int to a bool type.
When declaring a variable you can either explicitly state the type or use the var
keyword to let the compiler infer the type. The complete list of built-in types can be seen here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/built-in-types.
You can use struct, class, interface, enum and record constructs to create custom types. There are two very important points about the .NET type system:
int
derive somewhere up the chain from System.Object. This unified hierarchy is called the Common Type System (CTS).