Lester
Lester

Reputation: 4413

Defining constants by scope in C#

I've always been in the habit of defining constants at the class level:

public class MyClass
{
    private const int SomeNumber = 10;
    ...
}

But, I recently worked with someone who believes that if a constant is only used by a specific method it should be defined in that method:

public class MyClass
{
    public void SomeMethod()
    {
        const int SomeNumber = 10;
        ...
    }
}

My only argument for preferring the first is that if the constant is needed in other methods there is no refactoring needed and also it makes it easier to update constants since they'll be defined in the same place.

Are there any other pros/cons or is there no real difference?

Upvotes: 3

Views: 1972

Answers (4)

user395760
user395760

Reputation:

A common reasoning against globals, singletons, etc. is that the scope of everything should be limited as far as (reasonably) possible. I agree - the smaller the scope, the less code can break when someone messes with it and the less code can mess with it. This reasoning doesn't quite apply to constants. But still, if it is only needed in a single method, define it there. If only to prevent some fool from using it in a completely unrelated context because it happens to fit, breaking stuff when the "constant" does change (which shouldn't be often - otherwise it's not a constant but should go in a configuration file - but still).

As for "less refactoring if other methods need to access the constant"... YAGNI.

Upvotes: 2

mlibby
mlibby

Reputation: 6724

The method level const hints to the compiler that the variable will not change so it can optimize for that case. Which is great if you are in the habit of hard-coding strings or numbers into your methods that are not used outside those methods. Which is not, imho, a good habit.

Upvotes: 1

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120927

If it needs updating it's not really a constant. I mean, you don't often refactor the value of Pi. Things that change belong in a configuration file in my opinion.

That said, I usually use class level public constants. I've never seen or used method-level constants. Conceptually, a method level constant makes little sense to me.

Upvotes: 5

TalentTuner
TalentTuner

Reputation: 17556

i would go with your approach of defining at least at class level. so that same constant can be seen by various methods of class.

or even better approach

define all constant in a single class so that all those constants can be seen by differnt classes through out your solution eevn if you want to change some logic in the constant calculation you can do it at a centrilized place.

Upvotes: 0

Related Questions