Skip to content

Instantly share code, notes, and snippets.

@tuannguyenssu
Created August 2, 2019 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuannguyenssu/7f76013c4e8ca5c1e27d4945e6f88663 to your computer and use it in GitHub Desktop.
Save tuannguyenssu/7f76013c4e8ca5c1e27d4945e6f88663 to your computer and use it in GitHub Desktop.
//--------------------------------------------------------------------------------------
// C# 7.0 Features - Các tính năng nổi bật trên phiên bản C# 7.0
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
// 1. Out varibales
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
// Các phiên bản trước
int result;
if (int.TryParse(input, out result))
Console.WriteLine(result);
//--------------------------------------------------------------------------------------
// C# 7 cho phép khai báo biến out trực tiếp trong hàm
if (int.TryParse(input, out int result))
Console.WriteLine(result);
//--------------------------------------------------------------------------------------
// 2. Tuples
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
// Việc khai báo tuple giờ đã linh hoạt và tường minh hơn
(string Alpha, string Beta) namedLetters = ("a", "b");
Console.WriteLine($"{namedLetters.Alpha}, {namedLetters.Beta}");
var alphabetStart = (Alpha: "a", Beta: "b");
Console.WriteLine($"{alphabetStart.Alpha}, {alphabetStart.Beta}");
(int max, int min) = Range(numbers);
Console.WriteLine(max);
Console.WriteLine(min);
//--------------------------------------------------------------------------------------
// 3. Discards : Sử dụng ký tự _ cho các trường hợp mà ta không quan tâm
//--------------------------------------------------------------------------------------
private static (string, double, int, int, int, int) QueryCityDataForYears(string name, int year1, int year2)
{
int population1 = 0, population2 = 0;
double area = 0;
if (name == "New York City") {
area = 468.48;
if (year1 == 1960) {
population1 = 7781984;
}
if (year2 == 2010) {
population2 = 8175133;
}
return (name, area, year1, population1, year2, population2);
}
return ("", 0, 0, 0, 0, 0);
}
var (_, _, _, pop1, _, pop2) = QueryCityDataForYears("New York City", 1960, 2010);
//--------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------
// 4. Pattern matching
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
// is operator
if (input is int count)
sum += count;
//--------------------------------------------------------------------------------------
// switch
public static int SumPositiveNumbers(IEnumerable<object> sequence)
{
int sum = 0;
foreach (var i in sequence)
{
switch (i)
{
case 0:
break;
case IEnumerable<int> childSequence:
{
foreach(var item in childSequence)
sum += (item > 0) ? item : 0;
break;
}
case int n when n > 0:
sum += n;
break;
case null:
throw new NullReferenceException("Null found in sequence");
default:
throw new InvalidOperationException("Unrecognized type");
}
}
return sum;
}
//--------------------------------------------------------------------------------------
// 5. Ref locals and returns
//--------------------------------------------------------------------------------------
public static ref int Find(int[,] matrix, Func<int, bool> predicate)
{
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
if (predicate(matrix[i, j]))
return ref matrix[i, j];
throw new InvalidOperationException("Not found");
}
ref var item = ref MatrixSearch.Find(matrix, (val) => val == 42);
Console.WriteLine(item);
item = 24;
Console.WriteLine(matrix[4, 2]);
//--------------------------------------------------------------------------------------
// 6. Local functions
//--------------------------------------------------------------------------------------
public Task<string> PerformLongRunningWork(string address, int index, string name)
{
if (string.IsNullOrWhiteSpace(address))
throw new ArgumentException(message: "An address is required", paramName: nameof(address));
if (index < 0)
throw new ArgumentOutOfRangeException(paramName: nameof(index), message: "The index must be non-negative");
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException(message: "You must supply a name", paramName: nameof(name));
return longRunningWorkImplementation();
async Task<string> longRunningWorkImplementation()
{
var interimResult = await FirstWork(address);
var secondResult = await SecondStep(index, name);
return $"The results are {interimResult} and {secondResult}. Enjoy.";
}
}
//--------------------------------------------------------------------------------------
// 7. More expression-bodied members
//--------------------------------------------------------------------------------------
// Expression-bodied constructor
public ExpressionMembersExample(string label) => this.Label = label;
// Expression-bodied finalizer
~ExpressionMembersExample() => Console.Error.WriteLine("Finalized!");
private string label;
// Expression-bodied get / set accessors.
public string Label
{
get => label;
set => this.label = value ?? "Default label";
}
//--------------------------------------------------------------------------------------
// 8. Throw expressions
//--------------------------------------------------------------------------------------
public string Name
{
get => name;
set => name = value ??
throw new ArgumentNullException(paramName: nameof(value), message: "Name cannot be null");
}
DateTime ToDateTime(IFormatProvider provider) =>
throw new InvalidCastException("Conversion to a DateTime is not supported.");
//--------------------------------------------------------------------------------------
// 9. Generalized async return types
//--------------------------------------------------------------------------------------
public async ValueTask<int> Func()
{
await Task.Delay(100);
return 5;
}
//--------------------------------------------------------------------------------------
// 10. Numeric literal syntax improvements
//--------------------------------------------------------------------------------------
public const int Sixteen = 0b0001_0000;
public const int ThirtyTwo = 0b0010_0000;
public const int SixtyFour = 0b0100_0000;
public const int OneHundredTwentyEight = 0b1000_0000;
public const long BillionsAndBillions = 100_000_000_000;
public const double AvogadroConstant = 6.022_140_857_747_474e23;
public const decimal GoldenRatio = 1.618_033_988_749_894_848_204_586_834_365_638_117_720_309_179M;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment