- C# 7 and .NET Core Cookbook
- Dirk Strauss
- 219字
- 2021-07-03 00:11:52
How to do it...
- The following code example will illustrate how we used to have to use TryParse to check if a string value is a valid integer. You will notice that we had to declare the integer variable intVal, which was used as the out variable. The intVal variable would just sort of hang there in mid air, usually not initialized and waiting to be used in TryParse.
string sValue = "500";
int intVal;
if (int.TryParse(sValue, out intVal))
{
WriteLine($"{intVal} is a valid integer");
// Do something with intVal
}
- In C# 7.0 this has been simplified, as can be seen in the following code example. We can now declare the out variable at the point where it is passed as an out parameter, like so:
if (int.TryParse(sValue, out int intVal))
{
WriteLine($"{intVal} is a valid integer");
// Do something with intVal
}
- This is a small change, but a very nice one. Run the console application and check the output displayed.

- As we are declaring the out variable as an argument to the out parameter, the compiler will be able to infer what the type should be. This means that we can also use the var keyword, like this:
if (int.TryParse(sValue, out var intVal))
{
WriteLine($"{intVal} is a valid integer");
// Do something with intVal
}
推薦閱讀
- Developing Middleware in Java EE 8
- 新編Premiere Pro CC從入門到精通
- HTML5+CSS3網頁設計
- Learning DHTMLX Suite UI
- SQL Server 2016數據庫應用與開發
- R語言:邁向大數據之路(加強版)
- Java并發編程之美
- Vue.js 3應用開發與核心源碼解析
- Java程序設計教程
- 視窗軟件設計和開發自動化:可視化D++語言
- JavaScript前端開發基礎教程
- Developing Java Applications with Spring and Spring Boot
- C/C++代碼調試的藝術
- 城市信息模型平臺頂層設計與實踐
- Leaflet.js Essentials