WEB系、アプリ系でC#を使っている会社は少ない?
使っている企業とか
そもそもC#って
Microsoft製
型がある
オブジェクト指向
継承があったりインターフェースがあったり抽象クラスがあったり
public class Child : Parent
{
private readonly string str;
private readonly int num;
public Child(string str, int num)
{
this.str = str;
this.num = num;
}
public string GetContent()
{
return $"str = {str}, num = {num}";
}
}
var child = new Child("test", 1);
child.GetContent();
// str = test, num = 1
C#のいいと思う機能
型推論
// int型に
var num = 1;
// List<string>型に
var strList = new List<string>() { };
getter, setter, メンバ
public class People
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get => $"{FirstName}{LastName}";
}
}
var people = new People();
people.FirstName = "Taro";
people.LastName = "Tanaka";
Console.WriteLine(people.FullName);
プロパティごとにアクセス修飾子を変えることもできる
public int Age
{
get;
private set;
}
readonlyというものも
public class People
{
private readonly DateTime birthday;
public People(DateTime birthday)
{
this.birthday = birthday;
}
}
インスタンスフィールドであればコンストラクタ内でのみ割り当て可能
初期化
オブジェクト初期化子
public class People
{
public string FirstName { get; set; }
public string LastName { get; set; }
public People() { }
}
var people = new People()
{
FirstName = "Taro",
LastName = "Tanaka"
};
名前付き引数
public class People
{
public People(int age, DateTime birthday)
{
// 処理
}
}
var people = new People(age: 5, birthday: DateTime.Now);
async await
単数のタスク
public async Task<string> GetSingleAsync()
{
var result = await GetStringAsync();
return $"結果={result}";
}
private Task<string> GetStringAsync()
{
var task = Task<string>.Run(() =>
{
// 何か重い処理
return "async!";
});
return task;
}
var single = new SampleAsync().GetSingleAsync().Result;
複数のタスク
public async Task<string> GetMultiAsync()
{
var task1 = GetStringAsync();
var task2 = GetStringAsync();
var task3 = GetStringAsync();
var task4 = GetIntAsync();
var results = await Task.WhenAll(task1, task2, task3);
return string.Join(",", results);
}
var multi = new SampleAsync().GetMultiAsync().Result;
LINQ
コレクションを便利に扱える拡張メソッド
var arr = new string[] { "a", "bb", "ccc" };
// 含んでいるか
arr.Any(s => s == "a");
// True
// 絞り込み
arr.Where(s => s.Length >= 2);
// IEnumerable<string> { "bb", "ccc" }
// 射影
arr.Select(s => s + s);
// IEnumerable<string> { "aa", "bbbb", "cccccc" }
IEnumerableな値が返されるためメソッドチェーンで書くことが可能
arr.Where(s => s.Length >= 2)
.Select(s => s + s)
.ToArray();
他にも
- 拡張メソッド
- ジェネリクス
- 属性定義、Attribute
- null条件演算子
- 例外フィルター
- タプル、分解
マルチプラットフォームに
すでにWindowsだけのものではない
MacやUbuntuでだって開発できる
(引用元:Microsoft really does love Linux)