Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?

간혹 유사한 질문을 하는 분들이 있는데,

.NET Framework에서 C# 버전만 올릴 수 있을까요?
; https://forum.dotnetdev.kr/t/net-framework-c/9750

개인적인 답변이라면, 아무 문제 없다고 말씀드리고 싶습니다. 일단 방법은 아래의 문서에도 나오는데요,

C# language versioning
; https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version

단지 csproj 파일에 <LangVersion /> 속성만 추가하면 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
      ...[생략]..
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <Deterministic>true</Deterministic>
    <LangVersion>12</LangVersion>
  </PropertyGroup>

  ...[생략]..

  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

그런데, 문서에 보면 이런 문구가 있습니다. ^^

C# 12 is supported only on .NET 8 and newer versions. 

여기서 "only"는 사실 부분적으로는 맞고 부분적으로는 틀립니다. 이유는...?




C# 컴파일러가 새로운 버전이 나왔을 때, 신규 문법은 크게 다음의 4가지 분류로 나눌 수 있습니다.

  1. Syntactic sugar 문법인 경우
  2. BCL에 추가 타입이 함께 요구되는 경우
  3. 닷넷 런타임의 변경이 함께 요구되는 경우
  4. 하위 버전의 C#과 컴파일 결과가 달라지는 경우

첫 번째 유형의 경우, C# 12에서 예를 들면 "컬렉션 식"이 좋은 예입니다.

C# 12 - 컬렉션 식(Collection Expressions)
; https://www.sysnet.pe.kr/2/0/13415

가령 아래의 코드는,

List<int> list = [1, 2, 3, 4, 5];

C# 컴파일러가 단순히 기존 문법으로 변환해,

List<int> list = new List<int>(5) { 1, 2, 3, 4, 5 };

컴파일시키기 때문에 아무런 문제 없이 .NET Framework에 적용이 가능합니다.




그다음, 두 번째 유형은 신규 문법을 위해 BCL에 새로운 타입이 추가된 경우입니다. C# 12 문법에서는 Experimental 지원이 그 사례입니다.

C# 12 - Experimental 특성 지원
; https://www.sysnet.pe.kr/2/0/13444

문법 자체는 C#의 기본 문법을 벗어나진 않지만, 그것을 사용할 때 ".NET 8" BCL에 포함된 타입을 사용하는 유형인데요,

using System.Diagnostics.CodeAnalysis;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
#pragma warning disable MYID01
            MyType myType = new MyType();
#pragma warning restore MYID01
        }
    }
}

[Experimental("MYID01")]
public class MyType
{
}

당연히, .NET Framework 프로젝트에서 저대로 컴파일하면 ExperimentalAttribute가 없다는 오류가 발생합니다.

error CS0246: The type or namespace name 'ExperimentalAttribute' could not be found (are you missing a using directive or an assembly reference?)

하지만, 그냥 맞춰주면 될 일이기 때문에 다음과 같이 .NET 8의 ExperimentalAttribute 정의를 그대로 가져와 .NET Framework 프로젝트에 포함만 시켜 처리할 수 있습니다.

[Experimental("MYID01")]
public class MyType
{
}

#if !NET8_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
    public sealed class ExperimentalAttribute(string diagnosticId) : Attribute
    {
        public string DiagnosticId { get; } = diagnosticId;

        public string UrlFormat { get; set; }
    }
}
#endif




세 번째 유형은, "닷넷 런타임" 자체가 바뀐 경우로 이건 방법이 없습니다. 바로 이런 유형이 있기 때문에 문서에서 "C# 12 is supported only on .NET 8 and newer versions."라는 문구가 있는 것입니다.

이에 대한 좋은 사례가 인라인 배열입니다.

C# 12 - 인라인 배열(Inline Arrays)
; https://www.sysnet.pe.kr/2/0/13412

인라인 배열의 경우 Experimental처럼 InlineArray 특성을 필요로 하는데요,

[System.Runtime.CompilerServices.InlineArray(5)]
public struct Buffer
{
    private int _element0;
}

#if !NET8_0_OR_GREATER
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
    public sealed class InlineArrayAttribute : Attribute
    {
        public InlineArrayAttribute(int length)
        {
            Length = length;
        }

        public int Length { get; }
    }
}
#endif

위와 같이 InlineArrayAttribute를 포함시켜도 빌드할 때 컴파일 오류가 발생합니다.

error CS9171: Target runtime doesn't support inline array types.

오류 메시지가 친절하게 ^^ "Target runtime"이 지원하지 않는다고, 즉, .NET Framework 4.8의 CLR 환경에서는 지원이 안 된다고 알려줍니다.




마지막 4번째로 인해 아마도 해당 문서에서는 "Choosing a language version newer than the default can cause hard to diagnose compile-time and runtime errors."라는 문구를 넣은 듯합니다.

이에 대한 사례로는 ref readonly가 있는데요,

C# 12 - ref readonly 매개변수
; https://www.sysnet.pe.kr/2/0/13428

ref readonly 대신 in 변경자로 처리해야만 했던 C# 11 이하에서는 허용되었던 구문을 ref readonly 이후로는 경고가 발생하는 식으로 바뀌는 등의 미묘한 차이가 있는 것입니다. 또 다른 예로는 C# 9의 개선된 조건 연산자 처리를 들 수 있습니다.

C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)
; https://www.sysnet.pe.kr/2/0/12399

그렇다고 해서, 위에 나열한 2가지 유형들이 이전 버전과의 호환성을 깨뜨릴 정도는 아니고, 단지 경고나 에러로 대체하기 때문에 다시 한번 그 코드를 살펴봐야 하는 정도의 문제가 발생합니다.

아마도 이것 때문에, 마이크로소프트 입장에서는 뭐랄까,,, 약간의 보험 성격으로 "Choosing a language version newer than the default can cause hard to diagnose compile-time and runtime errors." 문구를 넣어둔 것이 아닌가... 하는 개인적인 의견입니다.




정리해 볼까요? 1번과 2번에 해당하는 문법은 그냥 쓰시면 됩니다. 반면 3번과 같은 경우는 어차피 컴파일 오류로 보여주기 때문에 사용하고 싶어도 할 수 없으므로 걱정할 필요가 없습니다.

4번 유형의 경우, 일례로 개선된 타입 추론 등으로 인해 신규 C# 컴파일러로는 경고 또는 에러가 발생할 수 있는 건데요, 만약 그 코드를 유지 보수해야 하는 핵심 인력이 빠졌고, 논리적으로 도저히 건드릴 수 없는 코드라면 그냥 기존 C# 컴파일러를 고수하는 것이 좋겠습니다. 그런 의미에서, 만약 신규 프로젝트를 진행하는 경우라면 최신 C# 버전을 적용하는 것을 두려워할 필요는 없을 것입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 3/7/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  115  116  [117]  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11033정성태8/24/201623475오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201622655개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201618742오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201621892VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201629192.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201622264오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201623938.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201625093Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201623938개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201623116오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
11023정성태8/10/201624634개발 환경 구성: 293. Azure 구독 후 PaaS 서비스 만들어 보기
11022정성태8/10/201625153개발 환경 구성: 292. Azure Cloud Service 배포시 사용자 정의 작업을 추가하는 방법
11021정성태8/10/201622081오류 유형: 349. System.Runtime.Remoting.RemotingException - Type '..., ..., Version=..., Culture=neutral, PublicKeyToken=null' is not registered for activation [2]
11020정성태8/10/201625047VC++: 98. 원본과 대상 버퍼가 같은 경우 memcpy, wmemcpy 주의점
11019정성태8/10/201641889기타: 60. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 (2쇄 정오표)
11018정성태8/9/201626094.NET Framework: 600. 단일 메서드 내에서의 할당으로 알아보는 자바와 닷넷의 GC 차이점 [1]
11017정성태8/9/201627415웹: 33. HTTP 쿠키에 한글 값을 설정하는 방법
11016정성태8/7/201625353개발 환경 구성: 291. Windows Server Containers 소개
11015정성태8/7/201623647오류 유형: 348. Windows Server 2016 TP5에서 Windows Containers의 docker run 실행 시 encountered an error during Start failed in Win32
11014정성태8/6/201624423오류 유형: 347. Hyper-V Virtual Machine Management service Account does not have permission to open attachment
11013정성태8/6/201635192개발 환경 구성: 290. Windows 10에서 경험해 보는 Windows Containers와 docker [4]
11012정성태8/6/201625245오류 유형: 346. Windows 10에서 Windows Containers의 docker run 실행 시 encountered an error during CreateContainer failed in Win32 발생
11011정성태8/6/201626734기타: 59. outlook.live.com 메일 서비스의 아웃룩 POP3 설정하는 방법
11010정성태8/6/201623788기타: 58. Outlook에 설정한 SMTP/POP3(예:천리안 메일) 계정 암호를 잊어버린 경우
11009정성태8/3/201628960개발 환경 구성: 289. 2016-08-02부터 시작된 윈도우 10 1주년 업데이트에서 Bash Shell 사용 [8]
11008정성태8/1/201623112오류 유형: 345. 2의 30승 이상의 원소를 갖는 경우 버그가 발생하는 이진 검색(Binary Search) 코드
... 106  107  108  109  110  111  112  113  114  115  116  [117]  118  119  120  ...