
// Tab 키를 누르면 자동으로 코드가 완성된다.
Console.WriteLine("C#");
// Ctrl + Space를 눌러 IntelliSense를 호출하면 해당 메서드나 변수에 대한 정보와 예제를 볼 수 있다.
Console.WriteLine("Study");
// 코드 템플릿을 이용해 코드를 더 빠르게 작성한다.
// e.g. for문을 작성할 때, for 키워드를 입력하고, 두 번 Tab키를 누르면 for문의 기본적인 코드 탬플릿이 자동 생성된다.
for (int i = 0; i < UPPER; i++){}
// Hello World.cs
using System;
namespace HelloWorld
{
class program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
namespace ConsoleApp2;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
Console.WriteLine("Hello World!");
Console.WriteLine("My Name is Kero");
Console.WriteLine(10);
Console.WriteLine(3.141592);
Console.WriteLine(3 + 3);
Console.Write("Hello! ");
Console.Write("We are Learning ");
Console.WriteLine("at TeamSparta");
문자열 내 특수한 문자를 포함시키기 위해 사용되는 특별한 문자 조합
| 이스케이프 시퀀스 | 설명 |
|---|---|
\' | 작은따옴표(') 삽입 |
\" | 큰따옴표(") 삽입 |
\\ | 역슬래시() 삽입 |
\n | 새 줄(줄바꿈) 삽입 |
\r | 현재 줄 맨 앞으로 이동 |
\t | 탭 삽입 |
\b | 백스페이스 삽입 |
Console.WriteLine("Hello\nWorld");
// 출력결과
// Hello
// World
Console.WriteLine("Name\tAge");
Console.WriteLine("Kero\t30");
Console.WriteLine("Young\t25");
// 출력결과
// Name Age
// Kero 30
// Young 25
Console.WriteLine("We learn \"C# Programming\"");
// 출력결과
// The book is called "C# Programming"
Console.WriteLine("He said, \'Hello\' to me.");
// 출력결과
// He said, 'Hello' to me.
Console.WriteLine("C:\\MyDocuments\\Project\\");
// 출력결과
// C:\MyDocuments\Project\
| 자료형 | .NET 데이타 타입 | 크기 (바이트) | 범위 |
|---|---|---|---|
| sbyte | System.SByte | 1 | -128 ~ 127 |
| byte | System.Byte | 1 | 0 ~ 255 |
| short | System.Int16 | 2 | -32,768 ~ 32,767 |
| ushort | System.UInt16 | 2 | 0 ~ 65,535 |
| int | System.Int32 | 4 | -2,147,483,648 ~ 2,147,483,647 |
| uint | System.UInt32 | 4 | 0 ~ 4,294,967,295 |
| long | System.Int64 | 8 | -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 |
| ulong | System.UInt64 | 8 | 0 ~ 18,446,744,073,709,551,615 |
| float | System.Single | 4 | ±1.5 × 10^-45 ~ ±3.4 × 10^38 |
| double | System.Double | 8 | ±5.0 × 10^-324 ~ ±1.7 × 10^308 |
| decimal | System.Decimal | 16 | ±1.0 × 10^-28 ~ ±7.9 × 10^28 |
| char | System.Char | 2 | 유니코드 문자 |
| string | System.String | 유니코드 문자열 | |
| bool | System.Boolean | 1 | true 또는 false |
int num = 10;
float f = 3.14f;
char c = 'A';
string str = "Hello, World!";
int num1 = 0x10;
int num2 = 0b1010;
long num3 = 100000000000000L;
int num;
int num1, num2, num3;
int num; // 변수 선언
num = 10; // 변수 초기화
int num = 10; // 변수 선언과 초기화를 한 번에 수행
int num1, num2, num3 = 10; (X, 이럼 num3만 10으로 초기화 됨)
num1 = num2 = num3 = 10; (O)
키워드
abstract as base bool break byte case catch char checked class const
continue decimal default delegate do double else enum event explicit
extern false finally fixed float for foreach goto if implicit in int
interface internal is lock long namespace new null object operator out
override params private protected public readonly ref return sbyte sealed
short sizeof stackalloc static string struct switch this throw true try
typeof uint ulong unchecked unsafe ushort using virtual void volatile while식별자(Identifiers)
식별자: 변수, 메서드, 클래스, 인터페이스 등에 사용되는 이름을 말함. 키워드와 동일하게 사용할 수 없다.
식별자를 사용할 때에는 다음과 같은 규칙을 따라야 한다.
// 좋은 예시
int playerScore;
string playerName;
float itemPrice;
// 나쁜 예시 (중요 의미 있는 변수명 짓기)
int x1; // 변수명이 의미를 알기 어려움
string a; // 변수명이 명확하지 않음
// 오류 예시
int 1stNumber; // 변수명은 숫자로 시작할 수 없음
string my-name; // 변수명에 하이픈(-)을 사용할 수 없음
float total$; // 변수명에 특수문자($)를 사용할 수 없음
코드 컨벤션(Code convention)
개발자들 사이에서 약속된 코드 작성 규칙으로, 코드의 가독성을 높이고 유지 보수를 쉽게 하기 위해 사용됨. 코드 컨벤션은 프로그래밍 언어마다 다를 수 있으며, 다음 규칙을 따라야 함
식별자 표기법
들여쓰기
중괄호 위치
빈 줄 사용
주석
일반적인 코드 컨벤션
class MyClass
{
// 필드는 camelCase 표기법을 사용합니다.
private int myField;
// 프로퍼티는 PascalCase 표기법을 사용합니다.
public int MyProperty { get; set; }
// 메서드는 PascalCase 표기법을 사용합니다.
public void MyMethod()
{
if (true)
{
// 중괄호는 새로운 줄에서 시작합니다.
}
// 코드 블록은 탭(tab) 또는 스페이스(space) 4칸으로 들여씁니다.
// 관련 없는 코드 사이에는 빈 줄을 사용하여 구분합니다.
// 블록 사이에는 두 줄을 띄어씁니다.
/*
여러 줄 주석을 사용할 때는
/ * 를 새로운 줄에서 시작하고,
* / 를 새로운 줄에서 끝내도록 합니다.
*/
// 한 줄 주석은 이렇게 사용합니다.
int a = 10; // 코드 끝에도 한 줄 주석을 사용할 수 있습니다.
}
}
int num1 = 10;
long num2 = (long)num1; // int를 long으로 명시적 형변환
byte num1 = 10;
int num2 = num1; // byte형에서 int형으로 암시적 형변환
1) 작은 데이터 타입에서 더 큰 데이터 타입으로 대입하는 경우
byte, short, char 등 작은 데이터 타입에서 int, long, float 등 더 큰 데이터 타입으로 대입할 때 암시적 형변환이 발생
float result = 1; // 1은 int형 리터럴 값이지만 float형으로 암시적 형변환
2) 리터럴 값이 대입되는 경우
C# 컴파일러는 리터럴 값의 데이터 타입을 판별하여 변수에 암시적으로 형변환 함
int num1 = 10;
float num2 = 3.14f;
float result = num1 + num2; // int형과 float형의 덧셈에서 float형으로 암시적 형변환
3) 정수형과 부동소수점형 간의 연산을 수행하는 경우
정수형과 부동소수점형의 연산 결과는 부동소수점형으로 변환됨
더 큰 형태를 따라간다고 생각하면 된다.
암시적 형변환은 프로그래머가 직접 형변환 코드를 작성하지 않아도 돼서 코드를 간결하게 작성할 수 있다. 하지만 암시적 형변환이 발생하는 경우 데이터 타입을 신중하게 고려해서 코드를 작성해야 한다.
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello, {0}!", name);
사용자로부터 여러 개의 값을 한 줄에 입력받고 싶을 때에는 Console.ReadLine 메서드를 사용해 입력받은 값을 문자열로 받은 후, string.Split 메서드를 사용하여 문자열을 나누어서 처리할 수 있다.
사용자로부터 공백으로 구분된 두 개의 정수를 입력받아 더하는 코드를 작성해 보자. (다중 입력 기초)
Console.Write("Enter two numbers: ");
string input = Console.ReadLine(); // "10 20"과 같은 문자열을 입력받음
string[] numbers = input.Split(' '); // 문자열을 공백으로 구분하여 배열로 만듦
int num1 = int.Parse(numbers[0]); // 첫 번째 값을 정수로 변환하여 저장
int num2 = int.Parse(numbers[1]); // 두 번째 값을 정수로 변환하여 저장
int sum = num1 + num2; // 두 수를 더하여 결과를 계산
Console.WriteLine("The sum of {0} and {1} is {2}.", num1, num2, sum);
string[] numbers = input.Split(' '); // 문자열을 공백으로 구분하여 배열로 만듦
// { "10", "20" }
int num1 = int.Parse(numbers[0]); // 첫 번째 값을 정수로 변환하여 저장
int num2 = int.Parse(numbers[1]); // 두 번째 값을 정수로 변환하여 저장
int sum = num1 + num2; // 두 수를 더하여 결과를 계산
Console.WriteLine("The sum of {0} and {1} is {2}.", num1, num2, sum);
var num = 10; // int 자료형으로 결정됨
var name = "kero"; // string 자료형으로 결정됨
var pi = 3.141592; // double 자료형으로 결정됨
산술 연산자
숫자를 대상으로 사용됨
| 연산자 | 설명 |
|---|---|
| + | 덧셈 |
| - | 뺄셈 |
| * | 곱셈 |
| / | 나눗셈 |
| % | 나머지 |
관계 연산자
두 값을 비교하여 참(true) 또는 거짓(flase) 값을 반환함
| 연산자 | 설명 |
|---|---|
| == | 같음 |
| != | 다름 |
| > | 큼 |
| < | 작음 |
| >= | 크거나 같음 |
| <= | 작거나 같음 |
논리 연산자
참(true) 또는 거짓(flase) 값을 대상으로 사용됨
| 연산자 | 설명 |
|---|---|
| && | 논리곱(AND) |
| II | 논리합(OR) |
| ! | 논리부정(NOT) |
산술 연산자부터 실습해 보자. 연산을 위해 피연산자 두 개를 만들어 주자.
class Program
{
static void Main(string[] args)
{
int num1 = 20, num2 = 10;
}
}
static void Main(string[] args)
{
Console.WriteLine("산술연산자");
int num1 = 20, num2 = 10;
Console.WriteLine(num1 + num2);
Console.WriteLine(num1 - num2);
Console.WriteLine(num1 / num2);
Console.WriteLine(num1 * num2);
Console.WriteLine(num1 % num2);
}
Console.WriteLine("관계연산자");
Console.WriteLine(num1 == num2);
Console.WriteLine(num1 != num2);
Console.WriteLine(num1 > num2);
Console.WriteLine(num1 < num2);
Console.WriteLine(num1 >= num2);
Console.WriteLine(num1 <= num2);
Console.WriteLine("논리연산자");
int num3 = 15;
Console.WriteLine("논리연산자");
int num3 = 15;
// 0 <= num3 <= 20
Console.WriteLine("논리연산자");
int num3 = 15;
// 0 <= num3 <= 20
Console.WriteLine(0 <= num3 && num3 <= 20);
Console.WriteLine("논리연산자");
int num3 = 15;
// 0 <= num3 <= 20
Console.WriteLine(0 > num3 || num3 > 20);
Console.WriteLine("논리연산자");
int num3 = 15;
// 0 <= num3 <= 20
Console.WriteLine(0 <= num3 && num3 <= 20); // 0 과 20 사이에 포함되면
Console.WriteLine(0 > num3 || num3 > 20); // 0 ~ 20 사이에 포함되지 않으면
Console.WriteLine("논리연산자");
int num3 = 15;
// 0 <= num3 <= 20
Console.WriteLine(0 <= num3 && num3 <= 20); // 0 과 20 사이에 포함되면
Console.WriteLine(0 > num3 || num3 > 20); // 0 ~ 20 사이에 포함되지 않으면
Console.WriteLine( !(0 <= num3 && num3 <= 20) ); // 0 ~ 20 사이에 포함되지 않으면
| 연산자 | 설명 |
|---|---|
| & (AND) | 두 비트 값이 모두 1일 때 1을 반환 |
| I (OR) | 두 비트 값 중 하나라도 1일 때 1을 반환 |
| ^ (XOR) | 두 비트 값이 서로 다를 때 1을 반환 |
| ~ (NOT) | 비트 값의 보수(complement)를 반환 |
| << (왼쪽 시프트) | 비트를 왼쪽으로 이동 |
| >> (오른쪽 시프트) | 비트를 오른쪽으로 이동 |
int a = 0b1100; // 12 (2진수)
int b = 0b1010; // 10 (2진수)
int and = a & b; // 0b1000 (8)
int or = a | b; // 0b1110 (14)
int xor = a ^ b; // 0b0110 (6)
int c = 0b1011; // 11 (2진수)
int leftShift = c << 2; // 0b101100 (44)
int rightShift = c >> 1; // 0b0101 (5)
int d = 0b1100; // 12 (2진수)
int bit3 = (d >> 2) & 0b1; // 1 (3번째 비트)
d |= 0b1000; // 0b1100 | 0b1000 = 0b1100 (12)
변수를 더 편리하게 조작하고 값을 증감시킬 수 있다.
(코드를 빨리, 간결하게 사용 가능)
복합 대입 연산자
C#에서는 변수에 값을 할당하는 대입 연산자(=) 외에도 다양한 복합 대입 연산자를 제공
변수에 연산을 수행한 결과를 저장하는 연산자
| 연산자 | 예시 | 설명 |
|---|---|---|
| += | x += y; | x = x + y; x에 y를 더해 넣는다 |
| -= | x -= y; | x = x - y; |
| *= | x *= y; | x = x * y; |
| /= | x /= y; | x = x / y; |
| %= | x %= y; | x = x % y; |
증감 연산자
변수의 값을 1 증가시키거나 감소시키는 연산자
피연산자의 앞에 붙냐 뒤에 붙냐의 차이로 전위형과 후위형이 나뉨.
++x; -> x를 더하고 사용함. x++; -> 세미콜론 끝난 다음에 ++ 진행함
| 연산자 | 설명 |
|---|---|
| ++ | 1 증가 |
| -- | 1 감소 |
연산자 우선순위는 수식 내에서 연산자가 수행되는 순서를 결정함
연산자 우선순위에 따라 연산의 결과가 달라질 수 있기 때문에 중요
C#의 주요 연산자 우선순위
높은 우선순위의 연산자가 먼저 수행됨
아래는 C#에서 주로 사용되는 연산자들의 우선순위를 나열한 것.
string str1 = "Hello, World!"; // 리터럴 문자열 사용
string str2 = new string('H', 5); // 문자 'H'를 5개로 구성된 문자열 생성
string str1 = "Hello";
string str2 = "World";
string str3 = str1 + " " + str2;
string str = "Hello, World!";
string[] words = str.Split(',');
string str = "Hello, World!";
int index = str.IndexOf("World");
string str = "Hello, World!";
string newStr = str.Replace("World", "Universe");
string str = "123";
int num = int.Parse(str);
int num = 123;
string str = num.ToString();
string str1 = "Hello";
string str2 = "World";
bool isEqual = str1 == str2;
string str1 = "Apple";
string str2 = "Banana";
int compare = string.Compare(str1, str2);
string name = "John";
int age = 30;
string message = string.Format("My name is {0} and I'm {1} years old.", name, age);
string name = "John";
int age = 30;
string message = $"My name is {name} and I'm {age} years old.";
string str1 = "Hello, World!";
string str2 = new string('h', 5);
string str3 = str1 + " " + str2;
Console.WriteLine(str3);
// 출력: Hello, World! hhhhh
string[] str4 = str1.Split(',');
Console.WriteLine(str4[0]);
Console.WriteLine(str4[1]);
int index = str1.IndexOf("World");
Console.WriteLine(index);
string newstr = str1.Replace("World", "Universe");
Console.WriteLine(newstr);
Console.WriteLine(str1);
string str5 = "123";
int num = int.Parse(str5);
Console.WriteLine(num);
// 출력: 123
string str5 = "123";
int num = int.Parse(str5);
Console.WriteLine(num);
num += 10;
Console.WriteLine(num.ToString());
// 출력: 123
// 출력: 133
Console.WriteLine(str1 == str2);
Console.WriteLine(string.Compare(str1, str2));
string name = "John";
int age = 30;
string message = string.Format("My name is {0} and i'm {1} years old.", name, age);
Console.WriteLine(message);
string name = "John";
int age = 30;
message = $"My name is {name} and I'm {age} years old.";
Console.WriteLine(message);