declaring strings inside vs. outside of functions

D

darrel

Often, I want to use a string in multiple functions on a page. I can declare
and re-set the string in each function, or I can just delcare the string
outside of the individual functions so that they can all see it.

This works fine.

My question is if there is any reason NOT to go ahead and declare ALL
strings at the top? Is there a performance/memory hit in doing that? Or is
it simply a matter of clean code syntax/layout?

-Darrel
 
S

Scott Allen

Go for clear code that is also easy to read and maintainable. If the
string serves different purposes in the different methods, than you
should keep the declaration inside the methods as this can reduce
confusion tremendously.
 
W

William F. Robertson, Jr.

Strings are immutable in .NET. What that means is every operation, every
change, any time you change a string, and new string is created and the old
one is marked for GC.

string s = "hello";
s = s.Replace( "hell", "heaven" );

Two strings were created. I think there is actually more because the string
literals must be loaded.

IMHO, it is more a style issue. I like to have strings declared inside my
methods, they are marked for GC faster when the methods exits, rather than
when the Page is done processing a request.

HTH,

bill
 
K

Kevin Spencer

You're talking about the issue of scope. There is a reason why variables
declared inside functions aree not accessible from outside those functions.
They are scoped to function scope, and are protected from any other code
modifying them unintentionally. When you want to use a variable in more than
one function, it is good to declare it global to the class (as a field or
property). When you don't, it is dangerous to declare it global, as it may
be unintentionally modified by some other code than the function for which
you intended it.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top