Advertisement
here2share

C# Cheat Sheet...

Nov 23rd, 2019
863
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.78 KB | None | 0 0
  1. C# Cheat Sheet
  2.  
  3.     Data Types
  4.  
  5.      Primitive   Size            Example
  6.      
  7.      String      2 bytes/char    s = "reference";
  8.      bool                        b = true;
  9.      char        2 bytes         ch = 'a';
  10.      byte        1 byte          b = 0x78;
  11.      short       2 bytes         val = 70;
  12.      int         4 bytes         val = 700;
  13.      long        8 bytes         val = 70;
  14.      float       4 bytes         val = 70.0F;
  15.      double      8 bytes         val = 70.0D;
  16.      decimal     16 bytes        val = 70.0M;
  17.  
  18.     Arrays
  19.  
  20.     2.1 Declaration
  21.  
  22.     //Initiliazed using a list defined with curly braces
  23.     int[] nameArray = {100, 101, 102};
  24.  
  25.     //Define an empty array
  26.     int[] nameArray = new int[3]; // 3 rows and 2 columns
  27.  
  28.     //To access a specific item in the array
  29.     int[] nameArray = new int[10];
  30.     int firstNumber = nameArray[0];
  31.     nameArray[1] = 20;
  32.  
  33.     //Multidimensional arrays
  34.     int [,] matrix = new int [2,2]
  35.     matrix[0,0] = 1;
  36.     matrix[0,1] = 2;
  37.     matrix[1,0] = 3;
  38.     matrix[1,1] = 4;
  39.  
  40.     int[,] predefinedMatrix = new int[2,2] { { 1, 2 }, { 3, 4 } };
  41.  
  42.     2.2 Array Operations
  43.  
  44.     //Sort ascending
  45.     Array.Sort(nameArray);
  46.  
  47.     //Sort begins at element 6 and sorts 20 elements
  48.     Array.Sort(nameArray,6,20);
  49.  
  50.     //Use 1 array as a key & sort 2 arrays
  51.     string[] values = {"Juan", "Victor", "Elena"};
  52.     string[] keys = {"Jimenez", "Martin", "Ortiz"};
  53.     Array.Sort(keys, values);
  54.  
  55.     //Clear elements in array (array, first element, # elements)
  56.     Array.Clear(nameArray, 0, nameArray.Length);
  57.  
  58.     //Copy elements from one array to another
  59.     Array.Copy(scr, target, numOfElements);
  60.  
  61.     String Operations
  62.  
  63.      //To concatenate between strings, use the plus operator:
  64.      string firstName = "Erin";
  65.      string lastName = "Roger";
  66.      string fullName = firstName + " " + lastName;
  67.  
  68.      //To add one string to another, use the += operator:
  69.      string secondLastName = "Green";
  70.      string fullName += secondLastName;
  71.      
  72.      //ToString function
  73.      //It converts an object to its string representation so that it is suitable for display
  74.      Object.ToString();
  75.      
  76.      //String formatting
  77.      //Each additional argument to the function can be referred to in the string using the brackets operator with the index number.
  78.      String.Format(String format, Object arg0);
  79.       format - A composite format string that includes one or more format items
  80.       arg0 - The first or only object to format
  81.  
  82.      //Substring
  83.      //Returns a part of the string, beginning from the index specified as the argument. Substring also accepts a maximum length for the substring
  84.      String.Substring(beginAt);
  85.      String.Substring(beginAt, maximum);
  86.      
  87.      //Replace
  88.      string newStr = oldStr.Replace("old","new");
  89.  
  90.      //IndexOf
  91.      //Finds the first ocurrence of a string in a larger string
  92.      //Returns -1 if the string is not found
  93.      String.IndexOf(val, start, num)
  94.      val - string to search for
  95.      start - where to begin in string
  96.  
  97.      //LastIndexOf
  98.      //Search from end of string
  99.  
  100.      //Split
  101.      //Split is used to break delimited string into substrings
  102.      String.Split(Char[]);
  103.  
  104.      //ToCharArray
  105.      //Places selected characteres in a string in a char array
  106.      String str = "AaBbCcDd";
  107.      //create array of 8 vowels
  108.      var chars = str.ToCharArray();
  109.      //create array of 'B' and 'C'
  110.      var chars = str.ToCharArray(2,2);
  111.  
  112.     System.Text.StringBuilder
  113.  
  114.      4.1 Constructor
  115.  
  116.      StringBuilder sb = new StringBuilder();
  117.      StringBuilder sb = new StringBuilder(myString);
  118.      StringBuilder sb = new StringBuilder(myString, capacity);
  119.  
  120.      myString - Initial value of StringBuilder object
  121.      capacity - Initial size of buffer
  122.  
  123.     DateTime
  124.  
  125.      5.1 DateTime Constructor
  126.  
  127.      DateTime(year, month, day)
  128.      DateTime(year, month, day, hour, minute, second)
  129.  
  130.      DateTime newYear = DateTime.Parse("1/1/2018"):
  131.      DateTime currentDate = DateTime.Now;
  132.      DateTime nextYear = DateTime.AddYears(1);
  133.  
  134.     TimeSpan
  135.  
  136.      6.1 TimeSpan Constructor
  137.          
  138.      TimpeSpan(hour, minute, sec)
  139.      
  140.      TimeSpan timeS = new TimeSpan(10, 14, 50);
  141.      TimeSpan timeS_Hours = TimeSpan.FromDays(3640);
  142.  
  143.     Formatting Values
  144.  
  145.      Format item syntax: {index[,alignment][:format string]}
  146.      index - Specifies element in list of values to which format is applied
  147.      aligment - Indicates minimun width (in characters) to display value
  148.      format string - Contains the code which specififes the format of the displayed value
  149.  
  150.      7.1 Numeric
  151.  
  152.      Format   Name           Pattern             Value       Result
  153.      C or c   Currency       {0:C2}, 1000.1      $ 1000.1    A currency value
  154.      D or d   Decimal        {0:D5}, 30          00030       Integer digits with optional negative sign
  155.      E or e   Exponential    {0,9:E2}, 120.2     1.20+E002   Exponential notation
  156.      F or f   Fixed-point    {0,9:F2}, 120.2     120.2       Integral and decimal digits with optional negative sign
  157.      G or g   General        {0,9:G2}, 120.2     120.2       The more compact of either fixed-point or scientific notation
  158.      N or n   Number         {0,9:N1}, 1300.5    1,300,5    Integral and decimal digits, group separators, and a decimal separator with optional negative sign
  159.      P or p   Percent        {0,9:P3}, .0903     9.03%       Number multiplied by 100 and displayed with a percent symbol
  160.      R or r   Round-trip     {0,9:R}, 3.1416     3.1316      A string that can round-trip to an identical number
  161.      X or x   Hexadecimal    {0,9:X4}, 31        001f        A hexadecimal string
  162.  
  163.     C# compiler at the Command Line
  164.  
  165.      csc File.cs -> Compiles Files.cs producing File.exe
  166.      csc -target:library File.cs -> Compiles File.cs producing File.dll
  167.      csc -out:My.exe File.cs -> Compiles File.cs and creates My.exe
  168.      csc -define:DEBUG -optimize -out:File2.exe *.cs -> Compiles all the C# files in the current directory with optimizations enabled and defines the DEBUG symbol. The output is File2.exe
  169.      csc -target:library -out:File2.dll -warn:0 -nologo -debug *.cs -> Compiles all the C# files in the current directory producing a debug version of File2.dll. No logo and no warnings are displayed
  170.      csc -target:library -out:Something.xyz *.cs -> Compiles all the C# files in the current directory to Something.xyz (a DLL)
  171.      
  172.      8.1 Compiler Options Listed
  173.  
  174.      Option                     Purpose
  175.      @                          Reads a response file for more options.
  176.      -?                         Displays a usage message to stdout.
  177.      -additionalfile                Names additional files that don't directly affect code generation but may be used by analyzers for producing errors or warnings.
  178.      -addmodule                 Links the specified modules into this assembly
  179.      -analyzer                  Run the analyzers from this assembly (Short form: -a)
  180.      -appconfig                 Specifies the location of app.config at assembly binding time.
  181.      -baseaddress               Specifies the base address for the library to be built.
  182.      -bugreport                 Creates a 'Bug Report' file. This file will be sent together with any crash information if it is used with -errorreport:prompt or -errorreport:send.
  183.      -checked                   Causes the compiler to generate overflow checks.
  184.      -checksumalgorithm:<alg>   Specifies the algorithm for calculating the source file checksum stored in PDB. Supported values are: SHA1 (default) or SHA256.
  185.      -codepage                  Specifies the codepage to use when opening source files.
  186.      -debug                     Emits debugging information.
  187.      -define                        Defines conditional compilation symbols.
  188.      -delaysign                 Delay-signs the assembly by using only the public part of the strong name key.
  189.      -deterministic             Causes the compiler to output an assembly whose binary content is identical across compilations if inputs are identical.
  190.      -doc                       Specifies an XML Documentation file to generate.
  191.      -errorreport               Specifies how to handle internal compiler errors: prompt, send, or none. The default is none.
  192.      -filealign                 Specifies the alignment used for output file sections.
  193.      -fullpaths                 Causes the compiler to generate fully qualified paths.
  194.      -help                      Displays a usage message to stdout.
  195.      -highentropyva             Specifies that high entropy ASLR is supported.
  196.      -incremental               Enables incremental compilation [obsolete].
  197.      -keycontainer              Specifies a strong name key container.
  198.      -keyfile                   Specifies a strong name key file.
  199.      -langversion:<string>      Specify language version: Default, ISO-1, ISO-2, 3, 4, 5, 6, 7, 7.1, 7.2, 7.3, or Latest
  200.      -lib                       Specifies additional directories in which to search for references.
  201.      -link                      Makes COM type information in specified assemblies available to the project.
  202.      -linkresource              Links the specified resource to this assembly.
  203.      -main                      Specifies the type that contains the entry point (ignore all other possible entry points).
  204.      -moduleassemblyname            Specifies an assembly whose non-public types a .netmodule can access.
  205.      -modulename:<string>       Specify the name of the source module.
  206.      -noconfig                  Instructs the compiler not to auto include CSC.RSP file.
  207.      -nologo                        Suppresses compiler copyright message.
  208.      -nostdlib                  Instructs the compiler not to reference standard library (mscorlib.dll).
  209.      -nowarn                        Disables specific warning messages
  210.      -nowin32manifest           Instructs the compiler not to embed an application manifest in the executable file.
  211.      -optimize                  Enables/disables optimizations.
  212.      -out                       Specifies the output file name (default: base name of file with main class or first file).
  213.      -parallel[+|-]             Specifies whether to use concurrent build (+).
  214.      -pathmap                   Specifies a mapping for source path names output by the compiler.
  215.      -pdb                       Specifies the file name and location of the .pdb file.
  216.      -platform                  Limits which platforms this code can run on: x86, Itanium, x64, anycpu, or anycpu32bitpreferred. The default is anycpu.
  217.      -preferreduilang           Specifies the language to be used for compiler output.
  218.      -publicsign                Apply a public key without signing the assembly, but set the bit in the assembly indicating the assembly is signed.
  219.      -recurse                   Includes all files in the current directory and subdirectories according to the wildcard specifications.
  220.      -reference                 References metadata from the specified assembly files.
  221.      -refout                    Generate a reference assembly in addition to the primary assembly.
  222.      -refonly                   Generate a reference assembly instead of a primary assembly.
  223.      -resource                  Embeds the specified resource.
  224.      -ruleset:<file>            Specify a ruleset file that disables specific diagnostics.
  225.      -subsystemversion          Specifies the minimum version of the subsystem that the executable file can use.
  226.      -target                    Specifies the format of the output file by using one of four options: -target:appcontainerexe, -target:exe, -target:library, -target:module, -target:winexe, -target:winmdobj.
  227.      -unsafe                    Allows unsafe code.
  228.      -utf8output                    Outputs compiler messages in UTF-8 encoding.
  229.      -warn                      Sets the warning level (0-4).
  230.      -warnaserror               Reports specific warnings as errors.
  231.      -win32icon                 Uses this icon for the output.
  232.      -win32manifest             Specifies a custom win32 manifest file.
  233.      -win32res                  Specifies the win32 resource file (.res).
  234.  
  235.    Control flow statements
  236.  
  237.     9.1 Switch
  238.  
  239.     switch (expression) {
  240.     //expression may be integer, string or enum
  241.     case expression:
  242.         //statements
  243.         break/ goto / return()
  244.  
  245.     case ..
  246.     default
  247.         //statements
  248.         break/ goto / return()
  249.     }
  250.  
  251.     9.2 If
  252.  
  253.     if (condition) {
  254.         //statements
  255.     } else {
  256.         //statements
  257.     }
  258.  
  259.    Loop
  260.  
  261.    10.1 While
  262.  
  263.    while (condition) {body}
  264.  
  265.    10.2 Do while
  266.  
  267.    do {body} while condition;
  268.  
  269.    10.3 For
  270.  
  271.    for (initializer; termination condition; iteration;) {
  272.            //statements
  273.    }
  274.  
  275.    10.4 For each
  276.  
  277.    foreach (type identifier in collection)  {
  278.        //statements
  279.    }
  280.  
  281.    Class Definition
  282.  
  283.    11.1 Class
  284.  
  285.    public | protected | internal | private
  286.    abstract | sealed | static
  287.  
  288.    class className [:class/interfaces inherited from]
  289.  
  290.    11.2 Constructor
  291.  
  292.    [access modifier] className (parameters) [:initializer]
  293.  
  294.    initializer -base calls constructor in base class.
  295.                 this calls constuctor within class.
  296.  
  297.    public class nameClass : Initializer {
  298.        public className(dataType param1 , dataType param2, ...) : base(param1, param2)
  299.        { constructor body }
  300.    }
  301.  
  302.    11.3 Method
  303.  
  304.    [access modifier]
  305.    static | virtual | override | new | sealed | abstract
  306.    methodName (parameter list) { body }
  307.  
  308.    virtual – method can be overridden in subclass
  309.    override – overrides virtual method in base class
  310.    new – hides non-virtual method in base class
  311.    sealed – prevents derived class from inheriting
  312.    abstract – must be implemented by subclass
  313.  
  314.    Passing parameters:
  315.        1. By default, parametres are passed by value
  316.        2. Passing by reference: ref, in and out modifers
  317.  
  318.    To pass a parameter by reference with the intent of changing the value, use the ref, or out keyword. To pass by reference with the intent of avoiding copying but not changing the value, use the in modifier
  319.  
  320.    11.4 Property
  321.  
  322.    [modifier] <dataType> property name{
  323.        public string BrandName
  324.        {
  325.            get { return brandName; }
  326.            set { brandName = value; }
  327.        }
  328.    }
  329.  
  330.    Struct
  331.  
  332.    12.1 Defining a structure
  333.  
  334.    [attribute][modifier] struct name [:interfaces] { struct-body }
  335.  
  336.    12.2 Class vs Structure
  337.  
  338.       -> Classes are reference types and structs are value types
  339.       -> Structures do not support inheritance
  340.       -> Structures cannot have default constructor
  341.  
  342.    Enum
  343.  
  344.    13.1 Declaring enum variable
  345.  
  346.    enum <enumName> {
  347.        enumeration list
  348.    };
  349.  
  350.    enumName - Specifies the enumeration type name
  351.    enumeration list is a comma-separated list of identifiers
  352.  
  353.    //Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it.
  354.  
  355.    Delegates
  356.  
  357.    //A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
  358.  
  359.    14.1 Declaring delegates
  360.  
  361.    //Delegate declaration determines the methods that can be referenced by the delegate.
  362.  
  363.    delegate <return type> <delegate-name> <parameter list>
  364.  
  365.    14.2 Instantiating delegates
  366.  
  367.    //When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method
  368.  
  369.    public delegate void printString(string s);
  370.    printString ps1 = new printString(WriteToScreen);
  371.    printString ps2 = new printString(WriteToFile);
  372.  
  373.    Events
  374.  
  375.    15.1 Declaring events
  376.  
  377.    //To declare an event inside a class, first a delegate type for the event must be declared.
  378.  
  379.    public delegate string MyDelegate(string str);
  380.  
  381.    //The event itself is declared by using the event keyword
  382.  
  383.    event MyDelegate MyEvent;
  384.  
  385.    15.2 Commonly used Control Events
  386.  
  387.    Event                                           Delegate
  388.  
  389.    Click, MouseEnter, DoubleClick, MouseLeave      EventHandler( object sender, EventArgs e)
  390.    MouseDown, Mouseup, MouseMove                   MouseEventHandler(object sender, MouseEventArgs e)
  391.                                                        e.X, e.Y – x and y coordinates
  392.                                                        e.Button – MouseButton.Left, Middle, Right
  393.    KeyUp, KeyDown                                  KeyEventHandler(object sndr, KeyEventArgs e)
  394.                                                        e.Handled – Indicates whether event is handled.
  395.                                                        e.KeyCode – Keys enumeration, e.g., Keys.V
  396.                                                        e.Modifiers – Indicates if Alt, Ctrl, or Shift key.
  397.    KeyPress                                        KeyPressEventHandler(object sender, KeyPressEventArgs e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement