ArrayList array = new ArrayList();
Queue qq = new Queue();
Stack ss = new Stack();
Dictionary<int, string> dictionary =
new Dictionary<int, string>();
List<string> list = new List<string>();
Queue<int> q = new Queue<int>();
Stack<int> stack = new Stack<int>();
LinkedList<string> linked = new LinkedList<string>();
ImmutableList<string> listIn = list.ToImmutableList();
ReadOnlyCollection<string> s = new ReadOnlyCollection<string>(list);
Span<byte> bytes = new Span<byte>();
Memory<byte> bytes2 = new Memory<byte>();
OrderedDictionary ordered = new OrderedDictionary();
StringCollection stringCollection = new StringCollection();
public class UsingEnum<T> where T : System.Enum { }
public class MyGenericClass<T> where T : IComparable<T>, new()
{
// The following line is not possible without new() constraint:
T item = new T();
}
try
{
}
catch (Exception)
{
//NIC
}
public static void Method2(object a)
{
if (a == null)
throw new ArgumentNullException("Jest null");
}
try
{
number = int.Parse(mystr);
// number
}
catch (FormatException)
{
number = 11;
}
//Warto też pamiętać o tym, że try-catch nie powinno nam służyć
//jako mechanizm kontroli przepływu aplikacji.
string mystr = "1";
int number;
if (int.TryParse(mystr, out number))
{
// number
}
else
{
//domyślna wartość
number = 11;
}
try
{
}
catch (Exception ex)
{
throw;
}
try
{
}
catch (Exception ex)
{
throw ex;
}
public class SomeClass
{
public int Value;
}
public class ClassDefault
{
public static int defaultInt;
public static string defaultString;
public static SomeClass defaultSomeClass;
public static List<SomeClass> defaultListOfSomeClass;
}
public class Main_Errors_3_ReferencesTypes
{
public static void Run()
{
int a = ClassDefault.defaultInt;
int b = ClassDefault.defaultInt;
a = a + 2;
b = b + 6;
ClassDefault.defaultSomeClass = new SomeClass();
//referencje
SomeClass sc1 = ClassDefault.defaultSomeClass;
SomeClass sc2 = ClassDefault.defaultSomeClass;
sc1.Value = 2;
sc2.Value = 3;
}
}
class ClassDefaultStruct
{
public static Point defaultThree;
}
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
ClassDefaultTest.defaultThree = new Point();
Point sc1 = ClassDefaultTest.defaultThree;
Point sc2 = ClassDefaultTest.defaultThree;
sc1.X = 2;
sc2.X = 3;
public record Record1(int FirstNumber, int SecondNumber);
//Czy Rekordy są typem wartościowym,
//Czy typem referencyjnym?
Record1 rA = new(1, 2);
Record1 rAtest = rA;
Console.WriteLine(ReferenceEquals(rA, rAtest));
//true
//Podobne do tej klasy, ale to jednak nie to samo
//o tym za chwilę
public class Record3
{
public string FirstNumber { get; init; }
public string SecondNumber { get; init; }
public Record3(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
Console.WriteLine($"Record1 rA = new(1, 2);");
Console.WriteLine($"Record1 rB = new(1, 2);");
Console.WriteLine($"Check if they are Equal : {Equals(rA, rB)}");
Console.WriteLine($"Check if they are ReferenceEquals : " +
$"{ ReferenceEquals(rA, rB)}");
Console.WriteLine($"Hash Code rA: {rA.GetHashCode()}");
Console.WriteLine($"Hash Code rB: {rB.GetHashCode()}");
string s0 = "A";
Console.WriteLine(s0 == "a"); //false
Console.WriteLine(s0.Equals("a")); //false
Console.WriteLine(s0.Equals("a",
StringComparison.Ordinal)); //false
Console.WriteLine(s0.Equals("a",
StringComparison.CurrentCulture)); //false
Console.WriteLine(s0.Equals("a",
StringComparison.OrdinalIgnoreCase)); //true
Console.WriteLine(s0.Equals("a",
StringComparison.CurrentCultureIgnoreCase)); //true
Console.WriteLine(s0.Equals("a",
StringComparison.InvariantCulture)); //false
Console.WriteLine(s0.Equals("a",
StringComparison.InvariantCultureIgnoreCase)); //true
string s0 = "A";
Console.WriteLine(s0 == "a"); //false
Console.WriteLine(s0.Equals("a")); //false
Console.WriteLine(s0.Equals("a",
StringComparison.Ordinal)); //false
Console.WriteLine(s0.Equals("a",
StringComparison.CurrentCulture)); //false
Console.WriteLine(s0.Equals("a",
StringComparison.OrdinalIgnoreCase)); //true
Console.WriteLine(s0.Equals("a",
StringComparison.CurrentCultureIgnoreCase)); //true
Console.WriteLine(s0.Equals("a",
StringComparison.InvariantCulture)); //false
Console.WriteLine(s0.Equals("a",
StringComparison.InvariantCultureIgnoreCase)); //true
string s = "ß";
Console.WriteLine(s == "ss"); //false
Console.WriteLine(s.Equals("ss")); //false
Console.WriteLine(s.Equals("ss",
StringComparison.Ordinal)); //false
Console.WriteLine(s.Equals("ss",
StringComparison.CurrentCulture)); //true
Console.WriteLine(s.Equals("ss",
StringComparison.OrdinalIgnoreCase)); //false
Console.WriteLine(s.Equals("ss",
StringComparison.CurrentCultureIgnoreCase)); //true
Console.WriteLine(s.Equals("ss",
StringComparison.InvariantCulture)); //true
Console.WriteLine(s.Equals("ss",
StringComparison.InvariantCultureIgnoreCase)); //true
string s1 = "æ";
Console.WriteLine(s1 == "ae"); //false
Console.WriteLine(s1.Equals("ae")); //false
Console.WriteLine(s1.Equals("ae",
StringComparison.Ordinal)); //false
Console.WriteLine(s1.Equals("ae",
StringComparison.CurrentCulture)); //true
Console.WriteLine(s1.Equals("ae",
StringComparison.OrdinalIgnoreCase)); //false
Console.WriteLine(s1.Equals("ae",
StringComparison.CurrentCultureIgnoreCase)); //true
Console.WriteLine(s1.Equals("ae",
StringComparison.InvariantCulture)); //true
Console.WriteLine(s1.Equals("ae",
StringComparison.InvariantCultureIgnoreCase)); //true
string line;
StreamReader reader = null;
try
{
reader = new StreamReader("file.txt");
line = reader.ReadLine();
}
finally
{
if (reader != null)
reader.Dispose();
}
string line;
using (StreamReader reader = new StreamReader("file.txt"))
{
line = reader.ReadLine();
}
Console.WriteLine(line);
public void GCTestFinalize()
{
StreamWriter stream = File.CreateText("a.txt");
stream.Write("TEST");
GC.Collect();
GC.WaitForPendingFinalizers();
File.Delete("a.txt");
}
public static bool IsPrime(int number)
{
if (number <= 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
var boundary = (int)Math.Floor(Math.Sqrt(number));
for (int i = 3; i <= boundary; i += 2)
if (number % i == 0)
return false;
return true;
}
List<int> numbers = new List<int>()
{ 200, 400, 500, 933, 130, 150, 230, 240, 525, 134, 516 };
var first = numbers.Where
(x => IsPrime(x)).First();
var first2 = numbers.First(x => IsPrime(x));
var first3 = numbers.FirstOrDefault(x => IsPrime(x));
//INCORRECT
List<string> values = new List<string>()
{ "Hello ", "far ", "Home ", "!" };
string outputValue = string.Empty;
foreach (var value in values)
{
outputValue += value;
}
outputValue = string.Empty;
//CORRECT
StringBuilder outputValueBuilder = new StringBuilder();
foreach (var value in values)
{
outputValueBuilder.Append(value);
}
bool isTrue = true;
if (isTrue == true)
{
// Code
}
if (isTrue)
{
// Code
}
var person = new Person();
//INCORRECT
var woman1 = (Woman)person;
//CORRECT
var woman2 = person as Woman;
//Umieść cokolwiek chcesz
dynamic d1 = "OK";
d1 = 111;
d1 = "Also Ok";
//Wszystko jest okej dopóki dynamiczny obiekt ma
//metodę Remove i toArray()
dynamic d2 = new List<int>() { 4, 5, 5 };
dynamic operationStatus = d2.Remove(4);
dynamic array = d2.ToArray();
d2 = new List<double>() { 1.5, 2.5, 7.5, };
dynamic operationStatus2 = d2.Remove(1.5);
dynamic array2 = d2.ToArray();
dynamic d2 = new List<int>() { 4, 5, 5 };
try
{
//metody
dynamic sum = d2.Sum();
}
catch (Exception)
{
}
dynamic stuff = JsonConvert.DeserializeObject
("{ 'Name': 'Jon Smith'," +
" 'Address':" +
"{ 'City': 'New York', 'State': 'NY' }," +
" 'Age': 42 }");
string name = stuff.Name;
string address = stuff.Address.City;
bool IsBlocked = true;
dynamic person = new System.Dynamic.ExpandoObject();
person.Name = "Cezary";
person.Age = 12;
if (IsBlocked)
{
person.StatusBlocked = true;
}
string json = Newtonsoft.Json.JsonConvert.
SerializeObject(person);
namespace ConsoleAppPresentation.NewDomain
{
public abstract class Employee
{
public string Name { get; set; }
}
public class HR : Employee { }
public class Programmer : Employee { }
}
namespace ConsoleAppPresentation.OldDomain
{
public abstract class Employee
{
public string Name { get; set; }
}
public class HR : Employee { }
public class Programmer : Employee { }
}
public static void Run4()
{
var s1 = GetNameOfEmployee
(new OldDomain.HR() { Name = "CW" });
var s2 = GetNameOfEmployee
(new NewDomain.Programmer { Name = "MS" });
var s3 = GetNameOfEmployee
(new OldDomain.Programmer { Name = "KL" });
var s4 = GetNameOfEmployee
(new NewDomain.HR { Name = "PL" });
var s = ConvertOld
(new OldDomain.Programmer() { Name = "PL" });
}
public static string GetNameOfEmployee(dynamic employee)
{
return employee.Name;
}
public static NewDomain.Employee ConvertOld
(OldDomain.Employee employee)
{
if (employee == null)
return null;
if (employee is OldDomain.HR)
return ConvertInternal((OldDomain.HR)employee);
if (employee is OldDomain.Programmer)
return ConvertInternal((OldDomain.Programmer)employee);
throw new ArgumentException("Unknown Employee", nameof(employee));
}
public static NewDomain.Employee ConvertOld
(OldDomain.Employee employee)
{
if (employee == null)
return null;
if (employee is OldDomain.HR)
return ConvertInternal((OldDomain.HR)employee);
if (employee is OldDomain.Programmer)
return ConvertInternal((OldDomain.Programmer)employee);
throw new ArgumentException("Unknown Employee", nameof(employee));
}
public static NewDomain.Employee Convert
(OldDomain.Employee employee)
{
return employee != null ?
ConvertInternal((dynamic)employee) : null;
}
public static NewDomain.HR ConvertInternal
(OldDomain.HR a)
{
//Konwersja starego na nowy
return new NewDomain.HR();
}
public static NewDomain.Programmer ConvertInternal
(OldDomain.Programmer a)
{
//Konwersja starego na nowy
return new NewDomain.Programmer();
}
foreach (var item in YieldCollectionsEx.NumberCollection())
{
Console.Write(item + " ,");
}
public static class YieldCollectionsEx
{
public static IEnumerable NumberCollection()
{
yield return 1;
yield return 2;
yield return 3;
yield return 4;
}
}
public interface IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}
public interface IEnumerator<T></T>
{
T Current { get; }
bool MoveNext();
void Reset();
}
var collection = YieldCollections.
RandomNumberCollection()
.Take(500);
foreach (var item in collection)
{
Console.Write(item + " ,");
}
public static IEnumerable<int> RandomNumberCollection()
{
while (true)
{
Random r = new Random(Guid.NewGuid()
.GetHashCode());
int number = r.Next();
yield return number;
}
}
public class Gamer
{
public string Name { get; set; }
public int Age { get; set; }
}
Gamer gammer1 = new Gamer
{
Name = "John Smith",
Age = 27
};
int[] tab = new[] { 1, 2, 3 };
List<int> list = new List<int>()
{
1,2,3,4,5,6,7,8,9,0
};
Dictionary<int, int> d =
new Dictionary<int, int>()
{
{1,2}, {3,4}, {5,6}, {7,8}, {9,0}
};
public delegate string calculateAgeEraFunctionPointer(int year);
public delegate string changeTitleFunctionPointer(string name);
public delegate void showTwoStringsPointer(string p1, string p2);
//public delegate string calculateAgeEraFunctionPointer(int year);
Func<int, string> funcPointer = methods.CalculateAgeEra;
//public delegate string changeTitleFunctionPointer(string name);
Func<string, string> titlePointer = methods.UpperCaseName;
public delegate void showTwoStringsPointer(string p1, string p2);
//public delegate void showTwoStringsPointer(string p1, string p2);
Action<string, string> show;
if (f == "1")
show = methods.Show;
else
show = methods.Show2;
private static void DynamicAdd()
{
var m5 = GetMultiX(5);
var m10 = GetMultiX(10);
Console.WriteLine(m5(10));
Console.WriteLine(m10(10));
}
private static Func<int, int> GetMultiX(int staticVal)
{
return x => staticVal * x;
}
public class PersonEntity
{
public string Name { get; set; }
}
public static Expression<Func<T, bool>>
DynamicWhere<T>(object value, string nameProperty)
{
var item = Expression.Parameter(typeof(T), "item");
var prop = Expression.Property(item, nameProperty);
var consVal = Expression.Constant(value);
var equal = Expression.Equal(prop, consVal);
var lambda = Expression.Lambda<Func<T, bool>>(equal, item);
return lambda;
}
IQueryable<PersonEntity> list = new List<PersonEntity>()
{
new PersonEntity() {Name ="Kl" },
new PersonEntity() {Name ="Cez" },
}.AsQueryable(); ;
var lambda = DynamicWhere<PersonEntity>("Cez", "Name");
var result = list.Where(lambda);
var listre = result.ToList();
int? nullValue = null;
int someValue = 5;
var result = nullValue ?? someValue;
string a1 = null;
string a2 = null;
string a3 = "BE";
string a4 = "AA";
var res = a1 ?? a2 ?? a3;
var res2 = a3 ?? a2 ?? a1;
var res3 = a1 ?? a3 ?? a4 ?? a2;
List<int?> list =
new List<int?>
{ null, 2, 3, 4, null, 5 };
int sum = list.Sum(k => k ?? 0);
object someVariableOne = "Cezary";
object someVariableTwo = "Staszek";
var bigString =
string.Format("1 => : {0}, " +
"2 =>: {1}",
someVariableOne, someVariableTwo);
//Nowe od c# 6.0
var bigString2 = $"1 => : {someVariableOne}," +
$" 2 => : {someVariableTwo}";
var bigString3 = $"1 => : {someVariableOne}," +
$" 2 => : {someVariableTwo}";
public class ShippingStage
{
public int? Value { get; set; }
}
public class ProductStage
{
public ShippingStage Shipping { get; set; }
}
public class Product
{
public ProductStage Stage { get; set; }
}
Product p1 = new Product();
Product p2 = new Product()
{ Stage = new ProductStage() };
Product p3 = new Product()
{
Stage = new ProductStage()
{ Shipping = new ShippingStage() }
};
Product p4 = new Product()
{
Stage = new ProductStage()
{
Shipping = new ShippingStage()
{ Value = 2 }
}
};
int val = 0;
if (p1.Stage != null &&
p1.Stage.Shipping != null &&
p1.Stage.Shipping.Value != null)
val = p1.Stage.Shipping.Value.Value;
if (p4.Stage != null && p4.Stage.Shipping
!= null && p4.Stage.Shipping.Value != null)
val = p4.Stage.Shipping.Value.Value;
var value = p1?.Stage?.Shipping?.Value;
var value2 = p2?.Stage?.Shipping?.Value;
var value3 = p3?.Stage?.Shipping?.Value;
var value4 = p4?.Stage?.Shipping?.Value;
string stefan = "";
string na = nameof(stefan);
private static readonly Logger _logger = new Logger();
public static void ShowGamer(Gamer currentGamer)
{
if (currentGamer == null)
_logger.Error("Argument currentGamer is not provided");
if (currentGamer == null)
_logger.Error($"Argument {nameof(currentGamer)} is not provided");
//...
}
public interface IStock
{
void Calculate();
//defaults
void CalculateSubTotal()
{
Console.WriteLine("Calc Sub");
}
}
public class CDProjectRedStock : IStock
{
public void Calculate()
{
Console.WriteLine("Calc");
}
public void CalculateSubTotal()
{
Console.WriteLine("New Calc Sub");
}
}
public class BankPolskiStock : IStock
{
public void Calculate()
{
Console.WriteLine("Calc");
}
}
static async Task Main()
{
await What();
}
static Task What()
{
return new Task(
() => Console.WriteLine("1"));
}
static async Task Main()
{
Task t = What();
await t;
var s = t.Status;
}
static Task What()
{
return new Task(
() => Console.WriteLine("1"));
}
await Task.Run
(
() => DoExpensiveOperation(someParameter)
);
private static string result;
static void Main()
{
SaySomething();
Console.WriteLine(result);
}
static async Task<int> SaySomething()
{
await Task.Delay(10);
result = "Hello!";
return 1;
}
private static string result;
static void Main()
{
SaySomething();
Console.WriteLine(result);
}
static async Task<int> SaySomething()
{
await Task.Delay(10);
result = "Hello!";
return 1;
}
private static string result;
static void Main()
{
SaySomething();
Console.WriteLine(result);
}
static async Task<int> SaySomething()
{
Thread.Sleep(10);
result = "Hello!";
return 1;
}
private static string result;
static void Main()
{
SaySomething();
Console.WriteLine(result);
}
static async Task<int> SaySomething()
{
Thread.Sleep(10);
result = "Hello!";
return 1;
}
List<Task> tasks = new List<Task>();
for (int i = 0; i < 80; i++)
{
tasks.Add(new Task(() => Console.WriteLine(i)));
}
foreach (var item in tasks)
{
item.RunSynchronously();
}
List<Task> tasks = new List<Task>();
for (int i = 0; i < 80; i++)
{
tasks.Add(new Task(() => Console.WriteLine(i)));
}
foreach (var item in tasks)
{
item.RunSynchronously();
}
for (int i = 0; i < 80; i++)
{
Task.Run(() => Console.WriteLine(i));
}
for (int i = 0; i < 11; i++)
{
Task.Run(() => Console.WriteLine(i));
}
Console.Read();
for (int i = 0; i < 80; i++)
{
Task.Run(() => Console.WriteLine(i));
}
for (int i = 0; i < 11; i++)
{
Task.Run(() => Console.WriteLine(i));
}
Console.Read();
List<Task> tasks = new List<Task>();
for (int i = 0; i < 80; i++)
{
int newi = i;
tasks.Add(new Task(() => Console.WriteLine(newi)));
}
foreach (var item in tasks)
{
item.RunSynchronously();
}
List<Task> tasks = new List<Task>();
for (int i = 0; i < 80; i++)
{
int newi = i;
tasks.Add(new Task(() => Console.WriteLine(newi)));
}
foreach (var item in tasks)
{
item.RunSynchronously();
}
for(var i=0; i<4; i++) {
setTimeout(
(function(x) {
return function() {
console.log("i=="+i+", x=="+x);
};
})(i)
, i*100);
}
for(var i=0; i<4; i++) {
setTimeout(
(function(x) {
return function() {
console.log("i=="+i+", x=="+x);
};
})(i)
, i*100);
}
private readonly static string _url = "https://postman-echo.com/delay/10";
private void Button_Click(object sender, RoutedEventArgs e)
{
ResultTextBlock.Text = "";
ResultTextBlock.Text += "Przed MyGetStringAsync()";
var result = MyGetStringAsync().Result;
ResultTextBlock.Text += "Napisze coś w międzyczasie";
ResultTextBlock.Text = result;
ResultTextBlock.Text += "Po MyGetStringAsync()";
}
public async Task<string> MyGetStringAsync()
{
using (HttpClient httpClient = new HttpClient())
{
return await httpClient.GetStringAsync(_url);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ResultTextBlock.Text = "";
ResultTextBlock.Text += "Przed MyGetStringAsync()";
var result = MyGetStringAsync().Result;
ResultTextBlock.Text += "Napisze coś w międzyczasie";
ResultTextBlock.Text = result;
ResultTextBlock.Text += "Po MyGetStringAsync()";
}
public async Task<string> MyGetStringAsync()
{
using (HttpClient httpClient = new HttpClient())
{
return await httpClient.GetStringAsync(_url)
.ConfigureAwait(false);
}
}
public class Weather
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Desc { get; set; }
}
public static List<Weather> CreateExample()
{
DateTime now = DateTime.Now;
var rng = new Random();
var exampleCollection = Enumerable.Range(1, 14).Select
(index => new Weather
{
Date = now.AddDays(index),
TemperatureC = rng.Next(-10, 40)
}
).ToList();
return exampleCollection;
}
foreach (var weather in exampleList)
{
weather.Desc = weather.TemperatureC switch
{
<= 6 and > 1 => "Nie ciekawie. Ubrać sie trzeba",
10 or 9 or 8 or 7 => "Zimno",
11 => "Uwaga Łatwo zachorować",
12 => "Uwaga Kurtka",
13 => "Uwaga",
<= 15 => "Super",
<= 20 => "Ok",
<= 28 => "Gorąco",
>= 30 => "Upał",
_ => "Nie wiem"
};
}
public class Pizza
{
public string Name { get; set; }
public bool HasMeat { get; set; }
public bool HasAnanas { get; set; }
public void Deconstruct(out string name, out bool hasMeat, out bool hasAnanas)
{
name = Name;
hasMeat = HasMeat;
hasAnanas = HasAnanas;
}
}
public class Pizza
{
public string Name { get; set; }
public bool HasMeat { get; set; }
public bool HasAnanas { get; set; }
public void Deconstruct(out string name, out bool hasMeat, out bool hasAnanas)
{
name = Name;
hasMeat = HasMeat;
hasAnanas = HasAnanas;
}
public string Desc { get; set; }
}
public static List<Pizza> CreateExample()
{
var rng = new Random();
var exampleCollection = Enumerable.Range(1, 14).Select
(index => new Pizza
{
Name = "P" + index.ToString() + rng.Next(1, 10).ToString(),
HasMeat = rng.NextDouble() >= 0.5,
HasAnanas = rng.NextDouble() >= 0.5
}
).ToList();
return exampleCollection;
}
Pizza a = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Marinara" };
Pizza b = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Peperoni" };
var (name, hasananas, hasmeat) = a;
var (name2, hasananas2, hasmeat2) = b;
var exampleList = CreateExample();
Pizza a = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Marinara" };
Pizza b = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Peperoni" };
exampleList.Add(b); exampleList.Add(a);
foreach (var pizza in exampleList)
{
pizza.Desc = pizza switch
{
("1", true, false) => "Taką zjem",
("2", true, true) => "Ujdzie",
("Peperoni", _, _) => "Moja ulubiona",
("Marinara", _, _) => "Często jadam",
(_, _, true) => "Tej nie zjem",
_ => "Nie wiem"
};
}
var exampleList = CreateExample();
Pizza a = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Marinara" };
Pizza b = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Peperoni" };
exampleList.Add(b); exampleList.Add(a);
foreach (var pizza in exampleList)
{
pizza.Desc = pizza switch
{
("2", _, var czymaAnans) => $"Pizza z Ananasem : {czymaAnans}",
{ HasMeat : true} => "Ma mieso"
};
}
var exampleList = CreateExample();
Pizza a = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Marinara" };
Pizza b = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Peperoni" };
exampleList.Add(b); exampleList.Add(a);
foreach (var pizza in exampleList)
{
pizza.Desc = pizza switch
{
("2", _, var czymaAnans) => $"Pizza z Ananasem : {czymaAnans}",
};
}
var exampleList = CreateExample();
Pizza a = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Marinara" };
Pizza b = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Peperoni" };
exampleList.Add(b); exampleList.Add(a);
foreach (var pizza in exampleList)
{
pizza.Desc = pizza switch
{
("2", _, var czymaAnans) => $"Pizza z Ananasem : {czymaAnans}",
};
}
var exampleList = CreateExample();
Pizza a = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Marinara" };
Pizza b = new Pizza() { HasAnanas = false, HasMeat = true, Name = "Peperoni" };
exampleList.Add(b); exampleList.Add(a);
foreach (var pizza in exampleList)
{
pizza.Desc = (pizza.HasMeat, pizza.HasAnanas) switch
{
(true, false) => "Super",
(false, true) => "Poprostu nie",
(false, false) => "Bez mięsa ?"
};
}
public class GreenTest : Test
{
}
public class RedTest : Test
{
}
public class Test
{
}
public static List<Test> CreateExample()
{
var rng = new Random();
List<Test> tests = new List<Test>();
for (int i = 0; i < 15 ; i++)
{
if (rng.Next(1,100) % 2 == 0)
tests.Add(new GreenTest());
else
tests.Add(new RedTest());
}
return tests;
}
var exampleList = CreateExample();
foreach (var test in exampleList)
{
string outcome = test switch
{
GreenTest => "Postive",
RedTest => "Negative",
_ => "unknow"
};
Console.WriteLine(outcome);
}
public class GreenTest : Test
{
}
public class RedTest : Test
{
}
public class Test
{
public bool IsValid { get; set; }
public DateTimeOffset TestedOn { get; set; }
public void Deconstruct(out int minutesSinceTest, out bool isValid)
{
minutesSinceTest = (int)(DateTimeOffset.UtcNow - TestedOn).TotalMinutes;
isValid = IsValid;
}
}
var exampleList = CreateExample();
foreach (var test in exampleList)
{
string outcome = test switch
{
( < 60 * 24 * 2, false) => "Nie poprawny test których jest młodszy niż 2 dni",
GreenTest(> 60 * 24, true) => "Postive, ale warto go po 24 godzinach zrobić ponownie",
_ => "unknow"
};
Console.WriteLine(outcome);
}