官术网_书友最值得收藏!

How it works...

The changes that C# 7.0 has made to out variables are not major. They are, however, a major convenience to those developers who use it often. So far in this chapter, we have seen the use of Tuples, pattern matching, and out variables. We can easily combine some of what we have learned to create something truly unique. Consider the use of extension methods, Tuples, and out variables. We can easily create an extension method called ToInt() that has the following implementation:

public static (string originalValue, int integerValue, bool isInteger) ToInt(this string stringValue)
{
var t = (original: stringValue, toIntegerValue: 0, isInt: false);
if (int.TryParse(stringValue, out var iValue))
{
t.toIntegerValue = iValue; t.isInt = true;
}
return t;
}

We create a Tuple literal that will be returned in the event of the TryParse returning false. If the TryParse is true, I set the t.toIntegerValue and t.isInt values. The code that calls the extension method looks as follows:

var (original, intVal, isInteger) = sValue.ToInt();
if (isInteger)
{
WriteLine($"{original} is a valid integer");
// Do something with intVal
}

When you run your console application, you will see that the output is exactly the same as before. This just illustrates the power of the new features in C# 7.0 when combined with each other. Throw some pattern matching into the mix, and we will have a very potent extension method. I'll leave you folks to play around with this some more. There is a lot to discover.

主站蜘蛛池模板: 株洲市| 遂川县| 黄石市| 兴宁市| 昔阳县| 茂名市| 丹凤县| 满城县| 登封市| 聂拉木县| 九台市| 高密市| 陆川县| 抚松县| 家居| 太谷县| 凤冈县| 平江县| 榆中县| 鱼台县| 邻水| 闽侯县| 保德县| 祁门县| 东丽区| 阿克陶县| 天祝| 临沧市| 夏津县| 江口县| 海原县| 金山区| 醴陵市| 平湖市| 公安县| 普陀区| 阳泉市| 勐海县| 虹口区| 牙克石市| 江西省|