简体   繁体   中英

Use a static readonly field in constructor C#

Below is my class with a static readonly field:

public class Stats
{
    public static readonly int MinPoints = 900;
    public static readonly int MaxPoints = 1500;

    public int Points { get; }

    private Stats()
    {
    }

    public Stats(int points) : this()
    {
        if (points < Stats.MinPoints || points > Stats.MaxPoints)
        {
            throw new InvalidOperationException();
        }

        Points = points;
    }
}

When compiling, I don't have any errors. But when I try to instanciate a Stats object, I'm getting a TypeInitializationException . When replacing PlayerStatistics.MaxPoints in the constructor with its proper value, the code works.

Here is the error I get when unit testing the constructor:

Expected a <System.InvalidOperationException> to be thrown, but found <System.TypeInitializationException>: "
"System.TypeInitializationException with message "The type initializer for 'League.Domain.Player.Stats' threw an exception."
     at League.Domain.Player.Stats..ctor(Int32 points) in C:\dev\repos\League\League.Domain\Player\Stats.cs:line 24
     at League.Tests.StatsSpecs.<>c__DisplayClass1_0.<Create_stats_with_incorrect_points_should_throw_exception>b__0() in C:\dev\repos\League\League.Tests\StatsSpecs.cs:line 36
     at FluentAssertions.Specialized.ActionAssertions.InvokeSubject()
     at FluentAssertions.Specialized.DelegateAssertions`1.InvokeSubjectWithInterception()
.
   at FluentAssertions.Execution.XUnit2TestFramework.Throw(String message)
   at FluentAssertions.Execution.TestFrameworkProvider.Throw(String message)
   at FluentAssertions.Execution.DefaultAssertionStrategy.HandleFailure(String message)
   at FluentAssertions.Execution.AssertionScope.FailWith(Func`1 failReasonFunc)
   at FluentAssertions.Execution.AssertionScope.FailWith(Func`1 failReasonFunc)
   at FluentAssertions.Execution.AssertionScope.FailWith(String message, Object[] args)
   at FluentAssertions.Specialized.DelegateAssertions`1.Throw[TException](Exception exception, String because, Object[] becauseArgs)
   at FluentAssertions.Specialized.DelegateAssertions`1.Throw[TException](String because, Object[] becauseArgs)
   at League.Tests.StatsSpecs.Create_stats_with_incorrect_points_should_throw_exception(Int32 points) in C:\dev\repos\League\League.Tests\StatsSpecs.cs:line 38

And here is my unit test, written with XUnit:

[Theory]
[InlineData(899)]
[InlineData(1501)]
public void Create_stats_with_incorrect_points_should_throw_exception(int points)
{
    Action action = () => new Stats(points);

    action.Should().Throw<InvalidOperationException>();
}

Is there a way to still use the static readonly field in the constructor?

I was able to find the solution...

I tried to simplify my code too much, and omitted to put a line in my class:

public class Stats
{
    // I didn't put this line of code, so it was working without it
    public static readonly Stats New = new Stats(1000);

    public static readonly int MinPoints = 900;
    public static readonly int MaxPoints = 1500;

    public int Points { get; }

    private Stats()
    {
    }

    public Stats(int points) : this()
    {
        if (points < Stats.MinPoints || points > Stats.MaxPoints)
        {
            throw new InvalidOperationException();
        }

        Points = points;
    }
}

So as mentioned Dmitry Bychenko, static readonly field are not assign at compile time. So if I were to put these lines before the line I ommited, like this:

public static readonly int MinPoints = 900;
public static readonly int MaxPoints = 1500;

public static readonly Stats New = new Stats(1000);

It would work fine.

And thanks to his comment, using const instead of a static readonly field make my code work, at any place I put these these two constants in my class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM