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 Loop | If-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.Linq | For | Console.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.
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.