본문 바로가기

CSharp/CSharp 문법66

string.Format()으로 문자열 포맷 지정하기 string.Format()으로 문자열 포맷 지정하기 string.Format()은 텍스트 내에 변수 값을 삽입할 수 있는 다양한 서식 지정 기능을 제공합니다. 숫자, 날짜, 통화 등 포맷이 필요한 문자열 출력에서 매우 유용하게 사용됩니다. using System; class Program { static void Main() { string name = "델파이사이트"; int visitors = 1234; DateTime today = DateTime.Today; string message = string.Format("📅 {0:yyyy-MM-dd} 기준, {1} 방문자 수: {2:N0}명", .. 2025. 5. 13.
string.Contains()로 문자열 포함 여부 간단히 확인하기 string.Contains()로 문자열 포함 여부 간단히 확인하기 C#의 string.Contains() 메서드를 사용하면 텍스트 내에 특정 문자열이 포함되어 있는지를 간단하고 직관적으로 검사할 수 있습니다. 검색, 필터링, 조건 분기 등에 유용하게 사용됩니다. using System; class Program { static void Main() { string message = "안녕하세요, 모노솔루션입니다."; if (message.Contains("모노")) { Console.WriteLine("✅ 회사명이 포함되어 있습니다."); } else { .. 2025. 5. 5.
Array.Exists()로 배열 조건 빠르게 검사하기 Array.Exists()로 배열 조건 빠르게 검사하기 C#의 Array.Exists() 메서드는 배열에 특정 조건을 만족하는 요소가 하나라도 존재하는지 간단하게 검사할 수 있는 방법입니다. 불필요한 반복문 없이 조건 검사를 간결하게 표현할 수 있어 유용합니다. using System; class Program { static void Main() { int[] numbers = { 3, 7, 9, 12, 15 }; bool hasEven = Array.Exists(numbers, n => n % 2 == 0); Console.WriteLine(hasEven ? "✅ 배열에 짝수가 있습니다." : ".. 2025. 4. 30.
string.IsNullOrWhiteSpace()로 문자열 안전하게 검사하기 string.IsNullOrWhiteSpace()로 문자열 안전하게 검사하기 C#에서는 string.IsNullOrWhiteSpace() 메서드를 사용하면 문자열이 null, 빈 문자열("") 또는 공백만 있는 경우를 한 번에 검사할 수 있습니다. 조건문을 깔끔하게 만들고, 널 포인터 예외도 예방할 수 있어 매우 유용합니다 using System; class Program { static void Main() { string input = " "; if (string.IsNullOrWhiteSpace(input)) { Console.WriteLine("⚠️ 입력값이 비어있거나 공백입니다."); } .. 2025. 4. 29.
switch 표현식으로 깔끔한 조건 분기 구현하기 switch 표현식으로 깔끔한 조건 분기 구현하기 C# 8.0부터 지원되는 switch 표현식은 기존의 switch문보다 더 간결하고 가독성 좋은 조건 분기 방식입니다. 조건마다 값을 반환해야 할 때 매우 유용하며, 함수형 스타일 코딩에 적합합니다. using System; class Program { static void Main() { string role = "admin"; string permission = role switch { "admin" => "모든 권한", "user" => "일반 권한", "guest" => "읽기 전용", _ => "알 수.. 2025. 4. 22.
List<T>와 AddRange()로 다중 요소 추가하기 List와 AddRange()로 다중 요소 추가하기\ C#의 List는 유연하고 자주 쓰이는 컬렉션 타입 중 하나입니다. 여러 개의 데이터를 한 번에 추가할 때는 Add() 대신 AddRange()를 사용하여 효율적으로 처리할 수 있습니다. using System; using System.Collections.Generic; class Program { static void Main() { List fruits = new List { "사과", "바나나" }; List moreFruits = new List { "포도", "복숭아", "수박" }; fruits.AddRange(moreFruits); Console.WriteLine.. 2025. 4. 18.
enum을 활용한 의미 있는 상수 집합 정의 enum을 활용한 의미 있는 상수 집합 정의 enum(열거형)은 관련된 상수 값을 이름으로 표현할 수 있게 해주는 C#의 기능입니다. 의미 있는 이름으로 코드를 작성하면 가독성, 유지보수성이 모두 좋아집니다. using System; enum OrderStatus { Pending, Processing, Shipped, Delivered, Cancelled } class Program { static void Main() { OrderStatus status = OrderStatus.Shipped; Console.WriteLine($"주문 상태: {status}"); if (status == OrderSta.. 2025. 4. 16.
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.