5

are there any significant difference between class-level string constants vs method level string constants. Will compiler recognize constants and apply constant folding? Or nw object always will be created?

Here is example: class-level consts

class A
    {
        private const string Sid = "sid";
        private const string Pid = "pid";

        public void Do()
        {
            Console.WriteLine(Sid);
            Console.WriteLine(Pid);
        }
    }

Method-level constants:

class B
    {
        public void Do()
        {
            const string Sid = "sid";
            const string Pid = "pid";

            Console.WriteLine(Sid);
            Console.WriteLine(Pid);
        }
    }
3
  • 1
    "Will compiler recognize constants and inline them?" what is inline in this context? Commented Mar 6, 2013 at 1:39
  • Sorry, I mean constant folding, so that object won't be deleted and created every time method accessed. Commented Mar 6, 2013 at 1:46
  • Const is a static variable, so yes, it won't be created every time. Commented Mar 6, 2013 at 1:48

2 Answers 2

1

String constants are newer "inlined"* because they are true objects. Compiler will always merge parts of the same string constant added together (i.e. "a"+"b" is identical to specifying "ab").

String constants also can "interned" - meaning all constants of the same value are referring to the same actual string object (To my knowledge C# compiler always does that).

Numeric constants can be "inlined" into places where they are used in addition to always computed as much as possible at compile time (i.e. 2*2*4 is identical to specifying 16).

To achieve "shared constant" behavior one need to use readonly fields instead of const.

*"inline" as placed into resulting code directly instead of referencing a shared value.

Sign up to request clarification or add additional context in comments.

Comments

1

The difference between the constants is in scope - just as with a non-const declaration, the main thing to consider is from where these values can be accessed. Now, which declaration is cleaner is irrelevant enough to be worthy of an epic flame war...

2 Comments

Scope in this case is only at compile time correct? So once the application is compiled it doesn't matter anyway?
Right, a const is a const wherever it is - it doesn't really have scope after compilation, since it is replaced.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.