A multi-paradigm and general-purpose C# is a programming language that ranges over static typing, strong typing, and declarative, functional, object-oriented, component-oriented, and generic programming disciplines. The modern programming language is mainly used for Windows and can be utilized for different tasks and on open source platforms.

C# is a fairly easy language for beginners and can be easily learned if you have basic knowledge of computers, object-oriented languages, or other C# basic knowledge. It can be used for both front-end and back-end development with .NET. It is a great marketable language and is highly in demand. Here is a C# cheat sheet to help you learn more about the language.

C# Cheat Sheet for Beginners

Declaring Variables

The syntax for variables in C# is that you first specify the data type followed by variable name and value:

<datatype> <variablename> = <initialvalue>;

The rules are:

  • Variables always start with an underscore or a letter.
  • Variables can not contain white spaces.
  • Variables should always start with a capital letter.
  • It can contain numbers.
  • Variables can not contain any symbols except underscore.

Examples for declaring a variable:

string Name = "exampleofvariable";
int Date = 22 December;

Declaring Arrays:

Arrays are data structures that are similar to variables. However, they can hold more than a single value.

The syntax for declaring arrays:

DataType[ ] ArrayName = { Values Separated By Commas } // Can contain array of any size
DataType[] ArrayName = new DataType[6] {Command Separated Values } // Array for 6 Data Values

Example of an Array:

String[] DeclareArrayNo12 = {"FirstArray", "Example1"}; string[]

Naming Conventions in C#

Here is how conventions are named in C# with examples.

Class: For naming a class, PascalClass is always used, which means the first letter of each word is capitalized. Mostly, nouns and pronouns are used to name classes, and underscores are not used. Also, do not give prefixes.

Example:

FirstSalary

Method: PascalClass is used for naming methods, and a maximum of 7 parameters are allowed while naming a class.

Example:

NewCar

Local variables and Arguments: Local variables and method arguments are always named using camelCase, which means the first letter of the first word is in lowercase, while the first letter of all other words is in a capital case. Hungarian notations are not used while naming local variables. Additionally, abbreviations for words or underscores are not used when naming local variables or method arguments.

Example:

firstName

Private variable: camelCase is used when naming a private variable, and abbreviations can be used while naming.

Example:

avgMarks

Public Variable: For naming a public variable, PascalCase is always used.

Example:

NewVariable

Constant: If the constant in consideration is exposed from a class publicly, PascalCase is used. On the other hand, if the constant is private to a function or a sub, camelCase is used.

Example:

Multiplication

Data Types Used in C#

Int Integer values like 1234, 10000
Double 64-bit floating-point, 6.145644
Float Floating point number, 7.1454
String Set of characters, “Hello.”
Byte 8bit unsigned integer
Char 16 bit Unicode character, ‘Z.’
Long 64 bit signed integer, -7.0789
Decimal High precision decimal numbers
Bool True or false Boolean value
Enums Value data type contains its value
Struct value type that is used to represent a record

Numbers

Numbers can be written in integer and floating types.

Integer type:

int can store size up to 4 bytes and can store whole numbers from -2,147,483,648 to 2,147,483,647.

Example:

int myNum = 100000;
Console.WriteLine(myNum);

long can store numbers up to 8 bytes and hence stores numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Example:

long myNum = 15000000000L;
Console.WriteLine(myNum);

Floating type:

float supports 6 to 7 decimal digits of 4 bytes.

Example:

float myNum = 6.89F;
Console.WriteLine(myNum);

double stores up to 15 decimal points and can store 8 bytes.

Example: double myNum = 18.90D;
Console.WriteLine(myNum);

In scientific numbers, ‘e’ can be used to present the power of 10.

Example:

float f1 = 35e3F;
double d1 = 12E4D;
Console.WriteLine(f1);
Console.WriteLine(d1);

Booleans

A bool data type can only hold the value ‘true’ or ‘false’ and is declared using ‘bool.’ These values are used for conditional testing.

Example:

bool thisIsFun = true;
bool thisIsBoring = false;
Console.WriteLine(thisIsFun); // Output will be True
Console.WriteLine(thisIsBoring); // Output will be False

Characters

A single character can be declared using ‘char’. The given character is enclosed in single quotes, like ‘Z’ or ‘a’.

Example:

char sectionNo = 'h';
Console.WriteLine(sectionNo);

Strings

Strings are used for declaring a text or a string of characters and are done using ‘string’ data type. Strings are always enclosed in double quotes ( ” ” ).

Example:

string greeting = "Hello Coders";
Console.WriteLine();

Conditional statements

If statements

The if statement is used in conditions where the condition must be true for the execution of the code.

Syntax:

if (true)
{
}
Example: if (Year > 2010)
{
Console.WriteLine("Hello 2010s!");
}

If else statement

If-else statements are used in the case of conditions where the condition for the if statements do not prove to be true, and hence the else statement code is executed.

Example:

if (Year > 2010)
{
Console.WriteLine("Hello 2010s!");
}
else
{
Console.WriteLine("Year is: " + Year);
}

Switch Statements

Much easier and cleaner to read, maintain and nested using if-else, Switch statements only evaluate one variable. Still, it is similar to the if-else statement.

Syntax:

switch (switch_on)
{
default:
}
Example:
switch (Rollno)
{
case 1301 :
Console.WriteLine("It's 1301!");
break;
case 1302 :
Console.WriteLine("It's 1302!");
break;
default :
Console.WriteLine("It's " + Rollno + "!");
break;
}

The break keyword stops the case from falling.

Loops

While loop

The while loop loops the code continuously until the condition becomes false.

Syntax:

while (true)
{
}
Example
while (Year >= 2013)
{
if (Year != 2100)
{
Console.WriteLine(Year++);
}
else
{
break;
}
}

It is important that you set the code to evaluate false at some time, or else the code will execute endlessly, resulting in errors.

For Loop

The for loop is like the while loop, but here you can specify when you want the loop to end.

Syntax:

for (int i = 0; i < length; i++)
{
}
Example:
for (int i = 0; i <= 100; i++)
{ Console.WriteLine(i);
}

Hence, the code will print the numbers from 1 to 100 until the code is true. “I” will be incremented after every execution, and hence the code will execute from i=1 to i=100. However, once the increment value reaches 101, the condition will turn false because “I” will not be <= 100, and hence the execution will stop.

For Each

The loop is used to loop around a collection of values as in arrays.

Syntax:

foreach (var item in collection)
{
}
Example:
foreach (string movie in MyGradesIn2020)
{
Console.WriteLine(grades);
}

The code will then print all the values in the MyGradesIn2020 array.

 

Modifiers

Modifiers are pretty useful when using the concepts of classes and inheritance.  They are keywords used to modify the declaration of types like class, struct, etc., and type members like fields, properties, indexers, etc.

Below are some of the most important modifiers that you will frequently use as a C# programmer.

  • Public: This allows a field or function to be accessible by any other code present in the same or different assembly which references the public field.
  • Private: This allows a field to be only accessible by the piece of code present in the same class or structure.
  • Protected: Any protected piece of code is only accessible by that same class or any other class that is derived (inherited) from the protected class.
  • Internal: This allows the field to be accessible by the code present in the same assembly. Any code from other assemblies won’t be able to access it.
  • Protected Internal: This field will be accessible by the code present in the same assembly. Any code from another assembly will be able to access it only if there is a derived class present in that other assembly.
  • Abstract: If a class is intended to only act as a base class of other classes, we use abstract modifiers. An abstract class has to be extended by other classes.
  • Async: Used to indicate an asynchronous modified method, lambda expression, or anonymous method.

Important String Operations

Strings are one of the most used data types in any programming language. You should know the use of the string operations given below.

Clone(): It is used to make the clone of a string and store it in another string.

E.g. String2 = String1.Clone()

CompareTo(): It is used to compare whether two strings are equal. If they are equal, the function returns 0, else it returns 1.

E.g. String2.CompareTo(String1)

Contains(): This is used to check whether a specific character or a substring is present in the given string.

E.g. String.Contains(“program”)

EndsWith(): To see whether the given string ends with a specific character or substring or not.

E.g. String.EndsWith(“am”)

GetHashCode(): used to return the hashcode of a given string.

E.g. String.GetHashCode()

IndexOf(): Returns the index location of a character. If the same character is located in the string multiple times, it returns the first occurrence of the given character.

E.g. String.IndexOf(“l”)

ToLower(): Used to change the given character or string to lowercase letters.

E.g. String.ToLower()

ToUpper(): Used to change the given character or string to uppercase letters.

E.g. String.ToUpper()