C# Pytania kwalfikacyjne, Błędy, Sztuczki, Async problemy, i Pattern Matching

Cezary Walenciuk

C# Pytania kwalfikacyjne, Błędy
Sztuczki
Async problemy
i Pattern Matching

@walenciukC

Speaker
Błąd numer 1 : Używanie złej kolekcji
  1. Array
  1. Span
  1. List

Błąd numer 1 : Używanie złej kolekcji

                    
                        ArrayList array = new ArrayList();
                        Queue qq = new Queue();
                        Stack ss = new Stack();
                    
                

Błąd numer 1 : Używanie złej kolekcji

                    
                        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();
                    
                

blog
Copyright © Cezary Walenciuk
blog
Copyright © 2019 Diagram
blog
Copyright © 2019 Diagram

Jak ograniczyć typy generyczne?

                    
                        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();
                        }
                    
                

Błąd numer 2 : Try / Catch

Błąd numer 2 : Try / Catch

                    
                        try
                        {
            
                        }
                        catch (Exception)
                        {
            
                            //NIC

                        }
                    
                

Błąd numer 2 : Try / Catch

                    
                        public static void Method2(object a)
                        {
                            if (a == null)
                                throw new ArgumentNullException("Jest null");
                        }
                    
                

Błąd numer 2 : Try / Catch

                    
                        try
                        {
                            number = int.Parse(mystr);
                            // number
                        }
                        catch (FormatException)
                        {
                            number = 11;
                        }
                    
                

Błąd numer 2 : Try / Catch

                    
                        //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;
                        }
                    
                

Błąd numer 2 : Try / Catch

                    
                        try
                        {
            
                        }
                        catch (Exception ex)
                        {
                            throw;
                        }
            
            
                        try
                        {
            
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    
                

blog
Copyright © 2019 Diagram
blog
Copyright © 2019 Diagram
Błąd numer 3 : Mylenie typu wartościowego z referencyjnym

Błąd numer 3 : Mylenie typu wartościowego z referencyjnym

                    
                        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;
                        }
                    
                

Błąd numer 3 : Mylenie typu wartościowego z referencyjnym

                    
                        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;
                            }
                        }
                    
                

Błąd numer 3 : Mylenie typu wartościowego z referencyjnym

                    
                        class ClassDefaultStruct
                        {
                            public static Point defaultThree;
                        }
                    
                        public struct Point
                        {
                            public int X { get; set; }
                            public int Y { get; set; }
                        }
                    
                

Błąd numer 3 : Mylenie typu wartościowego z referencyjnym

                    
                        ClassDefaultTest.defaultThree = new Point();

                        Point sc1 = ClassDefaultTest.defaultThree;
                        Point sc2 = ClassDefaultTest.defaultThree;
                        
                        sc1.X = 2;
                        sc2.X = 3;
                    
                

blog
Copyright © 2019 Diagram
blog
Copyright © 2019 Diagram
Błąd numer 4 : Mylenie klasy z rekordem

Błąd numer 4 : Mylenie klasy z rekordem

                    
                        public record Record1(int  FirstNumber, int SecondNumber);

                        //Czy Rekordy są typem wartościowym, 
                        //Czy typem referencyjnym?
                    
                

Błąd numer 4 : Mylenie klasy z rekordem

                    
                        Record1 rA = new(1, 2);
                        Record1 rAtest = rA;
                        Console.WriteLine(ReferenceEquals(rA, rAtest));

                        //true
                    
                

Błąd numer 4 : Mylenie klasy z rekordem

                    
                        //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;
                            }
                        }
                    
                

Błąd numer 4 : Mylenie klasy z rekordem

                    
                        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()}");
                    
                

blog
Copyright © 2019 Diagram
Błąd numer 5 : Porównywanie napisów

Błąd numer 5 : Porównywanie napisów

                    
                        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
                    
                

Błąd numer 5 : Porównywanie napisów

                    
                        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
                    
                

blog
Copyright © Cezary Walenciuk

Błąd numer 5 : Porównywanie napisów

                    
                        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
                    
                

blog
Copyright © Cezary Walenciuk

Błąd numer 5 : Porównywanie napisów

                    
                        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
                    
                

Błąd numer 6 : Uwalnianie zasobów

Błąd numer 6 : Uwalnianie zasobów

                    
                        string line;

                        StreamReader reader = null;
                        try
                        {
                            reader = new StreamReader("file.txt");
                            line = reader.ReadLine();
                        }
                        finally
                        {
                            if (reader != null)
                                reader.Dispose();
                        }
                    
                

Błąd numer 6 : Uwalnianie zasobów

                    
                        string line;

                        using (StreamReader reader = new StreamReader("file.txt"))
                        {
                            line = reader.ReadLine();
                        }

                        Console.WriteLine(line);
                    
                

blog
Copyright © Cezary Walenciuk
blog
Copyright © Cezary Walenciuk

Co robi metoda Finalize, Dispose?

                    
                        public void GCTestFinalize()
                        {
                            StreamWriter stream = File.CreateText("a.txt");
                            stream.Write("TEST");
                            
                            GC.Collect();
                            GC.WaitForPendingFinalizers();
                            
                            File.Delete("a.txt");
                        }
                    
                

Czy metoda finalize zawsze się wykona?

Błąd numer 7 : First i czy zawsze tak będzie

Błąd numer 7 : First i czy zawsze tak będzie

                    
                        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;
                        }
                    
                

Błąd numer 7 : First i czy zawsze tak będzie

                    
                        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));
                    
                

blog
Copyright © Cezary Walenciuk
Błąd numer 8 : Łączenie napisów

Błąd numer 8 : Łączenie napisów

                    
                        //INCORRECT
                        List<string> values = new List<string>()
                        { "Hello ", "far ", "Home ", "!" };

                        string outputValue = string.Empty;
            
                        foreach (var value in values)
                        {
                            outputValue += value;
                        }
                    
                

Błąd numer 8 : Łączenie napisów

                    
                        outputValue = string.Empty;

                        //CORRECT
                        StringBuilder outputValueBuilder = new StringBuilder();
                        foreach (var value in values)
                        {
                            outputValueBuilder.Append(value);
                        }
                    
                

Błąd numer 9 : Wyrażenia logiczne

Błąd numer 9 : Wyrażenia logiczne

                    
                        bool isTrue = true;

                        if (isTrue == true)
                        {
                            // Code
                        }
            
                        if (isTrue)
                        {
                            // Code
                        }
            
                    
                

Błąd numer 10 : Niezakładaj, że zawsze tak będzie

Błąd numer 10 : Niezakładaj, że zawsze tak będzie

                    
                        var person = new Person();

                        //INCORRECT
                        var woman1 = (Woman)person;
            
                        //CORRECT
                        var woman2 = person as Woman;
                    
                

Po co jest dynamic?
blog
Copyright © Cezary Walenciuk

Po co jest dynamic?

                    
                        //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();
                    
                

Po co jest dynamic?

                    
                        dynamic d2 = new List<int>() { 4, 5, 5 };

                        try
                        {
                            //metody
                            dynamic sum = d2.Sum();
                        }
                        catch (Exception)
                        {
            
                        }
                    
                

Po co jest dynamic?

                    
                        dynamic stuff = JsonConvert.DeserializeObject
                        ("{ 'Name': 'Jon Smith'," +
                        " 'Address':" +
                        "{ 'City': 'New York', 'State': 'NY' }," +
                        " 'Age': 42 }");
        
                        string name = stuff.Name;
                        string address = stuff.Address.City;
                    
                

Po co jest dynamic?

                    
                        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);
                    
                

DuckTyping w C#?

DuckTyping w C#?

                    
                        namespace ConsoleAppPresentation.NewDomain
                        {
                            public abstract class Employee
                            {
                                public string Name { get; set; }
                            }
                            public class HR : Employee { }
                            public class Programmer : Employee { }
                        }
                    
                

DuckTyping w C#?

                    
                        namespace ConsoleAppPresentation.OldDomain
                        {
                            public abstract class Employee
                            {
                                public string Name { get; set; }
                            }
                            public class HR : Employee { }
                            public class Programmer : Employee { }
                        }
                    
                

DuckTyping w C#?

                    
                        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;
                        }
                
                    
                

DuckTyping w C#?

                    
                        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));
                        }
                    
                

DuckTyping w C#?

                    
                        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));
                        }
                    
                

DuckTyping w C#?

                    
                        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();
                        }
                    
                

Sztuczki w C#
Sztuczki w C# : Yield

Sztuczki w C# : Yield

                    
                        foreach (var item in YieldCollectionsEx.NumberCollection())
                        {
                            Console.Write(item + " ,");
                        }
                    
                

Sztuczki w C# : Yield

                    
                        public static class YieldCollectionsEx
                        {
                            public static IEnumerable NumberCollection()
                            {
                                yield return 1;
                                yield return 2;
                                yield return 3;
                                yield return 4;
                            }
                        }
                    
                

Sztuczki w C# : Yield

                    
                        public interface IEnumerable<out T> : IEnumerable
                        {
                            IEnumerator<T> GetEnumerator();
                        }

                        public interface IEnumerator<T></T>
                        {
                            T Current { get; }
                            bool MoveNext();
                            void Reset();
                        }
                    
                

Sztuczki w C# : Yield

                    
                        var collection = YieldCollections.
                        RandomNumberCollection()
                        .Take(500);
            
                        foreach (var item in collection)
                        {
                            Console.Write(item + " ,");
                        }
                    
                

Sztuczki w C# : Yield

                    
                        public static IEnumerable<int> RandomNumberCollection()
                        {
                            while (true)
                            {
                                Random r = new Random(Guid.NewGuid()
                                    .GetHashCode());

                                int number = r.Next();

                                yield return number;
                            }
                        }
                    
                

blog
Copyright © Cezary Walenciuk
2: Sztuczki w C# : Tworzenie kolekcji

2: Sztuczki w C# : Tworzenie kolekcji

                    
                        public class Gamer
                        {
                            public string Name { get; set; }
                            public int Age { get; set; }
                        }
                    
                

2: Sztuczki w C# : Tworzenie kolekcji

                    
                        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}
                        };
                    
                

3: Action i Func

3: Sztuczki w C# : Action i Func

                    
                        public delegate string calculateAgeEraFunctionPointer(int year);

                        public delegate string changeTitleFunctionPointer(string name);

                        public delegate void showTwoStringsPointer(string p1, string p2);
                    
                

3: Sztuczki w C# : Action i Func

                    
                        //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);
                    
                

blog
Copyright © Cezary Walenciuk

3: Sztuczki w C# : Action i Func

                    
                        //public delegate void showTwoStringsPointer(string p1, string p2);

                        Action<string, string> show;

                        if (f == "1")
                            show = methods.Show;
                        else
                            show = methods.Show2;
                    
                

blog
Copyright © Cezary Walenciuk

3: Sztuczki w C# : Action i Func

                    
                        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;
                        }
                    
                

Sztuczki w C# 4: Wyrażenia drzewiaste czyli tworzenie dynamiczne wyrażenia Linq

4: Wyrażenia drzewiaste czyli tworzenie dynamiczne wyrażenia Linq

                    
                        public class PersonEntity
                        {
                            public string Name { get; set; }
                        }
                    
                

4: Wyrażenia drzewiaste czyli tworzenie dynamiczne wyrażenia Linq

                    
                        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;
                        } 
                    
                

4: Wyrażenia drzewiaste czyli tworzenie dynamiczne wyrażenia Linq

                    
                        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();
                    
                

Sztuczki w C# 5 : Null coalescing operator

5 : Null-coalescing-operator

                    
                        int? nullValue = null;
                        int someValue = 5;
            
                        var result = nullValue ?? someValue;
                    
                

5 : Null-coalescing-operator

                    
                        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;
                    
                

blog
Copyright © Cezary Walenciuk

5 : Null-coalescing-operator

                    
                        List<int?> list =
                        new List<int?>
                        { null, 2, 3, 4, null, 5 };
        
                        int sum = list.Sum(k => k ?? 0);
                    
                

Sztuczki w C# : String Interpolation

6 : StringInterpolation

                    
                        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}";
                    
                

Sztuczki w C# : Null Conditional ElvisOperator

7 : Null Conditional ElvisOperator

                    
                        public class ShippingStage
                        {
                            public int? Value { get; set; }
                        }
                
                        public class ProductStage
                        {
                            public ShippingStage Shipping { get; set; }
                        }
                
                        public class Product
                        {
                            public ProductStage Stage { get; set; }
                        }
                    
                

7 : Null Conditional ElvisOperator

                    
                        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 }
                            }
                        };
                    
                

7 : Null Conditional ElvisOperator

                    
                        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;
                    
                

blog
Copyright © Cezary Walenciuk
Sztuczki w C# : name of

8 : name of

                    
                        string stefan = "";
                        string na = nameof(stefan);
                    
                

8 : name of

                    
                        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");
                
                            //...
                        }
                    
                

Sztuczki w C# : Interface
blog
Copyright © Cezary Walenciuk

8 : Interface

                    
                        public interface IStock
                        {
                            void Calculate();
                    
                            //defaults
                            void CalculateSubTotal()
                            {
                                Console.WriteLine("Calc Sub");
                            }
                        }
                    
                

8 : Interface

                    
                        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");
                            }
                        }
                    
                

blog
Copyright © Cezary Walenciuk
Async Problemy
Async Problemy : Nie mieszać Task API z async i await

Async Problemy : Nie mieszać Task API z async i await

                    
                        static async Task Main()
                        {
                            await What();
                        }
                
                        static Task What()
                        {
                            return new Task(
                                () => Console.WriteLine("1"));
                
                        }
                    
                

Async Problemy : Nie mieszać Task API z async i await

                    
                        static async Task Main()
                        {
                            Task t = What();
                            await t;
                
                            var s = t.Status;
                        }
                
                        static Task What()
                        {
                            return new Task(
                                () => Console.WriteLine("1"));
                        }
                    
                

Async Problemy : Nie mieszać Task API z async i await

                    
                        await Task.Run
                        (
                            () => DoExpensiveOperation(someParameter)
                        );
                    
                

Async Problemy :
Podchwytliwe pytania z Task.Delay

Async Problemy : Podchwytliwe pytania z Task.Delay

                    

                        private static string result;

                        static void Main()
                        {
                            SaySomething();
                            Console.WriteLine(result);
                        }
                    
                        static async Task<int> SaySomething()
                        {
                            await Task.Delay(10);
                            result = "Hello!";
                            return 1;
                        }
                    
                

💡 Co pojawi się w konsoli?

Async Problemy : Podchwytliwe pytania z Task.Delay

                    

                        private static string result;

                        static void Main()
                        {
                            SaySomething();
                            Console.WriteLine(result);
                        }
                    
                        static async Task<int> SaySomething()
                        {
                            await Task.Delay(10);
                            result = "Hello!";
                            return 1;
                        }
                    
                

💡 Co pojawi się w konsoli?

[NIC]

Async Problemy : Podchwytlie pytania z Task.Delay

                    

                        private static string result;

                        static void Main()
                        {
                            SaySomething();
                            Console.WriteLine(result);
                        }
                
                        static async Task<int> SaySomething()
                        {
                            Thread.Sleep(10);
                            result = "Hello!";
                            return 1;
                        }
                    
                

💡 Co pojawi się w konsoli?

Async Problemy : Podchwytlie pytania z Task.Delay

                    

                        private static string result;

                        static void Main()
                        {
                            SaySomething();
                            Console.WriteLine(result);
                        }
                
                        static async Task<int> SaySomething()
                        {
                            Thread.Sleep(10);
                            result = "Hello!";
                            return 1;
                        }
                    
                

💡 Co pojawi się w konsoli?

Hello
Async Problemy : Podchwytliwe pytanie na temat domknięć w C#

Async Problemy : Podchwytliwe pytanie na temat domknięć w C#

                    

                        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();
                        }
                    
                

💡 Co pojawi się w konsoli?

Async Problemy : Podchwytliwe pytanie na temat domknięć w C#

                    

                        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();
                        }
                    
                

💡 Co pojawi się w konsoli?

80

Async Problemy : Podchwytliwe pytanie na temat domknięć w C#

                    

                        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();
                    
                

💡 Co pojawi się w konsoli?

Async Problemy : Podchwytliwe pytanie na temat domknięć w C#

                    

                        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();
                    
                

💡 Co pojawi się w konsoli?

[Wynik będzie losowy i liczby będą się powtarzać]
blog
Copyright © Cezary Walenciuk

Async Problemy : Podchwytliwe pytanie na temat domknięć w C#

                    

                        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();
                        }
                    
                

💡 Co pojawi się w konsoli?

Async Problemy : Podchwytliwe pytanie na temat domknięć w C#

                    

                        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();
                        }
                    
                

💡 Co pojawi się w konsoli?

[0,1,2...79]
JavaScript
To samo pytanie można zadać w JavaScript

JavaScript To samo pytanie można zadać w JavaScript

                    
                        for(var i=0; i<4; i++) {

                            setTimeout(
                              (function(x) {
                                return function() {  
                                  console.log("i=="+i+", x=="+x);
                                };

                              })(i) 
                            , i*100);

                        }
                    
                

💡 Co pojawi się w konsoli?

JavaScript To samo pytanie można zadać w JavaScript

                    

                        for(var i=0; i<4; i++) {

                            setTimeout(
                              (function(x) {
                                return function() {  
                                  console.log("i=="+i+", x=="+x);
                                };

                              })(i) 
                            , i*100);

                        }
                    
                

💡 Co pojawi się w konsoli?

i==4,x==0,i==4,x==1...
Async problemy : Jak zrobić deadlock

Async problemy : Jak zrobić deadlock

                    

                        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);
                            }
                        }
                    
                

Async problemy : Jak zrobić deadlock

                    
                        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);
                            }
                        }
                    
                

Pattern Matching w C# 8.0 i 9.0
Patter Matching w switch

Patter Matching w switch : przykład

                    
                        public class Weather
                        {
                            public DateTime Date { get; set; }
                    
                            public int TemperatureC { get; set; }
                    
                            public string Desc { get; set; }
                        }
                    
                

Patter Matching w switch : przykład

                    
                        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;
                        }
                    
                

Patter Matching w switch : przykład

                    
                        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"
                            };
                        }
                    
                

blog
Copyright © Cezary Walenciuk

Patter Matching w switch : przykład

                    
                        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;
                            }
                        }
                    
                

Patter Matching w switch : przykład

                    
                        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; }
                        }
                    
                

Patter Matching w switch : przykład

                    
                        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;
                        }
                    
                

Patter Matching w switch : przykład

                    
                        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;
                    
                

Positional Pattern

Patter Matching w switch : Positional Pattern

                    
                        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"
                            };
                        }
                    
                

Patter Matching w switch : Positional Pattern

                    
                        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"
                            };
                        }
                    
                

blog
Copyright © Cezary Walenciuk

Patter Matching w switch : Positional Pattern

                    
                        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}",
                            };
                        }
                    
                

blog
Copyright © Cezary Walenciuk

Patter Matching w switch : Positional Pattern

                    
                        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}",
                            };
                        }
                    
                

Tuple Pattern

Patter Matching w switch : Tuple Pattern

                    
                        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 ?"
                            };
                        }
                    
                

Patterns w C# 9.0

Type pattern

Patter Matching w switch : Type pattern

                    
                        public class GreenTest : Test
                        {
                    
                        }
                    
                        public class RedTest : Test
                        {
                    
                        }
                    
                        public class Test
                        {
                    
                        }
                    
                

Patter Matching w switch : Type pattern

                    
                        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;
                        }
                    
                

Patter Matching w switch : Type pattern

                    
                        var exampleList = CreateExample();

                        foreach (var test in exampleList)
                        {
                            string outcome = test switch
                            {
                                GreenTest => "Postive",
                                RedTest => "Negative",
                                _ => "unknow"
                            };
                            Console.WriteLine(outcome);
                        }
                    
                

Relational pattern

Patter Matching w switch : Relational pattern

                    
                        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;
                            }
                        }
                    
                

Patter Matching w switch : Relational pattern

                    
                        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);
                        }
                    
                

Dzięki za obecność