/ c# 6.0

C# 6.0

Null-conditional operators

int? numberOfartists = artists?.Count(); 

Artist defaultArtist = artists?[0]; 

Console.WriteLine($"name: {defaultArtist?.Name}"); 

int thecount = artist?Count ?? 0; 

Console.WriteLine("$"Default artist, {defaultArtist?.Name}, is age:{artists?[0]?.Age}");

//var handler = this.SomethingHappened;
//if (handler != null) handler(this, eventArgs);
this.SomethingHappened?.Invoke(this, eventArgs);

String interpolation

var address = string.Format($"334 S. Main St., {city}, {state}, {zip}\n");

var moneyOwed = $"Today: {DateTime.Now.ToShortDateString()}, Dollar owed {money:C}";

public string GetAllGrades() =>
    $@"All Grades: {Grades.OrderByDescending(g => g)
    .Select(s => s.ToString("F2")).Aggregate((partial, element) => $"{partial}, {element}")}";

Index initializers

var myNewDic = new Dictionary<string, string>
{
    ["name"] = "Robert", 
    ["artist"] = "mafia",
    ["FamousQuote"] = ""
};

var array = new[] {"name", "artist"}; 
var thisArrayList = new List<string>(array)
{
    [0] = "Robert", 
    [1] = "Mafia"
}

nameof Expressions

if (IsNullOrWhiteSpace(lastName))
    throw new ArgumentException(message: "Cannot be blank", paramName: nameof(lastName));
    
public string LastName
{
    get { return lastName; }
    set
    {
        if (value != lastName)
        {
            lastName = value;
            PropertyChanged?.Invoke(this, 
                new PropertyChangedEventArgs(nameof(LastName)));
        }
    }
}
private string lastName;

Extention add methods

public class Enrollment : IEnumerable<Student>
{
    private List<Student> allStudents = new List<Student>();

    public void Enroll(Student s)
    {
        allStudents.Add(s);
    }

    public IEnumerator<Student> GetEnumerator()
    {
        return ((IEnumerable<Student>)allStudents).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable<Student>)allStudents).GetEnumerator();
    }
    
    // No Add method
}
public static class StudentExtensions
{
    public static void Add(this Enrollment e, Student s) => e.Enroll(s);
}
var classList = new Enrollment()
{
    new Student("Lessie", "Crosby"),
    new Student("Vicki", "Petty")
}

await in catch and finally blocks

private static async Task LogDataAsync(string details, Exception ex) 
{ 
    using (var thisFile = File.Append.Text("issues.log"))
    {
        await thisFile.WriteLineAsync($"{details} {ex?.ToString()}");
    }
}

private static async void Test_AsnynInCatchFinally()
{
    try
    {
        throw new Exception("Something went wrong");
    }
    catch (Exception ex)
    {
        await LogDataAsync("Problem description -->", ex); 
    }
    finally 
    {
        await LogDataAsync("Complete.", null); 
    }
}

Adding exception filters

private static async void Test_ExceptionFilters()
{
    try
    {
        throw new Exception("Something went wrong");
    }
    catch (Exception ex) when (ex.Message.Substring(0,7) == "Warning")
    {
        // Do nothing. Just warning
    }
    catch (Exception ex)
    {
        await LogDataAsync("Problem description -->", ex); 
    }
    finally 
    {
        await LogDataAsync("Complete.", null); 
    }
}

Auto Properties Initializers

class Artist 
{
    public string Name { get; set;} = "A-List actor";
}

Read-only auto properties

class Artist 
{
    public int Age { get; } = 65;
}

Expression-bodied function members

static public stirng Name => "Jerry Seinfeld";

static public string GetFullName(string firstname, string lastname) => $"{firstname} {lastname}";

static public void PrintFullName(string firstname, string lastname) =>  Console.WriteLine($"{firstname} {lastname}"); 

static public Comedian PrintComedianName(string firstname, string lastname) => new Comedian(firstName, lastname)

usin static

using static System.Math; 
using static System.Console;

class Program
{
    private static void UsingSimplified() 
    {
        WriteLine($"The comedy club was great. But it cost me {Round(59.8)});
    }
}

order of operation with static and instance methods

Console.WriteLine 보다 인스턴스의 WriteLine이 우선함.

using static System.Console;

class Program
{
    internal class writer
    {
        public void SartTest(string statement)
        {
            WriteLine(statement);
        }
        
        public void WriteLine(string statement)
        {
            Console.WriteLine($"Instance method: {statement}");
        }
    }
    
    static private void Test_UsingInstance() 
    {
        Write w = new Writer(); 
        w.StartTest("Good morning"); 
    }
}

Immediate/watch windows on visual Studio

Linq Expression을 Immediate/Watch 윈도우에서 사용가능.

What's New in C# 6