คำสั่ง return ใช้สำหรับส่งคืนค่า เมื่อโปรแกรมเรียกฟังก์ชัน การควบคุมโปรแกรมจะถูกโอนไปยังฟังก์ชันที่ถูกเรียก ฟังก์ชันที่ถูกเรียกทำงานที่กำหนด และเมื่อคำสั่ง return ทำงาน หรือเมื่อถึงเครื่องหมายปิดบล็อกของฟังก์ชัน จะส่งควบคุมกลับไปยังโปรแกรมหลัก
ตัวอย่างการใช้ return ใน C# ที่นี่เราหาแฟกทอเรียลของตัวเลขและส่งคืนผลลัพธ์ด้วย return
while (n != 1) {
res = res * n;
n = n - 1;
}
return res;ตัวอย่างเต็ม
ตัวอย่าง
using System;
namespace Demo {
class Factorial {
public int display(int n) {
int res = 1;
while (n != 1) {
res = res * n;
n = n - 1;
}
return res;
}
static void Main(string[] args) {
int value = 5;
int ret;
Factorial fact = new Factorial();
ret = fact.display(value);
Console.WriteLine("Value is : {0}", ret);
Console.ReadLine();
}
}
}ผลลัพธ์
Value is : 120