tafuji's blog

C#, Xamarin, Azure DevOps を中心に書いています。

Xamarin.Forms で C# 9.0 を使う

はじめに

Xamarin.Forms で C# 9.0 が利用できるらしいとのことなので、確認のためのメモです。

結論

Xamarin.Forms のプロジェクトファイルに以下の設定を追加する。

<PropertyGroup>
    <LangVersion>9.0</LangVersion>
</PropertyGroup>

System.Runtime.CompilerServices.IsExternalInit 関連のエラーが出るときは、以下のコードを追加する。

namespace System.Runtime.CompilerServices
{
    public class IsExternalInit { }
}

メモ

Visual Stuiod で Xamarin.Forms の新規プロジェクトを作成する。(Version 16.8.2 を利用)

record 型のクラスを Xamarin.Forms のプロジェクトに追加する

public record Person
{
    public string LastName { get; }
    public string FirstName { get; }

    public Person(string first, string last) 
        => (FirstName, LastName) = (first, last);
}

この段階では、当然、コンパイルエラーがでる。

Before

プロジェクトファイルで言語バージョンを指定する。

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <ProduceReferenceAssembly>true</ProduceReferenceAssembly>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebugType>portable</DebugType>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>

  <!-- C# 9.0 -->
  <PropertyGroup>
    <LangVersion>9.0</LangVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Xamarin.Forms" Version="4.8.0.1451" />
    <PackageReference Include="Xamarin.Essentials" Version="1.5.3.2" />
  </ItemGroup>
</Project>

先ほどまで出ていたコンパイルエラーが消えた。

System.Runtime.CompilerServices.IsExternalInit 関連のエラーが出るときは、以下のコードを追加するとよい。

namespace System.Runtime.CompilerServices
{
    public class IsExternalInit { }
}

参考にしたサイト