using System.Collections.Generic;
using System.Threading.Tasks;
namespace Learning.CSharp
public static void Syntax()
Console.WriteLine("Hello World");
ushort fooUshort = 10000;
ulong fooUlong = 100000L;
double fooDouble = 123.4;
decimal fooDecimal = 150.3m;
string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)";
Console.WriteLine(fooString);
char charFromString = fooString[1];
string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);
string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2);
DateTime fooDate = DateTime.Now;
Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
string path = "C:\\Users\\User\\Desktop";
string verbatimPath = @"C:\Users\User\Desktop";
Console.WriteLine(path == verbatimPath);
string bazString = @"Here's some stuff
on a new line! ""Wow!"", the masses cried";
const int HoursWorkPerWeek = 9001;
int[] intArray = new int[10];
int[] y = { 9000, 1000, 1337 };
Console.WriteLine("intArray @ 0: " + intArray[0]);
List<int> intList = new List<int>();
List<string> stringList = new List<string>();
List<int> z = new List<int> { 9000, 1000, 1337 };
Console.WriteLine("intList @ 0: " + intList[0]);
Console.WriteLine("\n->Operators");
Console.WriteLine(i1 + i2 - i1 * 3 / 7);
Console.WriteLine("11%3 = " + (11 % 3));
Console.WriteLine("3 == 2? " + (3 == 2));
Console.WriteLine("3 != 2? " + (3 != 2));
Console.WriteLine("3 > 2? " + (3 > 2));
Console.WriteLine("3 < 2? " + (3 < 2));
Console.WriteLine("2 <= 2? " + (2 <= 2));
Console.WriteLine("2 >= 2? " + (2 >= 2));
Console.WriteLine("\n->Inc/Dec-rementation");
Console.WriteLine("\n->Control Structures");
Console.WriteLine("I get printed");
Console.WriteLine("I don't");
Console.WriteLine("I also don't");
string isTrue = toCompare == 17 ? "True" : "False";
} while (fooDoWhile < 100);
for (int fooFor = 0; fooFor < 10; fooFor++)
foreach (char character in "Hello World".ToCharArray())
monthString = "Februari";
monthString = "Summer time!!";
monthString = "Some other month";
if (int.TryParse("123", out tryInt))
Console.WriteLine(tryInt);
public static void Classes()
Bicycle trek = new Bicycle();
Console.WriteLine("trek info: " + trek.Info());
PennyFarthing funbike = new PennyFarthing(1, 10);
Console.WriteLine("funbike info: " + funbike.Info());
public static void Main(string[] args)
OtherInterestingFeatures();
params string[] otherParams
public static void MethodSignatures(
public static TValue SetDefault<TKey, TValue>(
IDictionary<TKey, TValue> dictionary,
if (!dictionary.TryGetValue(key, out result))
return dictionary[key] = defaultItem;
public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
foreach (var item in toPrint)
Console.WriteLine(item.ToString());
public static IEnumerable<int> YieldCounter(int limit = 10)
for (var i = 0; i < limit; i++)
public static void PrintYieldCounterToConsole()
foreach (var counter in YieldCounter())
Console.WriteLine(counter);
public static IEnumerable<int> ManyYieldCounter()
public static IEnumerable<int> YieldCounterWithBreak(int limit = 10)
for (var i = 0; i < limit; i++)
if (i > limit/2) yield break;
public static void OtherInterestingFeatures()
MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
MethodSignatures(3, another: 3);
MethodSignatures(ref maxCount, out count);
Console.WriteLine("Nullable variable: " + nullable);
bool hasValue = nullable.HasValue;
int notNullable = nullable ?? 0;
var magic = "magic is a string, at compile time, so you still get type safety";
var phonebook = new Dictionary<string, string>() {
{"Sarah", "212 555 5555"}
Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone"));
Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone"));
Func<int, int> square = (x) => x * x;
Console.WriteLine(square(3));
var funBike = PennyFarthing.CreateWithGears(6);
catch (NotSupportedException)
Console.WriteLine("Not so much fun now!");
throw new ApplicationException("It hit the fan", ex);
using (StreamWriter writer = new StreamWriter("log.txt"))
writer.WriteLine("Nothing suspicious here");
var words = new List<string> {"dog", "cat", "horse", "pony"};
new ParallelOptions() { MaxDegreeOfParallelism = 4 },
dynamic student = new ExpandoObject();
student.FirstName = "First Name";
student.Introduce = new Func<string, string>(
(introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo));
Console.WriteLine(student.Introduce("Beth"));
var bikes = new List<Bicycle>();
bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels));
.Where(b => b.Wheels > 3)
.Where(b => b.IsBroken && b.HasTassles)
.Select(b => b.ToString());
var sum = bikes.Sum(b => b.Wheels);
var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles });
foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome))
Console.WriteLine(bikeSummary.Name);
var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
var db = new BikeRepository();
var filter = db.Bikes.Where(b => b.HasTassles);
filter = filter.Where(b => b.IsBroken);
foreach (string bike in query)
Console.WriteLine(result);
public static class Extensions
public static void Print(this object obj)
Console.WriteLine(obj.ToString());
public class DelegateTest
public static int count = 0;
public static int Increment()
public delegate int IncrementDelegate();
public static event IncrementDelegate MyEvent;
static void Main(string[] args)
IncrementDelegate inc = new IncrementDelegate(Increment);
Console.WriteLine(inc());
IncrementDelegate composedInc = inc;
Console.WriteLine(composedInc());
MyEvent += new IncrementDelegate(Increment);
MyEvent += new IncrementDelegate(Increment);
Console.WriteLine(MyEvent());
protected virtual int Gear
public string Name { get; set; }
public string LongName => Name + " " + _speed + " speed";
public enum BikeAccessories
FullPackage = Bell | MudGuards | Racks | Lights
public BikeAccessories Accessories { get; set; }
public static int BicyclesCreated { get; set; }
readonly bool _hasCardsInSpokes = false;
public Bicycle(int startCadence, int startSpeed, int startGear,
string name, bool hasCardsInSpokes, BikeBrand brand)
_hasCardsInSpokes = hasCardsInSpokes;
public Bicycle(int startCadence, int startSpeed, BikeBrand brand) :
this(startCadence, startSpeed, 0, "big wheels", true, brand)
public void SpeedUp(int increment = 1)
public void SlowDown(int decrement = 1)
private bool _hasTassles;
get { return _hasTassles; }
set { _hasTassles = value; }
public bool IsBroken { get; private set; }
private string[] passengers = { "chris", "phil", "darren", "regina" };
public string this[int i]
public virtual string Info()
" Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") +
"\n------------------------------\n"
public static bool DidWeCreateEnoughBicycles()
return BicyclesCreated > 9000;
class PennyFarthing : Bicycle
public PennyFarthing(int startCadence, int startSpeed) :
base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra)
protected override int Gear
throw new InvalidOperationException("You can't change gears on a PennyFarthing");
public static PennyFarthing CreateWithGears(int gears)
var penny = new PennyFarthing(1, 1);
public override string Info()
string result = "PennyFarthing bicycle ";
result += base.ToString();
class MountainBike : Bicycle, IJumpable, IBreakable
public void Jump(int meters)
Console.WriteLine("Method A1 in class A");
Console.WriteLine("Method A2 in class A");
public int Length { get; set; }
public int Width { get; set; }
static void Main(string[] args)
Rectangle rect = new Rectangle { Length = 5, Width = 3 };
string username = "User";
class GlassBall : IJumpable, IBreakable
public int Damage { get; private set; } = 0;
public string Name { get; } = "Glass ball";
public string GenieName { get; }
public GlassBall(string genieName = null)
public void Jump(int meters)
throw new ArgumentException("Cannot jump negative amount!", nameof(meters));
public override string ToString()
public string SummonGenie()
static class MagicService
private static bool LogException(Exception ex)
public static bool CastSpell(string spell)
throw new MagicServiceException("Spell failed", 42);
catch(MagicServiceException ex) when (ex.Code == 42)
catch(Exception ex) when (LogException(ex))
public class MagicServiceException : Exception
public MagicServiceException(string message, int code) : base(message)
public static class PragmaWarning {
[Obsolete("Use NewMethod instead", false)]
public static void ObsoleteMethod()
public static void NewMethod()
public static void Main()
#pragma warning disable CS0618
#pragma warning restore CS0618
namespace Learning.More.CSharp
Console.WriteLine("The square root of 4 is {}.", Math.Sqrt(4));
Console.WriteLine("The square root of 4 is {}.", Sqrt(4));
public (string, string) GetName()
var names1 = ("Peter", "Parker");
Console.WriteLine(names1.Item2);
(string FirstName, string LastName) names2 = ("Peter", "Parker");
var names3 = (First:"Peter", Last:"Parker");
Console.WriteLine(names2.FirstName);
Console.WriteLine(names3.Last);
public string GetLastName() {
var fullName = GetName();
(string firstName, string lastName) = fullName;
var (_, last) = fullName;
public int randomNumber = 4;
public int anotherRandomNumber = 10;
public void Deconstruct(out int randomNumber, out int anotherRandomNumber)
randomNumber = this.randomNumber;
anotherRandomNumber = this.anotherRandomNumber;
static void Main(string[] args)
var tt = new TuplesTest();
(int num1, int num2) = tt;
Console.WriteLine($"num1: {num1}, num2: {num2}");
Console.WriteLine(tt.GetLastName());
class PatternMatchingTest
public static ref string FindItem(string[] arr, string el)
for(int i=0; i<arr.Length; i++)
throw new Exception("Item not found");
public static void SomeMethod()
string[] arr = {"this", "is", "an", "array"};
ref string item = ref FindItem(arr, "array");
Console.WriteLine(arr[3]);
private static int _id = 0;
public LocalFunctionTest()
public static void AnotherMethod()
var lf1 = new LocalFunctionTest();
var lf2 = new LocalFunctionTest();
Console.WriteLine($"{lf1.id}, {lf2.id}");