- Beginning C# 7 Hands-On:Advanced Language Features
- Tom Owsiak
- 393字
- 2021-07-02 15:29:16
Writing a swap function
A swap function is a common thing to write: a function that swaps two values. To do this, go to Solution Explorer, right-click on the name of the website, select Add, and then click on Class. Name the class GenMethods to keep it simple, and then click on OK. When the Visual Studio message comes up, click on Yes.
When the GenMethods file comes up, the only thing that you should leave there is using System. We don't need the constructor for this class, so get rid of that. Then, within the body of GenMethods, define the following between the set of curly braces below the public class GenMethods line:
public static void Swap<T>(ref T x, ref T y)
This will act at the class level: you don't have to make an object of the GenMethods type. In a sense, the only thing that is new here is the fact that this is a Swap<T> function, which means that it can act on several different data types equally well. Now, also remember that the ref keyword indicates that with the x and y parameters in this line, when you change the values inside the method, those changed values are also accessible inside the calling code. Keep that in mind.
Before going ahead, let's label this by entering the following comment above this line:
//method can operate on multiple data types
This basically means that the method can operate on multiple data types equally.
Now, between the set of curly braces beneath the preceding line, enter the following to swap the values:
T temp = x;
Here, you're taking the value of x and assigning it to a temporary one. Then, in the next stage, you can take x and assign y to it and then you can take y and assign temp to it, as follows:
x = y;
y = temp;
Let's add the following comments before proceeding:
T temp = x;
//save x x = y;
//assign y to x y = temp;
//assign original value of x back to y
Here, the first line means overwrite the value of x with the value of y, and then you assign y to x. In the last stage, you assign temp, which is the original value of x, back to y. This represents the switching of the values.
- 計(jì)算思維與算法入門
- Learning Cython Programming
- Delphi程序設(shè)計(jì)基礎(chǔ):教程、實(shí)驗(yàn)、習(xí)題
- 編程卓越之道(卷3):軟件工程化
- jQuery EasyUI網(wǎng)站開發(fā)實(shí)戰(zhàn)
- Data Analysis with Stata
- Python高效開發(fā)實(shí)戰(zhàn):Django、Tornado、Flask、Twisted(第3版)
- 常用工具軟件立體化教程(微課版)
- 零基礎(chǔ)學(xué)C語言程序設(shè)計(jì)
- Qlik Sense? Cookbook
- 編程改變生活:用Python提升你的能力(進(jìn)階篇·微課視頻版)
- Julia High Performance(Second Edition)
- Puppet Cookbook(Third Edition)
- 軟件測試項(xiàng)目實(shí)戰(zhàn)之功能測試篇
- HTML 5與CSS 3權(quán)威指南(第4版·上冊)