- Mastering Visual Studio 2017
- Kunal Chowdhury
- 347字
- 2021-07-15 17:26:38
The Is expression with pattern matching
In this type of pattern matching, it introduces a new pattern variable out of the expression, allowing you to extract the value of the type. It is similar to the out variable, but with a limited scope to the surroundings.
Let's look at an example. In the old method, we need to check for the data type, and then we must convert the variable to the specified data type to get the value out of it. Here, if the person is of type Employee, we can type cast it to Employee to get the values of the employee object:
if (person is Employee) { Employee employee = (Employee)person; Console.WriteLine("Person '{0}' is an Employee", employee.Firstname); } else if (person is Customer) { Customer customer = (Customer)person; Console.WriteLine("Person '{0}' is a Customer", customer.Firstname); }
In C# 7.0, you can do that in the same line while validating the expression. It allows you to extract the is expression by adding a pattern to the right side of the expression and extracting the value from it. The preceding example can be rewritten in C# 7.0 as follows:
if (person is Employee employee) { Console.WriteLine("Person '{0}' is an Employee", employee.Firstname); } else if (person is Customer customer) { Console.WriteLine("Person '{0}' is a Customer", customer.Firstname); }
Here you can see that employee is a value extracted from the same line as the expression, which you can use in subsequent lines of the block.
You can also use the extracted variable just like an out variable with a limited scope to the surrounded blocks. The following code snippet shows you how to do this:
if (!(obj is int i))
{
return;
} Console.WriteLine("Value of i: " + i);
Here you can see that the value i, which is derived after the conversion in the expression, acts like an out parameter and has access to it within the next code lines outside the expression block. If you run the preceding example, it will print the value of i (where obj is 50, in our case) in the console window:

- HTML5移動(dòng)Web開(kāi)發(fā)技術(shù)
- ASP.NET MVC4框架揭秘
- 劍指Offer(專(zhuān)項(xiàng)突破版):數(shù)據(jù)結(jié)構(gòu)與算法名企面試題精講
- INSTANT Sencha Touch
- Unity Game Development Scripting
- Visual Basic程序設(shè)計(jì)上機(jī)實(shí)驗(yàn)教程
- Java語(yǔ)言程序設(shè)計(jì)教程
- Python 3 數(shù)據(jù)分析與機(jī)器學(xué)習(xí)實(shí)戰(zhàn)
- Hack與HHVM權(quán)威指南
- 實(shí)驗(yàn)編程:PsychoPy從入門(mén)到精通
- 輕松學(xué)Scratch 3.0 少兒編程(全彩)
- 程序員面試金典(第6版)
- 跟小樓老師學(xué)用Axure RP 9:玩轉(zhuǎn)產(chǎn)品原型設(shè)計(jì)
- Lync Server Cookbook
- Natural Language Processing with Python Cookbook