Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# 7 on Linux
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using static System.Console;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().Run();
}
public void Run()
{
WriteLine("*** out variables ***");
PrintCoordinates(new Point(1, 5));
PrintStars("2");
PrintStars("a");
WriteLine("*** Pattern matching ***");
PrintStars(3);
PrintStars2(4);
PrintShape(new Circle(4));
PrintShape(new Rectangle(4, 4));
PrintShape(new Rectangle(4, 6));
PrintShape(new object());
// WriteLine("*** Tuples ***"); //NG
// var names = LookupName(5);
// WriteLine($"found {names.Item1} {names.Item3}.");
// WriteLine($"found {names.first} {names.last}.");
// (string first, string middle, string last) LookupName(4); // tuple elements have names
WriteLine("*** Deconstruction ***");
(var myX, var myY) = new Point(3, 5); // calls Deconstruct(out myX, out myY);
WriteLine($"{myX} {myY}");
WriteLine("*** Local functions ***");
WriteLine(Fibonacci(10));
WriteLine(Filter(new []{1,3,5,6}, i => i % 2 == 0));
WriteLine("*** Literal improvements ***");
var d = 123_456;
var x = 0xAB_CD_EF;
var b = 0b1010_1011_1100_1101_1110_1111;
WriteLine("*** Ref returns and locals ***");
int[] array = { 1, 15, -39, 0, 7, 14, -12 };
ref int place = ref Find(7, array); // aliases 7's place in the array
place = 9; // replaces 7 with 9 in the array
WriteLine(array[4]); // prints 9
}
//out variavles
public void PrintCoordinates(Point p)
{
p.GetCoordinates(out var x, out var y);
//not yet
//p.GetCoordinates(out var x1, out var *);
WriteLine($"({x}, {y})");
}
public void PrintStars(string s)
{
if (int.TryParse(s, out var i)) { WriteLine(new string('*', i)); }
else { WriteLine("Cloudy - no stars tonight!"); }
}
public void PrintStars(object o)
{
if (o is null) return; // constant pattern "null"
if (!(o is int i)) return; // type pattern "int i"
WriteLine(new string('*', i));
}
public void PrintStars2(object o)
{
if (o is int i || (o is string s && int.TryParse(s, out i)))
{
WriteLine(new string('*', i));
}
}
public void PrintShape(object shape)
{
switch(shape)
{
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("<unknown shape>");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}
}
public (string first, string middle, string last) LookupName(long id) // tuple return type
{
//sample
var first = "first" + id;
var middle = "middle" + id;
var last = "last" + id;
return (first, middle, last); // tuple literal
}
public int Fibonacci(int x)
{
if (x < 0) throw new ArgumentException("Less negativity please!", nameof(x));
return Fib(x).current;
(int current, int previous) Fib(int i)
{
if (i == 0) return (1, 0);
var (p, pp) = Fib(i - 1);
return (p + pp, p);
}
}
public IEnumerable<T> Filter<T>(IEnumerable<T> source, Func<T, bool> filter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (filter == null) throw new ArgumentNullException(nameof(filter));
return Iterator();
IEnumerable<T> Iterator()
{
foreach (var element in source)
{
if (filter(element)) { yield return element; }
}
}
}
public ref int Find(int number, int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == number)
{
return ref numbers[i]; // return the storage location, not the value
}
}
throw new IndexOutOfRangeException($"{nameof(number)} not found");
}
//not yet work
// public async ValueTask<long> GetDirectorySize<T>(string path, string searchPattern)
// {
// if (!Directory.EnumerateFileSystemEntries(path, searchPattern).Any())
// return 0;
// else
// return await Task.Run<long>(()=> Directory.GetFiles(path, searchPattern,
// SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)));
// }
}
class Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y) { X = x; Y = y; }
public void Deconstruct(out int x, out int y) { x = X; y = Y; }
public void GetCoordinates(out int x, out int y)
{
x = X;
y = Y;
}
}
struct Circle
{
public int Radius { get; set; }
public Circle(int r)
{
Radius = r;
}
}
struct Rectangle
{
public int Height { get; }
public int Length { get; }
public Rectangle(int h, int l)
{
Height = h;
Length = l;
}
}
class Person
{
private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>();
//not yet
// private int id = GetId();
// public Person(string name) => names.TryAdd(id, name); // constructors
// ~Person() => names.TryRemove(id, out *); // destructors
// public string Name
// {
// get => names[id]; // getters
// set => names[id] = value; // setters
// }
}
class Person2
{
// public string Name { get; }
// public Person2(string name) => Name = name ?? throw new ArgumentNullException(name);
// public string GetFirstName()
// {
// var parts = Name.Split(' ');
// return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException("No name!");
// }
// public string GetLastName() => throw new NotImplementedException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment