C# Crash Course

see C# Category

Recommended Book

 

Check out: Getting Started in C# Tutorial

 

Introduction

 
C# is a general-purpose, multi-paradigm programming language encompassing strong typing, lexically scoped, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed around 2000 by Microsoft within its .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270:2018). C# is one of the programming languages designed for the Common Language Infrastructure.

  • The language is intended to be a simple, modern, general-purpose, object-oriented programming language.
  • The language, and implementations thereof, should provide support for software engineering principles such as strong type checking, array bounds checking, detection of attempts to use uninitialized variables, and automatic garbage collection. Software robustness, durability, and programmer productivity are important.
  • The language is intended for use in developing software components suitable for deployment in distributed environments.
  • Portability is very important for source code and programmers, especially those already familiar with C and C++.
  • Support for internationalization is very important.
  • C# is intended to be suitable for writing applications for both hosted and embedded systems, ranging from the very large that use sophisticated operating systems, down to the very small having dedicated functions.
  • Although C# applications are intended to be economical with regard to memory and processing power requirements, the language was not intended to compete directly on performance and size with C or assembly language.

 

 

Resources

 
C# Exercises with Solutions (w3resource) (website)  [free] [excellent]

Chapter 1 A First Program Using C# – 67 cards (Quizlet) (website)  [free]

C# Programming – 71 cards (Quizlet) (website)  [free]

C# Tutorial (video)  [free]

C# Fundamentals (video)
  [free]

C# Fundamentals for Absolute Beginners (Bob Tabor) (course)  [free]

C# (TutorialsPoint) (website)  [free]

C# Study Guide (TutorialsPoint) (PDF)  [free]

 

Where to begin? Let’s start with the basics.

 
1 – Download and install Visual Studio Community Edition (2022). Visual Studio is an IDE, or Integrated Development Environment. An IDE is a collection of programming resources, features, and design components which aid in the development of software. Basically, an IDE helps you make software.

Select everything you want to learn about.

This will take a while. Take a break.

 

2 – Create a new project.

 

3 – Select Console App (.NET Core).

 

4 – Type the below code samples into Visual Studio (do NOT copy/paste). It is important when you first start learning to program that you type code, to better understand syntax and formatting of the specific programming language.

5 – Review each section, make your own changes, compile, and test.

6 – Research problems and learn from errors in your code.

7 – Practice, practice, practice!


Simple choice program
. Read:  Console.WriteLine Console.ReadLine  |  Do While LoopIf-Else

Do While Loop: In most computer programming languages, a do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block. The do while construct consists of a process symbol and a condition.

If-Else: The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.


Code

// System is a namespace, grouping of related code elements
using System; 
 
// your own, custom namespace
namespace Decisions
{
// a class is program-code-template for creating objects, providing values, 
// adding functions and methods
class Program 
{
 // Main is an entry point into your console app. 
  static void Main(string[] args) 
     {
          Console.Title = "Behind the Door!";
          string Success = "1";
          string message = "";
          string UserValue = "";
          Console.WriteLine("");
 
          // a loop
          do
          {
               Console.WriteLine("Eddie's TV Show");
               Console.WriteLine("Choose a door: 1, 2, 3: ");
               UserValue = Console.ReadLine();
 
              // tests for a condition    
               if (UserValue == "1")  {
                    message = "You have won a vacation to Hawaii!";
                    Success = "0";
               }
               else if (UserValue == "2")
               {
                    message = "You have won a jetski!";
                    Success = "0";
               }
               else if (UserValue == "3")
               {
                    message = "You have won a cruise!";
                    Success = "0";
              }
              else
             {
                  Console.WriteLine("");
                  Console.WriteLine("I did not recognize your answer!");
                  System.Threading.Thread.Sleep(3000);
                  Console.Clear(); 
              }
          Console.WriteLine(message);
 
     } while (Success == "1");
 
     Console.WriteLine("");
     Console.WriteLine("Press Enter to exit.");
     Console.ReadLine();
 
          }
     }
}

 

Working with arrays. Read:  Arrays  |  System.LinqForConsole.ReadKey  |  Console.Write

Array: In computer science, an array data structure, or simply an array, is a data structure consisting of a collection of elements, each identified by at least one array index or key. 


Code

using System;
using System.Linq;
 
class Program
{
    static ref int FirstElement(int[] array)
    {        
        return ref array[0];
    }
 
    static void Main()
    {
        int[] array1 = { 1, 4, 2, 7, 6, 4, 4, 5, 3, 7 };
        int[] array2 = new int[10];
        int maxValue = array1.Max();
        int indexElement = Array.IndexOf(array1, maxValue);
 
 
        // display elements in array1
        Console.Write("Original Array1: ");
        for (int i = 0; i < array1.Length; i++)            
        {            
            Console.Write(array1[i]);
            Console.Write(' ');
        }
 
        // max value
        Console.Write("\n\nMax value in array: {0}", maxValue);
        // index of max value
        Console.Write("\n\nIndex of max value in array: {0}", indexElement);
        Console.Write("\n\n");
 
        // sort ascending
        Console.Write("Array1 sorted ascending: ");
        Array.Sort(array1);
        for (int i = 0; i < array1.Length; i++)
        {            
            Console.Write(array1[i]);
            Console.Write(' ');
        }
        Console.Write("\n\n");
 
 
        // sort descending
        Console.Write("Array1 sorted descending: ");
        Array.Reverse(array1);
        for (int i = 0; i < array1.Length; i++)
        {
            Console.Write(array1[i]);
            Console.Write(' ');
        }
        Console.Write("\n\n");
 
        // make a change to array1, index 0
        FirstElement(array1) = 9;
 
        // display elements with a change in array1
        Console.Write("Array1 with changed element: ");
        for (int i = 0; i < array1.Length; i++)            
        {            
            Console.Write(array1[i]);
            Console.Write(' ');
        }
        Console.Write("\n\n");
 
 
        // copy all elements from array1 to array2
        int[] array1OriginalData1 = { 1, 4, 2, 7, 6, 4, 4, 5, 3, 7 };
        Array.Copy(array1OriginalData1, 0, array2, 0, 10);
 
        int[] array1OriginalData2 = { 1, 4, 2, 7, 6, 4, 4, 5, 3, 7 };
         
 
        // display elements in array2
        Console.Write("Array2 copied from Array1: ");
        for (int i = 0; i < array2.Length; i++)
        {
            Console.Write(array2[i]);
            Console.Write(' ');
        }
        Console.Write("\n\n");
 
        // Array.Copy
        // p1 = source array
        // p2 = start index in source array
        // p3 = destination array
        // p4 = start index in destination array
        // p5 = elements to copy
 
 
 
        // array1 with index
        Console.Write("Array1 sorted with Index:\n");
        for (int i = 0; i < array1OriginalData1.Length; i++)
        {
            int indexVal = Array.IndexOf(array1OriginalData1, array1OriginalData1[i]);
            Console.Write(array1OriginalData1[i] + "(" + indexVal.ToString() + ")");
            Console.Write(' ');
        }
        Console.Write("\n\n");
 
 
 
        // sort array1 into array2 by max value      
         
        Console.Write("Array2 sorted by max value from Array1: ");
        // sort descending        
        Array.Reverse(array1OriginalData1);
         
        // move by index value to array2
        for (int i = 0; i < array1.Length; i++)
        {
            Array.Copy(array1OriginalData1, i, array2, i, 1);
            Console.Write(array2[i]);
            Console.Write(' ');
        }        
        Console.Write("\n\n");
 
 
        Console.Write("\n\nCleared array 1\n");
        Array.Clear(array1, 0, array1.Length);
        for (int i = 0; i < array1.Length; i++)
        {            
            Console.Write(array1[i]);
            Console.Write(' ');
        }
        Console.Write("\n");
 
        Console.Write("\n\nCleared array 2\n");
        Array.Clear(array2, 0, array2.Length);
        for (int i = 0; i < array2.Length; i++)
        {            
            Console.Write(array2[i]);
            Console.Write(' ');
        }
        Console.Write("\n");
 
        Console.ReadKey();
    }
}

 

Various methods doing things. Read:  Thread.Sleep  |  Foreach  |  Threading.Task  |  System.IO  |  Process  |  EventLog.WriteEntry  |  File.ReadAllText  |  RegistryKey  |  Console.WriteLine

Foreach: Foreach loop is a control flow statement for traversing items in a collection. Foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say “do this to everything in this set”, rather than “do this x times”.


Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;      //used by Thread.Sleep
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;    //used by Process
using System.Windows.Forms;  //used by MessageBox
using Microsoft.Win32;       //used by Registry
 
namespace PlayingAround
{
class ReadAll
{
  public static void Main(string[] args)
   {
     Console.Out.WriteLine("DISPLAY CONTENTS OF A TEXT FILE");
 
     //creates {contents} variabe
     string contents = File.ReadAllText(@"C:\test.txt"); 
 
     //outputs {contents} to screen
     Console.Out.WriteLine("contents = " + contents); 
     Thread.Sleep(5000); //wait 5 seconds
 
     //will wait for {ENTER} key
     //Console.In.ReadLine(); 
 
     Console.Out.WriteLine("DISPLAY TIMESTAMP");
 
     //creates {DateTime} variable
     DateTime dt = DateTime.Now; 
 
     //outputs {DataTime} to screen
     Console.WriteLine("Current Time is {0} ", dt.ToString()); 
     Console.Out.WriteLine("");
     Console.Out.WriteLine("");
     Thread.Sleep(5000); //wait 5 seconds
 
     Console.Out.WriteLine("LAUNCH and KILL PROCESS");
     //launch cnn website using IE
     Process process1 = Process.Start("iexplore.exe", "www.cnn.com"); 
     Thread.Sleep(7000); //wait 7 seconds
 
     foreach (System.Diagnostics.Process IEProc in System.Diagnostics.Process.GetProcesses())
     {
          if (IEProc.ProcessName == "iexplore")
          {
             //if IE is found, kill it
             IEProc.Kill(); //kill IExplore.exe
          }   
     }
 
//launch notepad.exe - will stay open
Process process2 = Process.Start("notepad.exe"); 
//wait for process to close before continuing
process2.WaitForExit();                                          
Thread.Sleep(2000); //wait 2 seconds
 
//show simple popup message - 
//make sure you Add Reference to System.Windows.Forms---under Projects
MessageBox.Show("Program has completed!"); 
 
//begin event log creation
 
string sSource;
string sLog;
string sEvent;
 
sSource = "My Program";
sLog = "Application";
sEvent = "This is the description";
 
if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog);
 
EventLog.WriteEntry(sSource, sEvent);
//EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234);
//end event log
 
//write to text log
string text = "Text1 " + "Text2";
System.IO.File.WriteAllText(@"C:\log.txt", text);
 
//set registry key
const string userRoot = "HKEY_CURRENT_USER";
const string subkey = "RegistrySetValueExample";
const string keyName = userRoot + "\\" + subkey;
Registry.SetValue(keyName, "MyKeyName", "A_String_Value_Goes_Here", RegistryValueKind.String);
 
//get registry key
string regValue = (string)Registry.GetValue(keyName, "MyKeyName","");
 
//show popup message 
MessageBox.Show(regValue);                       
 
             
//delete registry key
string regDelete = @"RegistrySetValueExample";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(regDelete, true))
{
 if (key == null)
    {
    //does not exist 
    }
 else
    {
     //does exist
      key.DeleteValue("MyKeyName");
     }
   }
 
        }
    }
}

 

Getter Setter example. Read:  get (C# Reference)  |  set (C# Reference)  |  Console.WriteLine  |  Console.ReadKey

Mutator Method (Getter Setter): In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter, which returns the value of the private member variable.


Code

using System;
 
class Program
{
    // entry point
    static void Main()
    {
        AccessClass accessClass = new AccessClass
        {
             // comment-uncomment to test get set
             // our declared values
             // Number1 = 9, // setter value
             // Number2 = 99 // setter value
        };
 
        Console.WriteLine("Output: {0}", accessClass.Number1); // getter
        Console.WriteLine("Output: {0}", accessClass.Number2); // getter
        Console.ReadKey();
    }
}
 
 
public class AccessClass
{
    // our default values
    public int _number1 { get; set; } = 100; // our default value, aka Backing store
    public int _number2 { get; set; } = 200; // our default value, aka Backing store
 
    public int Number1
    {
        get
        {
            return _number1;
        }
        set
        {
            _number1 = value;
        }
    }
 
    public int Number2
    {
        get
        {
            return _number2;
        }
        set
        {
            _number2 = value;
        }
    }
}

 

Remove dupes from list. Read:  System.Linq  |  List<T>  |  Foreach  |  Console.WriteLine


Code

using System;
using System.Collections.Generic;
using System.Linq;
  
class Program
{
    static void Main()
    {
        // List with duplicate elements.
        List<int> list = new List<int>();
        list.Add(1);
        list.Add(2);
        list.Add(3);
        list.Add(3);
        list.Add(4);
        list.Add(4);
        list.Add(4);
  
        foreach (int value in list)
        {
            Console.WriteLine("Before: {0}", value);
        }
  
        // Get distinct elements and convert into a list again.
        List<int> distinct = list.Distinct().ToList();
  
        foreach (int value in distinct)
        {
            Console.WriteLine("After: {0}", value);
        }
    }
}

more coming soon…

 

Terminology


Class

Defines the data and behavior of a type, like a blueprint. Must have at least one method and one field.

Member
Represents the data or behavior of a class or struct (e.g., field, property, method, constant, event, etc.).

Variable
Word (storage location) that holds a value. The data type and name must be declared in a statement. Must be explicitly declared before use. Uses CamelCase notation.

Method
A code block containing a series of statements. Takes an input, performs some action, and sometimes produces an output. Something an object can do.

Field
Variable of any type, declared directly in a class. Should be private or protected, and store data needed by more than one method.

Property
A member that provides read and/or write access to a private field. Contains get/set accessors.

Access Modifier
Keyword used to specify the declared accessibility of a member or a type.

Public
Keyword with the most permissive access level. There are no restrictions on accessing these members.

Private
Keyword with the least permissive access level. Members are accessible only within the body of the class or the struct in which they are declared.

Internal
Keyword where members are accessible only within files in the same assembly.

Protected
Keyword where members are accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.

Constructor
Class method that has the same name as the class, is executed when an object is created, and can set default values for the object.

For
Executes a block repeatedly until a specified expression evaluates to false. This loop is handy for iterating over arrays and for sequential processing. (Hint: More compact version of another iteration statement.)

While
Executes a block repeatedly until a specified expression evaluates to false. (Hint: Less compact version of another iteration statement.)

Do-While
Executes a block repeatedly until a specified expression evaluates to false, but is always executed once before the conditional expression is evaluated.

Foreach
Statement used to iterate through every element in an array or collection. Should not be used to change the contents of the collection to avoid unpredictable side effects.

If-else
A selection statement that identifies which block of code to run based on the value of a Boolean expression.

Switch
A selection statement that transfers control to the case section whose label contains a constant value that matches the value of the expression evaluated.

Parameter
Used to pass values or variable references into a method.

Argument
The value of the parameter passed to a method

Overloading
Using the same name for multiple class methods within the same class but with different parameters.

Array
A data structure that contains several variables of the same type. Can be Single-Dimensional, Multidimensional or Jagged.

Inheritance
A characteristic of OOP that allows the creation of new classes that reuse, extend, and modify the behavior that is defined in other classes. Implemented with a colon followed by the parent class (e.g., public class B : A)

Encapsulation
A characteristic of OOP that restricts access to class members to prevent users from misusing objects. While hiding the internal functionalities, it allows the class to service requests or modify its code to suit changing requirements.

Polymorphism
A characteristic of OOP that allows objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior (speak()!). Uses the same public interface for different types, such as the money slots.

Keyword
Name reserved by the compiler that coders are not allowed to use as identifier.

Namespace
Groups classes together so that they have a unique identifier.

Assembly
Compilation of classes. In C#, usually ends in .dll or .exe

Expression
A sequence of one or more operands and zero or more operators that can be evaluated to a single value, object, method, or namespace.

Operator
Symbol which transforms and combines expressions

Object
Instance of a type created when a program runs. Can be visible or invisible. Has properties, events and methods.

Heap
Block of memory allocated on the fly when the ‘new’ operator is called, or with reference data types (e.g., strings).

Stack
Block of memory allocated when a program is executed, is sequential (LIFO), and used for value data types (e.g., int).

try-catch-finally
An exception handling statement where code is executed in the first block, any exceptions are handled in the second block, and resources are released in the final block.

Static
A modifier used to create data and functions that can be accessed without creating an instance of the class. Can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object.

Const
A modifier used with a declaration of a field or local variable, and specifying the value of which cannot be modified.

Abstract
A modifier used in a class declaration to indicate that the class is intended only to be a base class of other classes and cannot be instantiated.

Override
A modifier used with a method, a property, an indexer, or an event to create a new implementation of a virtual member inherited from a base class. Must have the same signature.

Virtual
A modifier used with a method or property declaration, the implementation of which can be changed by an overriding member in a derived class. When invoked, the run-time type of the object is checked for an overriding member.

Interface
Contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements this. Is a contract.

Indexer
Allows an instance of a class or struct to behave like an array. Resembles a property except that its accessors take parameters. Defined with this and value keywords.

Generic
A way to create a collection that is type-safe at compile-time (as opposed to casting types to and from the universal base type Object). Defined with a <T>.

Collection
A specialized class for data storage and retrieval. Provides support for stacks, queues, lists, and hash tables, increased type-safety and better performance.

Struct
A value type that can behave like a class but is instatiated on the stack, is lightweight, and is passed by value instead of reference.

Void
The return type for a method that does not return a value.

Int
A value type with a range of -2,147,483,648 to 2,147,483,647.

Bool
A value type that evaluates to true or false.

Byte
A value type with a range of 0 to 255.

Char
A value type that represents a Unicode character.

Decimal
A 128-bit value data type with great precision and a range which makes it appropriate for financial and monetary calculations.

Double
A value type that stores 64-bit floating-point values with a range of ±5.0 × 10−324 to ±1.7 × 10308

Enum
A value type consisting of a set of named constants. By default, the first element has the int value 0, and each successor is increased by 1.

Var
An implicit type. It aliases any type in the C# programming language. The aliased type is determined by the C# compiler. This has no performance penalty.

Parse
A method used to convert data from one type to another.

Float
A value type that stores 32-bit floating-point values with a range of -3.4 × 1038 to +3.4 × 1038.

Sealed
A modifier that prevents other classes from inheriting from the modified class.

Singleton
A class pattern that creates a single instance of itself. Allows other objects to access this instance through a class method that returns a reference to the instance. Declares the class constructor as private so that no other object can create a new instance. (Example = mouse pointer)

Is
An operator that checks if an object is compatible with a given type. Evaluates to false if the object is not convertible, but does NOT perform conversion.

As
An operator that is used to perform certain types of conversions between compatible reference or nullable types. Acts like a cast operation. However, if the conversion is not possible, it returns null instead of raising an exception.

Boxing
The implicit process where the CLR wraps a value type inside a System.Object and stores it on the managed heap.

Factory
An object for creating other objects. It is an abstraction of a constructor, and typically has a method for every kind of object it is capable of creating. These methods optionally accept parameters defining how the object is created, and then return the created object.

Attribute
A powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth).

Reflection
Dynamically creates an instance of a type, binds the type to an existing object, or gets the type from an existing object and invokes its methods or accesses its fields and properties. Enables you to access attributes.

more…

 

tags: MrNetTek, Eddie Jackson, Computer, Automation, “Merit is Might”, Artificial Intelligence, “Who is MrNetTek”

30 years of job experience! IT Professional. Computers, Electronics, Solar. ACM Member.