21. using System.Console; // 静的メンバーへの簡易アクセス(Using static)
using System.Math; // 静的メンバーへの簡易アクセス(Using static)
using System.Linq.Enumerable; // 静的メンバーへの簡易アクセス(Using static)
class Program
{
static void Main()
{
// 静的メンバーへの簡易アクセス(Using static)
WriteLine("Hello world!");
var root2 = Sqrt(2.0);
// 静的メンバーへの簡易アクセス: 拡張メソッド
var data = new[] { 2, 4, -1, 3, 0 };
var odd = Where(data, number => number % 2 != 0); // Ok
//var even = data.Where(i => i % 2 == 0); // Error, using System.Linq が無いのでスコープ外
}
}
22. using System;
using System.Linq;
class Program
{
static void Main()
{
Console.WriteLine("Hello world!");
var root2 = Math.Sqrt(2.0);
// 静的メンバーへの簡易アクセス: 拡張メソッド
var data = new[] { 2, 4, -1, 3, 0 };
var odd = Enumerable.Where(data, number => number % 2 != 0);
var even = data.Where(i => i % 2 == 0);
}
}
23. using System;
// プライマリコンストラクタ(Primary constructors)
class Employee(int number, string name) // Parameters on
classes
{
{ // プライマリコンストラクタ本体
if (number < 0 || string.IsNullOrWhiteSpace(name))
throw new ArgumentOutOfRangeException();
}
// Explicit constructors
public Employee(string name)
: this(1, name) // プライマリコンストラクタを呼ぶ
{ }
// Getter のみの自動実装プロパティ(Getter-only auto-properties)
// 自動実装プロパティ初期化子(Initializers for auto-properties)
public double Number { get; } = number;
public string Name { get; } = name ;
}
class Staff(int number, string name, DateTime hiredDate)
: Employee(number, name) // ベースクラスのコンストラクタを呼ぶ
{
DateTime hiredDate_ = hiredDate; // 初期化のスコープ
//void TemporaryFunction()
//{
// var hiredDate_ = hiredDate; // NG
//}
}
class Program
{
static void Main()
{
var employee = new Employee(1, "山田太郎");
var staff = new Staff (1, "福井太郎",
DateTime.Now);
}
}
24. using System;
class Employee
{
public Employee(int number, string name)
{
if (number < 0 || string.IsNullOrWhiteSpace(name))
throw new ArgumentOutOfRangeException();
Number = number;
Name = name ;
}
public Employee(string name)
: this(1, name)
{ }
public int Number { get; private set; }
public string Name { get; private set; }
}
class Staff : Employee
{
DateTime hiredDate_;
public Staff(int number, string name, DateTime hiredDate)
: base(number, name) // ベースクラスのコンストラクタを呼ぶ
{
this.hiredDate_ = hiredDate;
}
}
class Program
{
static void Main()
{
var employee = new Employee(1, "山田太郎");
var staff = new Staff (1, "福井太郎",
DateTime.Now);
}
}
25. using System.Console; // 静的メンバーへの簡易アクセス
(Using static)
using System.Math; // 静的メンバーへの簡易アクセス
(Using static)
class Program
{
static void Main()
{
var point1 = new Point();
var point2 = new Point(1.1, 2.2);
(point1 + point2).Print();
}
}
class Point(double x = 0.0, double y = 0.0) // プライマリ
コンストラクタ(Primary constructors)
{
public double X { get; } = x; // Getterのみの自動実装
プロパティ(Getter-only auto-properties)/自動実装プロパティ
初期化子(Initializers for auto-properties)
public double Y { get; } = y; // Getterのみの自動実装
プロパティ(Getter-only auto-properties)/自動実装プロパティ
初期化子(Initializers for auto-properties)
// Expression bodies on property-like function
members
public double Length => Sqrt(X * X + Y * Y); // 静的メ
ンバーへの簡易アクセス(Using static)
// Expression bodies on method-like members
public static Point operator +(Point point1, Point
point2)
=> new Point(point1.X + point2.X, point1.Y +
point2.Y);
// Expression bodies on method-like members (void)
public void Print() => WriteLine("({0}, {1})", X, Y);
// 静的メンバーへの簡易アクセス(Using static)
// Expression bodied indexers
// public double this[int index] => index == 0 ? X :
Y; // not yet
}
26. using System;
class Program
{
static void Main()
{
var point1 = new Point(-0.1, 3.8);
var point2 = new Point(1.1, 2.2);
(point1 + point2).Print();
}
}
class Point
{
public Point(double x = 0.0, double y = 0.0)
{
X = x;
Y = y;
}
public double X { get; private set; }
public double Y { get; private set; }
public double Length
{
get { return Math.Sqrt(X * X + Y * Y); }
}
public static Point operator +(Point point1, Point
point2)
{ return new Point(point1.X + point2.X, point1.Y +
point2.Y); }
public void Print()
{ Console.WriteLine("({0}, {1})", X, Y); }
public double this[int index]
{
get { return index == 0 ? X : Y; }
}
}
27. using System.Console; // 静的メンバーへの簡易アクセス(Using static)
// プライマリコンストラクタ(Primary constructors)
public struct Tally(int count, int sum) // Parameters on structs
{
// Getter のみの自動実装プロパティ(Getter-only auto-properties)
// 自動実装プロパティ初期化子(Initializers for auto-properties)
public int Count { get; } = count;
public int Sum { get; } = sum ;
// Expression bodies on property-like function members
public double Average => (double)Sum / Count;
}
class Program
{
static void Main()
{
var tally = new Tally(10, 500);
WriteLine(tally.Average); // 静的メンバーへの簡易アクセス(Using static)
}
}
28. using System;
public struct Tally
{
int count;
int sum ;
public int Count { get { return count; } }
public int Sum { get { return sum ; } }
public Tally(int count, int sum)
{
this.count = count;
this.sum = sum ;
}
public double Average
{
get { return (double)Sum / Count; }
}
}
class Program
{
static void Main()
{
var tally = new Tally(10, 500);
Console.WriteLine(tally.Average);
}
}
29. using System.Console; // 静的メンバーへの簡易アクセス
(Using static)
using System.Linq;
class Program
{
static void Sub(object item)
{
if ((var text = item as string) != null)
WriteLine(text); // 静的メンバーへの簡易ア
クセス(Using static)
}
static void Main()
{
// 変数宣言式(Declaration expressions)
if (int.TryParse("123", out int number))
WriteLine(number); // 静的メンバーへの簡易ア
クセス(Using static)
var texts = new[] { "123", "a123", "-34", "Q",
"123" };
var sum1 = texts.Select(text =>
int.TryParse(text, out int number) ? number : 0).Sum();
WriteLine(sum1); // 静的メンバーへの簡易アクセス
(Using static)
var sum2 = texts.Select(text =>
int.TryParse(text, out var number) ? number : 0).Sum();
WriteLine(sum2); // 静的メンバーへの簡易アクセス
(Using static)
Sub("ABC");
}
}
30. using System.Console; // 静的メンバーへの簡易アクセス
(Using static)
using System.Linq;
class Program
{
static void Sub(object item)
{
if ((var text = item as string) != null)
WriteLine(text); // 静的メンバーへの簡易ア
クセス(Using static)
}
static void Main()
{
// 変数宣言式(Declaration expressions)
if (int.TryParse("123", out int number))
WriteLine(number); // 静的メンバーへの簡易ア
クセス(Using static)
var texts = new[] { "123", "a123", "-34", "Q",
"123" };
var sum1 = texts.Select(text =>
int.TryParse(text, out int number) ? number : 0).Sum();
WriteLine(sum1); // 静的メンバーへの簡易アクセス
(Using static)
var sum2 = texts.Select(text =>
int.TryParse(text, out var number) ? number : 0).Sum();
WriteLine(sum2); // 静的メンバーへの簡易アクセス
(Using static)
Sub("ABC");
}
}
31. using System.Console; // 静的メンバーへの簡易アクセス(Using static)
class Person
{
public string Name { get; set; }
}
class Program
{
static void Main()
{
// null伝搬演算子(Null-conditional operators)
Person person = null;
var name1 = person?.Name?.Trim() ?? "anonymous";
WriteLine(name1); // 静的メンバーへの簡易アクセス(Using static)
Person[] people = null;
var name2 = people?[0]?.Name?.Trim() ?? "anonymous";
WriteLine(name2); // 静的メンバーへの簡易アクセス(Using static)
}
}
32. using System;
class Person
{
public string Name { get; set; }
}
class Program
{
static void Main()
{
Person person1 = null;
if (person1 != null) {
var name = person1.Name;
if (name != null) {
name = name.Trim();
Console.WriteLine(name);
}
}
Person[] people = null;
if (people != null) {
var person2 = people[0];
if (person2 != null) {
var name = person2.Name;
if (name != null) {
name = name.Trim();
Console.WriteLine(name);
}
}
}
}
}
33. using System;
using System.Console; // 静的メンバーへの簡易アクセス
(Using static)
using System.Threading.Tasks;
// catch/finally でのawait (Await in catch/finally)
class Program
{
static async Task DoSomethingCanFailAsync()
{
await Task.Delay(1000);
if (true)
throw new Exception("Error!");
}
static async Task ErrorFunctionAsync(string
errorMessage)
{
await Task.Delay(1000);
WriteLine(errorMessage); // 静的メンバーへの簡
易アクセス(Using static)
}
static async Task Sub()
{
try {
await DoSomethingCanFailAsync();
} catch (Exception ex) {
await ErrorFunctionAsync(ex.Message);
}
}
static void Main()
{
Sub().Wait();
}
}
34. using System;
using System.Threading.Tasks;
class Program
{
static async Task
DoSomethingCanFailAsync()
{
await Task.Delay(1000);
if (true)
throw new Exception("Error!");
}
static async Task
ErrorFunctionAsync(string errorMessage)
{
await Task.Delay(1000);
Console.WriteLine(errorMessage);
}
{
Exception exception = null;
try {
await DoSomethingCanFailAsync();
} catch (Exception ex) {
exception = ex;
}
if (exception != null)
await
ErrorFunctionAsync(exception.Message);
}
static void Main()
{
Sub().Wait();
}
}
35. using System;
using System.Console; // 静的メンバーへの簡易アクセス
(Using static)
// プライマリコンストラクタ(Primary constructors)
class MyException(MyException.Type state =
MyException.Type.Normal)
: Exception
{
public enum Type
{ Normal, Abnormal }
public Type State { get; } = state; // Getterのみの
自動実装プロパティ(Getter-only auto-properties)/自動実装
プロパティ初期化子(Initializers for auto-properties)
}
class Program
{
static void Sub()
{
throw new MyException(MyException.Type.Abnormal);
}
static void Main()
{
// 例外フィルター(Exception filters)
try {
Sub();
} catch (MyException ex) if (ex.State ==
MyException.Type.Abnormal) { // 例外フィルター(Exception
filters)
WriteLine("catch block: Abnormal."); // 静的メ
ンバーへの簡易アクセス(Using static)
} catch (MyException ex) {
WriteLine("catch block: Normal." ); // 静的メ
ンバーへの簡易アクセス(Using static)
}
}
}
36. using System;
class MyException : Exception
{
public enum Type
{ Normal, Abnormal }
public MyException(MyException.Type state =
MyException.Type.Normal)
{
State = state;
}
public Type State { get; private set; }
}
class Program
{
static void Sub()
{
throw new MyException(MyException.Type.Abnormal);
}
static void Main()
{
try {
Sub();
} catch (MyException ex) {
if (ex.State == MyException.Type.Abnormal)
Console.WriteLine("catch block:
Abnormal.");
else
Console.WriteLine("catch block:
Normal." );
}
}
}
37. using System.Console; // 静的メンバーへの簡易ア
クセス(Using static)
using System.ComponentModel;
class Program
{
static void Main()
{
var person = new Person { FirstName =
"Steve", LastName = "Ballmer" };
person.PropertyChanged += (sender, e)
=> WriteLine(string.Format("{0} has changed.",
e.PropertyName));
person.FirstName = "Satya" ;
person.FirstName = "Nadella";
}
}
public class ViewModelBase :
INotifyPropertyChanged
{
public event PropertyChangedEventHandler
PropertyChanged;
protected void RaisePropertyChanged(string
propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new
PropertyChangedEventArgs(propertyName));
}
}
38. class Person : ViewModelBase
{
string firstName = string.Empty;
public string FirstName
{
get { return firstName; }
set {
if (value != firstName) {
firstName = value;
RaisePropertyChanged(nameof(FirstName)); // nameof演算
子(Nameof expressions)
RaisePropertyChanged(nameof(FullName )); // nameof演算
子(Nameof expressions)
}
}
}
string lastName = string.Empty;
public string LastName
{
get { return lastName; }
set {
if (value != lastName) {
lastName = value;
RaisePropertyChanged(nameof(LastName));
// nameof演算子(Nameof expressions)
RaisePropertyChanged(nameof(FullName));
// nameof演算子(Nameof expressions)
}
}
}
public string FullName
{
get { return string.Format("{0} {1}", FirstName,
LastName); }
}
}
39. using System;
using System.ComponentModel;
class Program
{
static void Main()
{
var person = new Person { FirstName =
"Steve", LastName = "Ballmer" };
person.PropertyChanged += (sender, e)
=> Console.WriteLine(string.Format("{0} has
changed.", e.PropertyName));
person.FirstName = "Satya";
person.FirstName = "Nadella";
}
}
class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler
PropertyChanged;
40. string firstName = string.Empty;
string lastName = string.Empty;
public string FirstName
{
get { return firstName; }
set
{
if (value != firstName) {
firstName = value;
if (PropertyChanged != null) {
PropertyChanged(this, new
PropertyChangedEventArgs("FirstName"));
PropertyChanged(this, new
PropertyChangedEventArgs("FullName" ));
}
}
}
}
public string LastName
{
get { return lastName; }
set
{
if (value != lastName) {
lastName = value;
if (PropertyChanged != null) {
PropertyChanged(this, new
PropertyChangedEventArgs("LastName"));
PropertyChanged(this, new
PropertyChangedEventArgs("FullName"));
}
}
}
}
public string FullName
{
get { return string.Format("{0} {1}", FirstName,
LastName); }
}
}
41. using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
var person = new Person { FirstName =
"Steve", LastName = "Ballmer" };
person.PropertyChanged += (sender, e)
=> Console.WriteLine(string.Format("{0} has
changed.", e.PropertyName));
person.FirstName = "Satya";
person.FirstName = "Nadella";
}
}
public static class
PropertyChangedEventHandlerExtensions
{
public static void Raise(this
PropertyChangedEventHandler onPropertyChanged, object
sender, [CallerMemberName] string propertyName = "")
{
if (onPropertyChanged != null)
onPropertyChanged(sender, new
PropertyChangedEventArgs(propertyName));
}
public static void Raise<PropertyType>(this
PropertyChangedEventHandler onPropertyChanged, object
sender, Expression<Func<PropertyType>>
propertyExpression)
{ onPropertyChanged.Raise(sender,
propertyExpression.GetMemberName()); }
static string GetMemberName<MemberType>(this
Expression<Func<MemberType>> expression)
{ return
((MemberExpression)expression.Body).Member.Name; }
}
42. class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler
PropertyChanged;
string firstName = string.Empty;
string lastName = string.Empty;
public string FirstName
{
get { return firstName; }
set {
if (value != firstName) {
firstName = value;
PropertyChanged.Raise(this);
PropertyChanged.Raise(this, () =>
FullName);
}
}
}
public string LastName
{
get { return lastName; }
set {
if (value != lastName) {
lastName = value;
PropertyChanged.Raise(this);
PropertyChanged.Raise(this, () => FullName);
}
}
}
public string FullName
{
get { return string.Format("{0} {1}", FirstName,
LastName); }
}
}
43. using System.Collections.Generic;
using System.Console; // 静的メンバーへの簡易アクセ
ス(Using static)
class Program
{
static void Main()
{
// Index initializers
// Note: Index initializers have been
previously previewed but do not work in the
current CTP.
var numberNames = new Dictionary<string,
string>
{
{ "二", "two" },
{ "三", "three" },
{ "五", "five" }
};
//var numberNames = new Dictionary<string,
string> {
// ["二"] = "two" ,
// ["三"] = "three",
// ["五"] = "five"
//};
//// Indexed member initializer (Withdrawn)
//var numberNames = new Dictionary<string,
string> {
// $二= "two" ,
// $三= "three",
// $五= "five"
//};
// Indexed member access (Withdrawn)
var numberName = numberNames["三"];
// var numberName = numberNames.$三;
}
}
44. using System.Collections.Generic;
using System.Console; // 静的メンバーへの簡易アクセス(Using static)
class Program
{
static void Main()
{
// Binary literals (Planned)
// var bits = 0b00000100;
// Digit separators (Planned)
// var bits = 0b0010_1110;
// var hex = 0x00_2E;
// var dec = 1_234_567_890;
// Event initializers (Planned)
// new Customer { Notify += MyHandler };
// Params IEnumerable (Planned)
//int Avg(params IEnumerable<int> numbers) { … }
// String interpolation (Maybe)
// "{p.First} {p.Last} is {p.Age} years old.“
}
}