์ฐธ์กฐ์ ์ํ ๋งค๊ฐ๋ณ์ ์ ๋ฌ
๋ณดํต ๋ค๋ฅธ ๋ฉ์๋์ ์ธ์๋ฅผ ์ ๋ฌํ ๋, ๋ฐ์ดํฐ๊ฐ ๋ณต์ฌ๋์ด์ ์ ๋ฌ๋๋ค. ๋ง์ฝ ์ฃผ์๊ฐ์ ๋ณด๋ด๊ณ ์ถ๋ค๋ฉด ์์ ref๋ฅผ ๋ถ์ฌ์ฃผ๋ฉด ๋๋ค.
class Program
{
public static void Main(string[] args)
{
int x = 3;
int y = 4;
Console.WriteLine($"x = {x}, y = {y}");
Swap(x, y);
Console.WriteLine($"x = {x}, y = {y}");
SwapRef(ref x, ref y);
Console.WriteLine($"x = {x}, y = {y}");
}
static void Swap(int a, int b)
{
int temp = b;
b = a;
a = temp;
}
static void SwapRef(ref int a, ref int b)
{
int temp = b;
b = a;
a = temp;
}
}
์ ์ฝ๋๋ฅผ ์คํํ๋ฉด Swap์ ์ํ ๊ฐ์ x=3, y=4๊ฐ ๋์ค๊ณ , SwapRef์ ์ํ ๊ฐ์ x=4, y=3์ด ๋์ค๊ฒ ๋๋ค.
์ฌ๋ฌ ๊ฐ์ ๊ฐ์ returnํ๊ธฐ
์ฌ๋ฌ ๊ฐ์ ๊ฐ์ returnํ๊ณ ์ถ๋ค๋ฉด out ํค์๋๋ฅผ ์ฌ์ฉํด์ ์ถ๋ ฅ ์ ์ฉ ๋งค๊ฐ๋ณ์๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋ค. ref์ ๊ฐ์ ์ญํ ์ ํ์ง๋ง ํ ๊ฐ์ง ์ฐจ์ด์ ์ ๋ฐ๋ก ๋ฉ์๋๊ฐ ํด๋น ๋งค๊ฐ๋ณ์์ ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ์ง ์์ผ๋ฉด ์ปดํ์ผ๋ฌ๊ฐ ์๋ฌ ๋ฉ์ธ์ง๋ฅผ ์ถ๋ ฅํ๋ค๋ ์ ์ด๋ค. (ref๋ ์๋ฌด๋ฐ ๊ฒฝ๊ณ ๊ฐ ๋จ์ง ์๋๋ค)
class UsingOut
{
public static void Main(string[] args)
{
int a = 20;
int b = 3;
Divide(a, b, out int c, out int d);
Console.WriteLine($"a:{a}, b:{b}, ๋ชซ:{c}, ๋๋จธ์ง:{d}");
}
static void Divide(int a, int b, out int quotient, out int remainder)
{
quotient = a / b;
remainder = a % b;
}
}
๊ฐ๋ณ ๊ฐ์์ ์ธ์
๋ง์ฝ ๋ค์ด์ค๋ ์ธ์์ ๊ฐ์์ ์๊ด ์์ด ๋ชจ๋ ๊ฐ์ ๋ฉ์๋๋ก ๊ตฌํํ๊ณ ์ถ๋ค๋ฉด, param ํค์๋๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋ค.
class ChangeFactor
{
public static void Main(string[] args)
{
int total = Sum(1,2);
Console.WriteLine(total);
int total1 = Sum(1, 2, 3, 4 ,5);
Console.WriteLine(total1);
int total2 = Sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Console.WriteLine(total2);
}
static int Sum(params int[] nums)
{
int sum = 0;
foreach (int i in nums)
{
sum += i;
}
return sum;
}
}
์ ํ์ ์ธ์
ํน์ ๋งค๊ฐ๋ณ์์ default๊ฐ์ ๋ถ์ฌํ๊ณ , default๊ฐ์ ๊ฐ์ง ๋งค๊ฐ๋ณ์๋ ๋ฉ์๋๋ฅผ ํธ์ถํ ๋ ํด๋น ์ธ์๋ฅผ ์๋ตํ ์ ์๋ค. (์ ํ์ ์ธ์์ ์ค๋ฒ๋ก๋ฉ์ ๊ฐ์ด ์ฌ์ฉํ๋ ๊ฑด 0์ ์ง๋ฆฌ ์ฝ๋์ด๋ค. ๋ ์ค ํ๋๋ฅผ ์ ํํด์ ์ฌ์ฉํ๋๋ก ์ ์ฑ ์ ์ผ๋ก ๋ถ๋ช ํ๊ฒ ์ ํ ํ์๊ฐ ์๋ค.)
class OptionalParameter
{
static void Main(string[] args)
{
PrintProfile("Annie");
PrintProfile("Alice", "010-1234-5678");
}
static void PrintProfile(string name, string phone = "-")
{
Console.WriteLine($"Name: {name}, Phone: {phone}");
}
}
'๐ฅ๏ธ > C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C#] ์์, ๋คํ์ฑ, ์ค๋ฒ๋ผ์ด๋ฉ (0) | 2023.08.17 |
---|---|
[์ด๊ฒ์ด C#์ด๋ค] Chapter06: ์ฐ์ต๋ฌธ์ (0) | 2023.08.16 |
[์ด๊ฒ์ด C#์ด๋ค] Chapter05: ์ฐ์ต๋ฌธ์ (0) | 2023.08.16 |
[C#] switch๋ฌธ๊ณผ switch์ (0) | 2023.08.16 |
[์ด๊ฒ์ด C#์ด๋ค] Chapter4 ์ฐ์ต๋ฌธ์ (0) | 2023.08.16 |