CSharp/CSharp 문법19 try-catch-finally 구문으로 예외 처리 완전 정복! try-catch-finally 구문으로 예외 처리 완전 정복! C#에서는 프로그램 실행 중 예외 상황이 발생할 수 있으며, 이를 try-catch-finally 구문으로 안전하게 처리할 수 있습니다. 오류를 잡고, 리소스를 정리하고, 사용자에게 친절한 메시지를 제공하는 것은 프로 개발자의 기본입니다! using System; class Program { static void Main() { try { Console.Write("숫자를 입력하세요: "); int number = int.Parse(Console.ReadLine()); Console.WriteLine($"입력한 숫자: {number}".. 2025. 4. 14. foreach와 yield return을 활용한 커스텀 이터레이터 foreach와 yield return을 활용한 커스텀 이터레이터 C#의 yield return을 사용하면 반복자의 상태를 직접 관리하지 않고도 커스텀 이터레이터를 간결하게 구현할 수 있습니다. 필터링, 지연 실행, 파이프라인 처리 등에 매우 유용합니다. using System; using System.Collections.Generic; class Program { static void Main() { foreach (int prime in GetPrimesBelow(10)) { Console.WriteLine($"소수: {prime}"); } } static IEnumerable GetPrimesBelow(.. 2025. 4. 8. switch 표현식으로 간결하게 조건 분기하기 switch 표현식으로 간결하게 조건 분기하기C# 8.0부터는 기존의 switch 문보다 간단하고 표현력 있는 switch 표현식을 사용할 수 있습니다. 코드를 더 간결하게 만들고 가독성을 높이는 데 효과적 using System; class Program { static void Main() { string role = "admin"; string permission = role switch { "admin" => "모든 권한", "user" => "읽기/쓰기", "guest" => "읽기 전용", _ => "권한 없음" }; Co.. 2025. 4. 1. params 키워드로 가변 인자 받기 params 키워드로 가변 인자 받기 C#의 params 키워드를 사용하면 메서드에 개수 제한 없이 인자를 전달할 수 있습니다. 이 기능은 유연한 API를 만들 때 매우 유용합니다. using System; class Program { static void Main() { PrintNumbers(1, 2, 3); PrintNumbers(10, 20); PrintNumbers(); // 인자 없이도 호출 가능 } static void PrintNumbers(params int[] numbers) { Console.WriteLine("숫자 목록: " + string.Join(", ", numbers)); }.. 2025. 3. 28. try-catch-finally 구문으로 예외 처리 마스터하기 try-catch-finally 구문으로 예외 처리 마스터하기 try-catch-finally 구문으로 예외 처리 마스터하기 C#에서 예외(Exception)는 프로그램 실행 중 발생하는 문제를 처리하기 위한 핵심 메커니즘입니다. try-catch-finally 구문을 사용하면 오류를 우아하게 처리하고 자원 정리를 할 수 있습니다. using System; class Program { static void Main() { try { Console.Write("숫자를 입력하세요: "); int number = int.Parse(Console.ReadLine()); Console.WriteLine.. 2025. 3. 27. readonly struct로 값 타입 최적화하기 readonly struct로 값 타입 최적화하기 C#의 readonly struct는 값 타입(Struct)의 불변성을 보장하고 성능 최적화에 큰 도움이 되는 기능입니다. 값 타입은 주로 작은 데이터 덩어리를 표현할 때 사용되며, readonly를 붙이면 의도치 않은 변경을 방지할 수 있습니다. using System; public readonly struct Point { public int X { get; } public int Y { get; } public Point(int x, int y) { X = x; Y = y; } public double Distance => Math.Sqrt(X * X + Y * Y); } .. 2025. 3. 26. nameof 연산자 사용하기 nameof 연산자 사용하기 nameof는 변수, 속성, 메서드, 클래스 등의 이름을 문자열로 안전하게 가져올 수 있는 기능입니다. 코드 리팩토링 시에도 안전하게 작동하므로 유지보수성과 안정성이 향상됩니다. using System; class Person { public string Name { get; set; } public void PrintPropertyName() { Console.WriteLine(nameof(Name)); // "Name" 출력 } } class Program { static void Main() { var person = new Person(); person.PrintProperty.. 2025. 3. 25. 인터페이스와 추상클래스 namespace Property2{ //.Net 9.0 internal class Program { abstract class Product { private static int serial = 0; public string SerialID { get {return String.Format("{0:d5}", serial++);} } abstract public DateTime ProductDate { get;set; } } class MyProduct : Product { public override DateTime ProductDate { get;set; } } record RTransaction { public string From { get; set; } public string T.. 2025. 2. 14. 프로퍼티 1 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Xml.Linq; namespace Property{ internal class Program { /* class BirthdayInfo { private string name; private DateTime birthday; public string Name { get { return name; } .. 2025. 1. 30. 추상클래스 추상클래스 using @interface;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks; namespace @interface{ interface IRunnable { void Run(); } interface IFlyable { void Fly(); } class FlyingCar : IRunnable, IFlyable { public void Run() { Console.WriteLine("Run! Run!".. 2024. 12. 12. 클래스 c# 클래스using System.Drawing;using System.Net.Http.Headers;using System.Timers;using System.Collections.Generic;using System.Security.Cryptography.X509Certificates;using System.Runtime.CompilerServices; namespace _07_Class{ readonly struct RGBColor { public readonly byte R; public readonly byte G; public readonly byte B; public RGBColor(byte r, byte g, byt.. 2024. 12. 3. 메소드 ( Method) 메소드 ( Method) using System.Net.Http.Headers;using System.Security.Cryptography; namespace _06_Method{ internal class Program { static int Fibonacci(int n) { if (n 0) Console.WriteLine(", "); Console.Write(args[i]); sum += args[i]; } Console.WriteLine(); return sum; } .. 2024. 8. 16. 코드의 흐림제어 using System.Collections.Generic; namespace _05_Code{ //형식패턴 클래스 선언 class Preschooler { } class Underage { } class Adult { } class Senior { } internal class Program { #region 형식 패턴 static int CalculateFee(object visitor) { return visitor switch { Underage => 100, Adult => 500, Senior .. 2024. 8. 1. C# 문법 C# 문법 global using System; using System.Globalization; using static System.Console; namespace Hello { class MainApp { //enum DialogResult { YES, NO, CANCEL, CONFIRM, OK }; enum DialogResult { YES = 10, NO, CANCEL, CONFORM = 50, OK }; static void Main(string[] args) { //1번 테스트 /* if (args.Length == 0) { Console.WriteLine("사용법 : Hello.exe "); return; } WriteLine("Hello, {0}!", args[0]); */ //2번 테.. 2024. 7. 1. C# 강의 메모 C# 강의 메모 ******************** 1강 -구글에 C# 설치 검색 후 설치 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Console.WriteLine("Hello C#"); Console.WriteLine(args.Length); //args 인자 개수 Console.WriteLine("Hello" + args[0]); Console.ReadKey(); } } } - CMD 창에서 실행파일명 띄.. 2022. 9. 28. 기초문법 정리2 기초문법 정리2 소스 그룹화 #region 명칭 #endregion 파일 생성 //파일경로에 없으면 생성 있으면 연다. 두번째 인자를 True면 파일이 있을시 추가로 연다 using (StreamWriter writer = new StreamWriter(_path, true)) { writer.WriteLine(data); } //using은 using 안에서만 사용하고 나가면 자동 클로우즈해준다. (예전 파일 열고 계속 잡고있는 현상때문에 사용한다.) 예외처리 try { } catch(Exception ex) { } 날짜 형식 writer.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss\t") + data); //20151204 18:01:01 processi.. 2022. 9. 27. 두 문자열 경로로 결합 두 문자열 경로로 결합 public static string Combine(string path1, string path2, string path3); System.IO.Path.Combine(Application.Root,"log"); 2022. 9. 26. 파일 체크 후 생성 파일 체크 후 생성 using System.IO; public LogManager() { _path = System.IO.Path.Combine(Application.Root,"log"); } private void _SetLogPath() { if (!Directory.Exists(_path)) Directory.CreateDirectory(_path); } 2022. 9. 20. 기초문법 정리 기초문법 정리 조건문 if (조건식) { // 조건이 참일 경우 실행될 문장 } if (조건식) { // 참일 경우에 실행될 문장 } else { // 위의 조건식에 아무것도 해당하지 않을때 실행될 문장 } if (조건식) { // 참일 경우에 실행될 문장 } else if (조건식) { // 참일 경우에 실행될 문장 } else { // 위의 조건식에 아무것도 해당하지 않을때 실행될 문장 } switch (조건식) { case 상수: // 만약 조건식의 결과가 이 상수와 같다면! // 실행될 코드 break; // 탈출! case 상수: // 실행될 코드 break; } 반복문 while (조건식) { // 반복 실행될 코드 } for(초기식; 조건식; 증감식) { // 반복 실행될 코드 } forea.. 2022. 9. 16. 이전 1 다음