C# 기본문법 정리
data type (String, StringBuilder, int, double, bool)
조건문(if, switch)
반복문(for, foreach)
예외처리(try, catch, finally)
Class
Immutable Type -> 값이 설정되면 다시 변경할 수 없는 타입
public static void StringExample1()
{
string name = "seongguk";
string ment = $"my name is {name}";//문자열 보간
Console.WriteLine(ment);
}
Mutable Type -> 값을 계속 변경할 수 있는 타입
public static void StringExample2()
{
StringBuilder sb = new StringBuilder();
sb.Append("A");
sb.Append("B");
sb.Append("C");
sb.Append("D");
sb.Append("E");
sb.Append("F");
sb.Append("G");
Console.WriteLine($"{sb}");
}
public static void IntExample1()
{
string strNum = "123";
//정규식 사용하여 숫자인지 판단 후 int형으로 변경
if(Regex.IsMatch(strNum, @"^[0-9]+$"))
{
int num = int.Parse(strNum);
Console.WriteLine($"숫자변환 완료 : {num}");
}
else
{
Console.WriteLine("숫자가 아닙니다.");
}
}
- decimal 단점은 완전 느리다.
- float, double은 데이터 크기 및 사용법 그리고 소수점 최대 자리가 다르다.
public static void IntExample2()
{
Double[] values = { 10.0, 2.88, 2.88, 2.88, 9.0 };
Double result = 27.64;
Double total = 0;
foreach (var value in values)
total += value;
if (total.Equals(result))
Console.WriteLine("같음");
else
Console.WriteLine($"더한 값 : ({total}) 결과 : ({result}).");
decimal deResult = (decimal)result;
decimal detotal = (decimal)total;
if (deResult.Equals(detotal))
Console.WriteLine("같음");
else
Console.WriteLine($"더한 값 : ({deResult}) 결과 : ({detotal}).");
}
private static void BoolExample1()
{
bool isRed = true;
if (isRed)
{
Console.WriteLine($"빨간색입니다.");
}
else
{
Console.WriteLine($"빨간색이 아닙니다.");
}
}
If : 조건이 5개 미만일 경우 사용하자.
switch : 조건이 5개 이상일 경우 사용하자.
public static void ifExample()
{
string result;
int score = 90;
if(score >= 90)
{
result = "A";
}
else if(score >= 80)
{
result = "B";
}
else
{
result = "F";
}
Console.WriteLine($"{score}점은 {result}등급 입니다.");
}
public static void switchExample()
{
int day = 3;
// 관계 패턴
string week = day switch
{
1 => "월",
2 => "화",
3 => "수",
4 => "목",
5 => "금",
6 => "토",
7 => "일",
_ => "X"//default
};
Console.WriteLine($"오늘은 {week}요일 입니다.");
}
for : 일정한 개수 만큼 반복하고 싶으면 사용.
foreach : 자료구조를 이용한 반복문일 경우 사용.
/// <summary>
/// for
/// </summary
public static void forExample()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"num : {i}");
}
}
/// <summary>
/// foreach
/// </summary>
public static void foreachExample()
{
List<string> listSeason = new List<string>();
foreach (var item in Enum.GetValues(typeof(eSeason)))
{
listSeason.Add(item.ToString().Trim());
}
foreach (string item in listSeason)
{
Console.WriteLine($"계절 = {item}");
}
}
enum eSeason
{
Spring,
Summer,
Autumn,
Winter
}
try : 메인 동작 구문 넣는 부분.
catch : 메인 동작에 오류가 발생시 동작.
finally : 정상동작, 오류동작 무조건 동작.
/// <summary>
/// 예외처리 example
/// </summary
public static void ExceptionExample()
{
try
{
string strNum = "아아";
int num = Convert.ToInt32(strNum);
}
catch(Exception ex)
{
Console.WriteLine($"{ex.Message}");
}
finally
{
Console.WriteLine("무조건 실행");
}
}
객체는 붕어빵, 클래스는 붕어빵 틀
/// <summary>
/// class 예제
/// </summary>
public static void classExample()
{
Person person1 = new Person("A", "23");
Person person2 = new Person("A", "30");
person1.InfoPerson();
person2.InfoPerson();
}
class Person
{
private string name;
private string age;
public Person(string name, string age)
{
this.name = name;
this.age = age;
}
public void InfoPerson()
{
Console.WriteLine($"{name}의 나이는 {age}입니다.");
}
}