Show Menu
Cheatography

C# Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Create, run, debug programs from scratch

View>T­erminal
dotnet new console
Creates new Hello World program from scratch
dotnet restore
resolve .NET build assets
dotnet run
Run the program
Debugging
Debug> .NET Core Launch (Console)
Click line, add red dot (break­point), F5(run), local variables on left
Compiling
 
csc hello.cs

New Class

File MyClass.cs
Inside:
using System;
namespace SameAsMains{
classMyClass{
//...}
Reference MyClass in another class
MyClass c1 = new MyClass();
 
c1.fun­cti­on();

C#

C# is an object­-or­iented language, but C# further includes support for compon­ent­-or­iented progra­mming.
All C# types, including primitive types such as int and double, inherit from a single root object type.
C# supports both user-d­efined reference types and value types
The "­Hello, World" program starts with a using directive that references the System namespace.
Namespaces provide a hierar­chical means of organizing C# programs and libraries. Namespaces contain types and other namesp­ace­s—for example, the System namespace contains a number of types, such as the Console class referenced in the program, and a number of other namesp­aces, such as IO and Collec­tions.
A using directive that references a given namespace enables unqual­ified use of the types that are members of that namespace. Because of the using directive, the program can use Consol­e.W­rit­eLine as shorthand for System.Co­nso­le.W­ri­teLine.
While instance methods can reference a particular enclosing object instance using the keyword this, static methods operate without reference to a particular object.
short x = 2, y = 3 will make x a short and y an int

Types

string
Length (str.L­ength)
Enum
The enum keyword is used to declare an enumer­ation, a distinct type that consists of a set of named constants called the enumerator list.
 
By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example, in the following enumer­ation, Sat is 0, Sun is 1, Mon is 2, and so forth.
 
enum Day {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
 
Enumer­ators can use initia­lizers to override the default values, as shown in the following example.
 
enum Day {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
 
Every enumer­ation type has an underlying type, which can be any integral numeric type. The char type cannot be an underlying type of an enum. The default underlying type of enumer­ation elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type, as shown in the following example.
 
enum Day : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
 
an explicit cast is necessary to convert from enum type to an integral type.
 
int x = (int)D­ay.Sun;
Enteros con signo
sbyte, short, int, long
Enteros sin signo
byte, ushort, ulong, uint
FLoating point
float, double
float and double
binary point, not 100% accurate
decimal
decimal, as accurate as you can get
Value types
Simple
todos los anteriores y bool
Enumer­ación
enum e {}
Estructura
struct S {}
 
Reference types
Class types
object, string, class C{}
Interface types
interface I {}
Tipos de matroz
int[]¸­int[,]
Delegate types
delegate int D{}

Input and Output

Print line
System.Co­nso­le.W­ri­teL­ine()
 
System.Co­nso­le.W­rite()
Format string ($)
Consol­e.W­rit­eLi­ne(­$"Hello World! {c1.re­tur­nMe­ssa­ge(­)}");
Read line (string)
Consol­e.R­ead­Line();
Read char
Consol­e.R­ead­Key­().K­ey­Char;
Read Int
int n = int.Pa­rse­(Co­nso­le.R­ea­dLi­ne());
Read float

Data Structures and Collec­tions

Array
create and initialize
String[] Words = new String­[10];
create, initialize and fill
int[] prueba = new int[20­]{1­,2,­3,4­,5,­6,7­,8,­9,1­0,1­1,1­2,1­3,1­4,1­5,1­6,1­7,1­8,1­9,20};
int[] vector = {1,2,4}
access values
save values
array (multi­dim­ens­ional)
create and initialize
create, initialize and fill
access values
save values
get size
.Length
List
create and initialize
var names = new List<s­tri­ng> { "­<na­me>­", "­Ana­", "­Fel­ipe­" };
add to the end of the list
names.A­dd­("Ma­ria­");
remove from the end
names.R­em­ove­("An­a");
access
Consol­e.W­rit­eLi­ne(­$"My name is {names­[0]­}.");
length
Consol­e.W­rit­eLi­ne(­$"The list has {names.Count} people in it");
indexOf
var index = names.I­nd­exO­f("F­eli­pe");
Sort
names.S­ort();
Add new values from array to list
n3.Add­Ran­ge(n1);
Dictio­nar­y<T­Key­,TV­alu­e>
Tkey : The type of the keys in the dictio­nary.
The type of the values in the dictio­nary.
Declare Dictionary with String key and value
Dictio­nar­y<s­tring, string> openWith = new Dictio­nar­y<s­tring, string­>();
Declare and initialize DIctionary
var myDict = new Dictio­nar­y<s­tring, string> { { "­key­1", "­val­ue1­" }, { "­key­2", "­val­ue2­" } };
Add values to Dictionary
openWi­th.A­dd­("tx­t", "­not­epa­d.e­xe");
 
// The Add method throws an exception if the new key is // already in the dictio­nary.
Retrieve values from Dictionary
String program = openWi­th[­"­txt­"];
Check if value in Dictionary exists
if (openW­ith.Tr­yGe­tVa­lue­("ti­f", out value)) { Consol­e.W­rit­eLi­ne(­"For key = \"ti­f\", value = {0}.", value); } else { Consol­e.W­rit­eLi­ne(­"Key = \"ti­f\" is not found."­); }
List
Declare and initialize Object List
List<P­et> petsList = new List<P­et>{ new Pet { Name="B­arl­ey", Age=8.3 }, new Pet { Name="B­oot­s", Age=4.9 }, new Pet { Name="W­his­ker­s", Age=1.5 }, new Pet { Name="D­ais­y", Age=4.3 } };

Scope

this, ref, out, in, return, attrib­utes, propertoes
Keywords
ref
if the caller passes a local variable expression or an array element access expres­sion, and the called method replaces the object to which the ref parameter refers, then the caller’s local variable or the array element now refers to the new object when the method returns
 
When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value.
any operation on the parameter is made on the argument
 
void Method(ref int refArg­ument) { refArg­ument = refArg­ument + 44; } int number = 1; Method(ref number); Consol­e.W­rit­eLi­ne(­num­ber); // Output: 45
out
arguments are parsed by reference. any operation on the parameter is made on the argument. It is like the ref keyword, except that ref requires that the variable be initia­lized before it is passed. It is also like the in keyword, except that in does not allow the called method to modify the argument value.
 
It is like the ref keyword, except that ref requires that the variable be initia­lized before it is passed. It is also like the in keyword, except that in does not allow the called method to modify the argument value
in
The in keyword causes arguments to be passed by reference. It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument. It is like the ref or out keywords, except that in arguments cannot be modified by the called method. Whereas ref arguments may be modified, out arguments must be modified by the called method, and those modifi­cations are observable in the calling context.
 
the in modifier is usually unnece­ssary at the call site. It is only required in the method declar­ation.
A parameter is a variable in a method defini­tion.

When a method is called, the arguments are the data you pass into the method's parame­ters.

Parameter is variable in the declar­ation of function.

Argument is the actual value of this variable that gets passed to function.

Hierarchy

 

Concepts

assembly
An assembly is a file that is automa­tically generated by the compiler upon successful compil­ation of every .NET applic­ation. It can be either a Dynamic Link Library or an executable file. It is generated only once for an applic­ation and upon each subsequent compil­ation the assembly gets updated.
"­Flujo base e interm­edi­o"
Library
ensemble of functions
Struct and Class
Classes and structs are two of the basic constructs of the common type system in the .NET Framework. Each is essent­ially a data structure that encaps­ulates a set of data and behaviors that belong together as a logical unit. The data and behaviors are the members of the class or struct, and they include its methods, proper­ties, and events, and so on.
 
A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data. A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.
 
In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
Delegates
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instan­tiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance. Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs. The following example shows a delegate declar­ation: public delegate int Perfor­mCa­lcu­lat­ion(int x, int y);
return
The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return an optional value. If the method is a void type, the return statement can be omitted. If the return statement is inside a try block, the finally block, if one exists, will be executed before control returns to the calling method.

Type Methods

IndexOf
Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.
String, Array
string
nameOf­Str­ing.In­dex­Of(­"­r", 0, nameOf­Str­ing.Le­ngth);
array
int posI = Array.I­nd­exO­f(n­ame­OfA­rray, "­i");
Equals
public virtual bool Equals (object obj);
true if the specified object is equal to the current object; otherwise, false.
Split
String
.ToLower()
String
.Format
String
 
Consol­e.W­rit­eLi­ne(­"­Format Decimal: {0:n2}­", num);
cambia el punto flotante (n2 = dos)
Linq
.GroupBy()
words.E­xc­ept­(ba­nned)
String

File management

Write to a Text File
Write list of strings to a file
string[] lines = { "­First line", "­Second line", "­Third line" };
 
System.IO.Fi­le.W­ri­teA­llL­ine­s(@­"­C:­\Use­rs­\Pub­lic­\Te­stF­old­er­\Wri­teL­ine­s.t­xt", lines);
 
// WriteA­llLines creates a file, writes a collection of strings to the file, // and then closes the file. You do NOT need to call Flush() or Close().
Write String to a text file
string text = "A class is the most powerful data type in C#. Like a structure, " + "a class defines the data and behavior of the data type. ";
 
// WriteA­llText creates a file, writes the specified string to the file, // and then closes the file. You do NOT need to call Flush() or Close(). System.IO.Fi­le.W­ri­teA­llT­ext­(@"C­:\U­ser­s\P­ubl­ic­\Tes­tFo­lde­r\W­rit­eTe­xt.t­xt­", text);
Write only some strings in an array to a file.
// The using statement automa­tically flushes AND CLOSES the stream and calls // IDispo­sab­le.D­ispose on the stream object. // NOTE: do not use FileStream for text files because it writes bytes, but Stream­Writer // encodes the output as text.
using (Syste­m.I­O.S­tre­amW­riter file = new System.IO.St­rea­mWr­ite­r(@­"­C:­\Use­rs­\Pub­lic­\Te­stF­old­er­\Wri­teL­ine­s2.t­xt­")) { foreach (string line in lines) { // If the line doesn't contain the word 'Second', write the line to the file. if (!line.Co­nta­ins­("Se­con­d")) { file.W­rit­eLi­ne(­line); } } }
Append new text to an existing file.
// The using statement automa­tically flushes AND CLOSES the stream and calls // IDispo­sab­le.D­ispose on the stream object. using (Syste­m.I­O.S­tre­amW­riter file = new System.IO.St­rea­mWr­ite­r(@­"­C:­\Use­rs­\Pub­lic­\Te­stF­old­er­\Wri­teL­ine­s2.t­xt­", true)) { file.W­rit­eLi­ne(­"­Fourth line"); } }

Read Text from a File

Read the file as one string
string text = System.IO.Fi­le.R­ea­dAl­lTe­xt(­@"C:­\Us­ers­\Pu­bli­c\T­est­Fol­der­\Wr­ite­Tex­t.t­xt");
 
System.Co­nso­le.W­ri­teL­ine­("Co­ntents of WriteT­ext.txt = {0}", text);
Read each line of the file into a string array. Each element of the array is one line of the file.
string[] lines = System.IO.Fi­le.R­ea­dAl­lLi­nes­(@"C­:\U­ser­s\P­ubl­ic­\Tes­tFo­lde­r\W­rit­eLi­nes­2.t­xt");
 
System.Co­nso­le.W­ri­teL­ine­("Co­ntents of WriteL­ine­s2.txt = ");
foreach (string line in lines){
Consol­e.W­rit­eLi­ne(­"­\t" + line);
}
 
Consol­e.W­rit­eLi­ne(­"­\t" + line);

Variable declar­ation

const
You use the const keyword to declare a constant field or a constant local. Constant fields and locals aren't variables and may not be modified. Constants can be numbers, Boolean values, strings, or a null reference. Don’t create a constant to represent inform­ation that you expect to change at any time.
casting
double r = 2.0; int n = 1; n = (int) r
explicit conversion
String cadena =”5”; float variab­le_­flo­tante = float.P­ar­se(­cad­ena); int numero­_entero = int.Pa­rse­(ca­dena); char var_car = char.P­ars­e(c­adena);
&&
returns the boolean value TRUE if both operands are TRUE and returns FALSE otherwise. The operands are implicitly converted to type bool prior to evalua­tion, and the result is of type bool.

Repetition structures

foreach
foreach( int number in numbers){ Consol­e.W­rit­e($­"­\t{­num­ber­}")}

Inheri­tance

C# and .NET support single inheri­tance only. That is, a class can only inherit from a single class.
Not all members of a base class are inherited by derived classes.
Static constr­uctors, which initialize the static data of a class.
Instance constr­uctors, which you call to create a new instance of the class.
Each class must define its own constr­uctors.
Finalizers, which are called by the runtime's garbage collector to destroy instances of a class.
public class C : A
//C inherits from A

Operators

int a = 10, b = 3;
d = a+b++;
e = ++a-b;
a = 10, b = 3, d = null
a = 10, b= 3, d = 13
a = 11, d = 4, e = 7
!
calcula la negación lógica de su operando. Es decir, genera true, si el operando se evalúa como false, y false, si el operando se evalúa como true:
&
El operador & calcula el operador AND lógico de sus operandos. El resultado de x & y es true si x y y se evalúan como true. De lo contrario, el resultado es false.
^
The operator computes the logical exclusive OR, also known as the logical XOR, of its operands. The result of x y is true if x evaluates to true and y evaluates to false, or x evaluates to false and y evaluates to true. Otherwise, the result is false. That is, for the bool operands, the ^ operator computes the same result as the inequality operator !=.
|
The | operator computes the logical OR of its operands. The result of x | y is true if either x or y evaluates to true. Otherwise, the result is false. The | operator evaluates both operands even if the left-hand operand evaluates to true, so that the result must be true regardless of the value of the right-hand operand.
&&
computes the logical AND of its operands. The result of x && y is true if both x and y evaluate to true. Otherwise, the result is false. If x evaluates to false, y is not evaluated.

Methods

Function
returns a value
Procedure
executes commands
Method
subroutine associated with an object in OO
Subroutine
returns multiple values

Compiled and Structured langauges

Tanto compil­adores como interp­ret­adores son programas que convierten el código que escribes a lenguaje de máquina.
Lenguaje de máquina son las instru­cciones que entiende el computador (el procesador para ser más exactos) en código binario (unos y ceros).
La principal diferencia entre un lenguaje compilado y uno interp­retado es que el lenguaje compilado requiere un paso adicional antes de ser ejecutado, la compil­ación, que convierte el código que escribes a lenguaje de máquina. Un lenguaje interp­retado, por otro lado, es convertido a lenguaje de máquina a medida que es ejecutado.

Docume­ntation

Comments
//
/ /
/ <su­mma­ry> </s­umm­ary> /

Selection statements

case
int caseSwitch = 1; switch (caseS­witch) { case 1: Consol­e.W­rit­eLi­ne(­"Case 1"); break; case 2: Consol­e.W­rit­eLi­ne(­"Case 2"); break; default: Consol­e.W­rit­eLi­ne(­"­Default case"); break; }

Classes

Random
var rand = new Random();
// Instan­tiate random number generator using system­-su­pplied value as seed.
// Generate and display 5 random byte (integer) values.
var bytes = new byte[5]; rand.N­ext­Byt­es(­bytes);
// Generate and display 5 random integers between 0 and 100.
for (int ctr = 0; ctr <= 4; ctr++) Consol­e.W­rit­e("{­0,8­:N0­}", rand.N­ext­(101)); Consol­e.W­rit­eLi­ne();
// Generate and display 5 random integers.
Consol­e.W­rit­eLi­ne(­"Five random integer values­:"); for (int ctr = 0; ctr <= 4; ctr++) Consol­e.W­rit­e("{­0,1­5:N­0}", rand.N­ext()); Consol­e.W­rit­eLi­ne();
Obtener doubles según rango
rand.N­ext­Dou­ble() * 5
-
1,5 will generate 4 random numbers

Loops

 
foreac­h(var c in J)
 
for(int i =0; i < s.Length; i++)
 
while(c >10)