<repo_name>seangnewman/Udemy_Advanced_Language_Features<file_sep>/NullCoalescingOperator/Auto_Property.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class Auto_Property
    {
        public class Immutable_Person
        {
            public string Name { get; } = "<NAME>";
        }

        public class Person
        {
            public string Name { get; set; } = "<NAME>";
        }

        public class Complex_Person
        {
            public string Name { get; } = System.Security.Principal.WindowsPrincipal.Current.Identity.Name;
        }

        public static void Demo()
        {
            Console.WriteLine(new Person().Name);

        }
    }
}
<file_sep>/NullCoalescingOperator/LINQ_Queries.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class LINQ_Queries
    {

        public static void Demo()
        {
            string[] names =
            {
            "Tony", "Bruce", "Thor", "Captain", "Vision",
            "Natasha", "Barton", "Pieter", "Hill"

            };

            var results = new List<string>();

            foreach (string name in names)
            {
                if(name.StartsWith("B"))
                {
                    results.Add(name.ToUpper());
                }
            }
        }
        
    }
}




}
}
<file_sep>/NullCoalescingOperator/Soft_Typecast.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class Soft_Typecast
    {
        public static void Demo()
        {
            object[] array = new object[6]
            {
                DateTime.Now,
                true,
                "hello",
                123,
                123.4,
                'x'
            };

            
            int index = 0;

            foreach (object o in array)
            {
                int? i = (o as int?);
               Console.WriteLine("{0}: {1}", index++,   i ?? -1);

            }
        }
    }
}
<file_sep>/NullCoalescingOperator/LINQ.cs
﻿using System;
using System.Linq;

namespace AdvancedFeatures
{
    class LINQ
    {

        public static void Demo()
        {
            string[] names =
            {
                "Billy", "Bob", "Brad", "David", "Duncan", "Everett", "Hannah", "Mark",
                "Michael", "Theo", "Tom", "Victor", "Wendy"
            };



            var results = (from name in names
                          where name.StartsWith("B")
                          select name.ToUpper())
                          .Any() ? "At least 1 name starts with B " : "No names start with B";


            Console.WriteLine(string.Join(" ", results));


            var _groups = from name in names
                          group name by name[0] into groups
                          select groups;

            foreach (var group in _groups)
            {
                Console.WriteLine($"{group.Key} : {string.Join(" ",group)}");
                 
            }

        }
    }
}
<file_sep>/NullCoalescingOperator/ObjectInitializers.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class ObjectInitializers
    {
        public int X { get; set; }
        public int Y { get; set; }

        public struct Point
        {
            public int X;
            public int Y;
        }

        public override string ToString()
        {
            return string.Format($"{X} : {Y}");
        }

        public static void Demo()
        {
            var p1 = new Point { X=6, Y = 9 };

            // Anonymous Types
            var p2 = new { X = 12, Y = 18 };

            // List initialization
            var points1 = new List<Point>
            {
                new Point { X=6,  Y = 0 },
                new Point { X=9,  Y = 3 },
                new Point { X=12, Y = 6 },
                new Point { X=15, Y = 9 }
            };

            // Specifying capacity
            var points2 = new List<Point> (200)
            {
                new Point { X=6,  Y = 0 },
                new Point { X=9,  Y = 3 },
                new Point { X=12, Y = 6 },
                new Point { X=15, Y = 9 }
            };

            // Dictionary
            var colors1 = new Dictionary<int, string>
            {
                {0x00000FF, "Blue" },
                {0x000FF00, "Green" },
                {0x0FF0000, "Blue" }
            };

            // using indexers
            // Dictionary
            var colors2 = new Dictionary<int, string>
            {
                [0x00000FF] = "Blue",
                [0x000FF00] = "Green",
                [0x0FF0000] = "Blue"
            };

        }
    }

   
}
<file_sep>/NullCoalescingOperator/FibonacciSequence.cs
﻿using System.Collections;
using System.Collections.Generic;

namespace AdvancedFeatures
{
    class FibonacciSequence:IEnumerable, IEnumerator
    {
        private int current = 1;
        private int previous = 1;

        public IEnumerator GetEnumerator()
        {
            return this;
        }

        public bool MoveNext()
        {
            int old = current;
            current = current + previous;
            previous = old;
            return current <= 100;
        }

        public void Reset()
        {
            current = 1;
            previous = 1;
        }

        object IEnumerator.Current
        {
            get
            {
                return current;
            }
        }

        


    }

    
}
<file_sep>/NullCoalescingOperator/Using_Statement.cs
﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace AdvancedFeatures
{
    class Using_Statement
    {
        public static void Demo()
        {

            ICryptoTransform decryptor = DecryptString();

            using (var fs = File.Open("encrypted.txt", FileMode.Open)) 
                using ( var cs= new CryptoStream(fs, decryptor, CryptoStreamMode.Read))
                    using(var sr = new StreamReader(cs))
                    {
                        Console.WriteLine(sr.ReadToEnd());
                    }
                
            
             
        }

        

        public static ICryptoTransform DecryptString()
        {
            RijndaelManaged rMan = new RijndaelManaged();
            byte[] salt = Encoding.ASCII.GetBytes("my test salt");
            Rfc2898DeriveBytes passMan = new Rfc2898DeriveBytes("test", salt);
            rMan.Key = passMan.GetBytes(rMan.KeySize / 8);
            rMan.IV = passMan.GetBytes(rMan.BlockSize / 8);

            return  rMan.CreateEncryptor();

       
        }
    }
}
<file_sep>/NullCoalescingOperator/yield_return.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class yield_return
    {
        public static void Demo()
        {
            //var result = from i in Enumerable.Range(1, 98)
            //             where  i % 2 == 0
            //             select i; 

            var results = new FibonacciSequence();

            foreach (var result in results)
            {
                Console.Write($"{result} ");
            }
        }

        public static IEnumerable<int> GetFibonacciSequence()
        {
            int current = 1;
            int previous = 1;

            while (current <= 100)
            {
                yield return current;
                int old = current;
                current = current + previous;
                previous = old;
            }
        }
    }
}
<file_sep>/NullCoalescingOperator/Null_Conditional_Operator.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class Null_Conditional_Operator
    {

        private static string Truncate(string value, int length)
        {
            return value?.Substring(0, Math.Min(value.Length, length));
        }

        public static void Demo()
        {
            string name = Truncate(null, 11);
            Console.WriteLine(name?? "null");
        }
    }
}
<file_sep>/NullCoalescingOperator/Lambda_Expressions.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class Lambda_Expressions
    {
        public delegate int MathOperationDelegate(int number);

        private static int Multiply(int value)
        {
            return value * value;
        }

        public static void Demo()
        {
            int value = 5;
            //int result;

            MathOperationDelegate operation1 = new MathOperationDelegate(Multiply);


            //result = operation1(value);
            //Func<int, int> operation2 = Multiply;
           // var result = operation2(value);

            Func<int, int> operation3 = x => x * x;
            var result = operation3(value);


            Console.WriteLine(result);
        }
    }
}
<file_sep>/NullCoalescingOperator/Await_in_Catch_Finally.cs
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class Await_in_Catch_Finally
    {

        public static async void Demo()
        {
            try
            {
                WebRequest webRequest = WebRequest.Create("http://www.bitesizedcsharp.com");
                WebResponse response = await webRequest.GetResponseAsync();
            }catch(WebException exception)
            {
                await LogError(exception);
                Console.WriteLine("Exception asynchronously logged to file");
            }

        }

        private static async Task LogError(Exception exception)
        {
           using (StreamWriter writer = File.CreateText("error.log"))
            {
                await writer.WriteAsync(exception.Message);
            }
        }
    }
}
<file_sep>/NullCoalescingOperator/Useful_String_Methods.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class Useful_String_Methods
    {
        public static string GetFullName_IsNullOrEmpty(string firstName, string lastName)
        {
            // IsNullOrEmpty, IsNullOrWhiteSpace, String.Equals()
            string result = null;

            if (string.IsNullOrWhiteSpace(firstName))
            {
                return lastName;
            }
            else
            {
                return $"{firstName} {lastName}";
            }

            result = "<NAME>";

            Console.WriteLine("Is this Connor? {0}", string.Equals(result, "<NAME>",
                StringComparison.OrdinalIgnoreCase));
        }
    }
}
<file_sep>/NullCoalescingOperator/Expression_Bodied_Functions_Properties.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class Expression_Bodied_Functions_Properties
    {
        public class Person_With_ToString
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }

            public bool HasFirstName => !string.IsNullOrWhiteSpace(FirstName);

            public override string ToString() => string.Format("{0} {1}", FirstName, LastName);
        }

        public static void Demo()
        {
            var person = new Person_With_ToString();
            person.FirstName = "Cody";
            person.LastName = "Newman";
            if(person.HasFirstName)
            {
                Console.WriteLine(person);
            }
            
        }
    }
}
<file_sep>/NullCoalescingOperator/Declaratopm_Expression.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class Declaratopm_Expression
    {
        public static void Demo()
        {
            int input;

            input = Console.Read();

            while((input = Console.Read()) != 10) // char 10 is the linefeed 
            {
                Console.Write((char)input);
                input = Console.Read();
            }
        }
    }
}
<file_sep>/NullCoalescingOperator/Extension_Methods.cs
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace AdvancedFeatures
{
    static class Extension_Methods
    {

        public static void Demo()
        {
            object obj = GetsSomeObject();

            Console.WriteLine("Obj as string is : {0}", obj.ToXml());
        }

        private static object GetsSomeObject()
        {
            return 123;
        }

        public static string ToXml(this object obj)
        {
            var xs = new XmlSerializer(obj.GetType());
            using (var memoryStream = new MemoryStream())
            using (var xmlTextWriter = new XmlTextWriter(memoryStream, null))
            {
                xs.Serialize(xmlTextWriter, obj);
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
        }
    }
}
<file_sep>/NullCoalescingOperator/NullCoalescingOperator.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedFeatures
{
    class NullCoalescingOperator
    {
        public static string Demo(string value)
        {
            return value ?? string.Empty;
        }

        public static int Demo(int? value)
        {
             
            return value ?? default(int);
        }
    }
}
