Search code examples
c#.net-core-3.1

Does the compiler optimize a functor field initialized in its declaration by a lambda to make the lambda static?


If I write a class like I have below:

using System;

namespace MyNamespace
{
    public class MyClass1
    {
        //example Functor
        public Func<int, bool> IsLeapYear { get; set; } = (year) => (year % 4u == 0u && year % 100 != 0) || (year % 400 == 0);
    }
}

Do I have a different instance of the functor for every instance of MyClass or a reference for the same one?

What if I do this?

using System;

namespace MyNamespace
{
    public class MyClass2
    {
        private static readonly Func<int, bool> _isLeapYear = (year) => (year % 4u == 0u && year % 100 != 0) || (year % 400 == 0);
        public Func<int, bool> IsLeapYear { get; set; } = _isLeapYear;
    }
}

I would expect every instance of MyClass2 to hold the same instance of the functor for sure in this case. I want to know if the code of MyClass1 is equivalent to that of MyClass2 because I have a ton of functors in the same class, and I was hoping to make my code shorter.

I use .NetCore 3.1, C# 8.0, Visual Studio Enterprise 2019. (I tagged the question with because I figured the compiler is part of the framework).

[Edit: highlighted in bold the actual question]


Solution

  • It will be the same instance.

    public class MyClass1
    {
        //example Functor
        public Func<int, bool> IsLeapYear { get; set; } = 
            (year) => (year % 4u == 0u && year % 100 != 0) || (year % 400 == 0);
    }
    
    var a = new MyClass1();
    var b = new MyClass1();
    
    // result = true
    var result = object.ReferenceEquals(a.IsLeapYear, b.IsLeapYear);