본문 바로가기

C#/공부

4. 클래스와 메소드

1. 여러 메소드 선언과 사용 결과

 

using System;

class Program
{
    public static void Main()
    {
        int a = 100, b = 10;
        Console.WriteLine("add(a,b) = {0}",add(a,b));
        Console.WriteLine("before swap a: {0}, b: {1}", a, b);
        swap(ref a, ref b);
        Console.WriteLine("after swap a: {0}, b: {1}", a, b);
        Console.WriteLine("div(a,b) = {0:N}", div(a, b));
    }
    static int add(int i1, int i2)
    {
        return i1 + i2;
    }
    static void swap(ref int i1,ref int i2)
    {
        int temp = i2;
        i2 = i1;
        i1 = temp;
    }
    static double div(int i1, int i2)
    {
        return (double)i1 / (double)i2;
    }
}

 

 

 

2. 클래스

 

이름 성별 나이가 있는 고양이 클래스를 main에서 두 가지 방식으로 선언하였다.

 

using System;

namespace ConsoleApplication1
{
    class Cat
    {
        public string name;
        public string gender;
        public int age;

        public Cat()
        {
        }

        public Cat(String name, String gender, int age)
        {
            this.name = name;
            this.gender = gender;
            this.age = age;
        }

        public void inform()
        {
            Console.WriteLine("고양이 이름:{0}, 나이:{1}, 성별:{2}", name, age, gender);
        }
    }
    class Program
    {
        public static void Main()
        {
            Cat cat1 = new Cat();
            cat1.name = "white";
            cat1.age = 5;
            cat1.gender = "male";

            Cat cat2 = new Cat("Black", "female", 8);

            cat1.inform();
            cat2.inform();
        }
    }
}

 

'C# > 공부' 카테고리의 다른 글

C# 실력 늘리기 1일차  (0) 2022.07.19
시리얼 통신  (0) 2022.07.11
3. 조건문 / 반복문 / 제어문  (0) 2022.07.06
2. 연산자와 배열  (0) 2022.07.05
1. C# 시작 - Hello, world! 와 변수, 자료형, 서식 지정자  (0) 2022.07.05