본문 바로가기
c# 입문

[c#] c# ref, out , 메서드 오버로딩(overloading)

by javaman 2022. 7. 8.

삼항 연산자

 

bool isPair = ((num%2 == 0)? true :false )
//num 이 짝수이면 isPair = true
//num 이 홀수이면 isPair = false

 

 

상수

 

//상수 선언
const int ROCK =1 ;
const int PAPER=2 ;
const int SCISSORS = 0 ;

//열거형 상수
enum Choice { SCISSORS, ROCK , PAPER }

 

 

do while 문

 

 do{
    Console.WriteLine("일단 한번은 실행");
    pa--;
    } while (pa > 0);
         //일단 한번은 실행

 

break && continue 문

 

break : for 문 ,while문  빠져나가기 ( ※ if 문 아님)

 

continue : continue 이하 코드를 실행하지 않고, for문의 다음 회전으로 이동하기

 

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Boolean isPrime = true;
            short num = 1002;
            for(int i = 2; i < num; i++)
            {
                if ((num % i) != 0) continue; 
                isPrime = false;
            }
            if (isPrime)
                Console.WriteLine($"{num} 은/는 소수 입니다");
            else Console.WriteLine($"{num}은/는 소수가 아닙니다");

            
        }
    }
}

 

ref && out

 

ref : 실제 매개 변수에 저장된 값 변경, 

 

out : 함수 (메서드) 를 호출한 클래스 블럭 안에서 선언된 실제 매개 변수의 값을 변경함

        여러개의 값을 반환(return)하고 싶을 때 사용 !

 

 

using System;

namespace ConsoleApp1
{
    class Program
    {   static int AddOne(ref int a)
        {
            return ++a;
        }
        static void Main(string[] args)
        {
            int a = 3;
            AddOne( ref a);//변수 a의 값을 직접 변경함 call by reference


            
        }
    }
}
using System;

namespace ConsoleApp1
{
    class Program
    {   
        static void Add(ref int a, ref int b,  out int r1, out int r2)
        {
            r1 = a + b;
            r2 = a * b;
        }
        static void Main(string[] args)
        {
            int a = 3;
            int b = 4;
            int result1 = 0  ;
            int result2 = 0;
            Add( ref a, ref b, out result1, out result2);//변수 a의 값을 직접 변경함 call by reference

            Console.WriteLine($"a+b = {result1} and a*b = {result2}");
            
        }
    }
}

 

(메서드) 오버로딩

 

: 함수 이름의 재사용

 

 ☞ 매개변수의 타입 또는 개수를 다르게 정의해야 함

    반환 데이터 형은 고려하지 않음

 

 

static void Add(int a,int b){

	Console.WriteLine("첫번째 함수");
}

static void Add(float a, int b ){

	Console.WriteLine("두번째 함수");
}

 

선택적 매개변수

 

static int Add( int a, int b, int c = 0 ){

	return a+b+c;//여기서 c 는 선택적인 변수임
}