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

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.

主站蜘蛛池模板: 洞口县| 东光县| 大安市| 凌海市| 利津县| 泸州市| 苍南县| 肃宁县| 黄浦区| 都江堰市| 台湾省| 喀喇| 贵定县| 安仁县| 望都县| 治多县| 桓台县| 城市| 呼图壁县| 防城港市| 成安县| 南宫市| 会东县| 营口市| 永济市| 田林县| 沈阳市| 黔江区| 北辰区| 米易县| 七台河市| 凭祥市| 林口县| 千阳县| 扎兰屯市| 黄骅市| 蒙山县| 遵义县| 礼泉县| 柳河县| 原平市|