0
class foo
{
    string bar()
    {
        const string c = "dead beef";
        return c;
    }

    void Test()
    {
        string a = bar();
        string b = bar();
    }
}

are a and b different instance or are they pointing to the same memory address? (the == comparison would return true regardless they are the same instance or not so I can't really test it)

5
  • 2
    Strings are immutable, so you don't need to know or care. You can use Object.ReferenceEquals to find out though. Commented Jan 24, 2018 at 21:58
  • @Blorgbeard was wondering if im saving some tiny bit of resource for methods that will be called millions of times Commented Jan 24, 2018 at 22:00
  • @Steve Then measure how long it takes to run your method millions of times and see if changing the implementation changes the time. Commented Jan 24, 2018 at 22:01
  • If you'd like to see the difference local const variables have on the generated IL, take a look at a question I asked back in '09 - stackoverflow.com/questions/1707959/… Commented Jan 24, 2018 at 22:14
  • Imo, this would get inlined anyway, so doesn't matter. The call would never happen. Commented Jan 24, 2018 at 22:20

1 Answer 1

1

No, but it doesn't really matter for the majority of cases.

For structs (int, float, DateTime, etc) the value will placed on the stack so the memory reuse isn't relevant.

For strings, const doesn't do anything special but string constants themselves are interned so all matching constant string values will point to the same instance in memory.

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

2 Comments

interesting. that's why Object.ReferenceEquals(a, b) returns true or string but not int
Because ints are not objects, so they will boxed into (separate) object wrappers so they can be passed to ReferenceEquals.

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.