1

If I did something like this:

public int Foo
{
    get
    {
        return GetFoo() + 5;

        int GetFoo() => 3;
    }
}

It will actually compile, which makes me wonder if this would be a good or bad practice.

Now, clearly this particular example can be refactored into: public int Foo => 8;, but other cases might have a few local methods and doing stuff in it's main get portion.

Keeping in mind the fact that C# actually moves GetFoo outside of property or method it is in whenever the code is compiled, this should have just about the exact same performance as a property calling a normal method.

However, If one feels the need to use local functions in a property, is that a sign that the property is doing too much work and should be a method instead?

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
  • Unfortunately this is going to be primarily based on opinion. – Lasse V. Karlsen Jun 01 '18 at 07:09
  • Yeah, I had a feeling, but I just thought I'd see what people's thoughts are. What do you think? – AustinWBryan Jun 01 '18 at 07:11
  • 1
    This is opinion based, though i personally tend to extract complexity from a property and move it to a private method, properties in my mind shouldnt do much, and any class logic should be found in the class, saves having to search through gettters and setters for implementation.. on saying that, having a local function in a property is inert, though still a little smelly – TheGeneral Jun 01 '18 at 07:16
  • Right, I feel properties should be kept for simple things as well. Thing is, C# will be moving the functions into the class file itself later anyways. What is gained is increased abstraction, the same benefits of using them in normal methods, but, as you said, it would be harder to find the methods. Though it would get down to opinion, I feel like it's a smell to, that your property is getting too complicated. – AustinWBryan Jun 01 '18 at 07:20
  • 3
    I think that properties should be lightweight, if you feel the need to masquerade a method inside a property then I think the property should become a method as well. – Lasse V. Karlsen Jun 01 '18 at 08:11

0 Answers0