Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi folks,

lets assume I have the following code workflow:

C#
string s = "SOME_LONG_AND_NASTY_STRING_PROBABLY_A_BASE64_STRING";
WriteToDB(s);

public void WriteToDB(string str){
    InsertInDB(str);
}

public void InsertInDB(string str)
{
    //Do writing here using str
}


Since the string is a value type immutable each method call with it as parameter leads to a copy of that string in the memory. Even if WriteToDB justs routes the string to InsertInDB a copy is created. To minimize this bad effect I can wrap it in some data container and pass the container around. The container is of course a reference type.

What if I wrap the string in a Func<string> delegate (see below)?

C#
string s = "SOME_LONG_AND_NASTY_STRING_PROBABLY_A_BASE64_STRING";
WriteToDB(()=>s);

public void WriteToDB(Func<string> f_str){
    InsertInDB(f_str);
}

public void InsertInDB(Func<string> f_str)
{
    //Do writing here using f_str()
}


Is it true that the string is wrapped inside the Func-object and therefore passed as a reference type just like if i put it in a data container?

Id like to prevent myself to write a data container just to hold the string. Is there a better way to have a string passed as a parameter but without having it copied all the time? I know the ref keyword, but that seems to be wrong either in this case.

Thanks for your suggestions.

Jens
Posted
Updated 11-Dec-12 23:10pm
v2
Comments
Sergey Alexandrovich Kryukov 11-Dec-12 11:40am    
Makes no sense at all, sorry.
--SA

1 solution

Since when was a string a value type?
Trust me on this, all .NET strings are reference types, so your concern is immaterial. (As is your question :laugh:)
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 11-Dec-12 11:42am    
Exactly, a 5.
--SA
fjdiewornncalwe 11-Dec-12 11:59am    
My 5
Thomas Daniels 11-Dec-12 12:17pm    
+5!
Jibesh 11-Dec-12 14:09pm    
true!
Jens Meyer 12-Dec-12 5:09am    
Ok, thanks for your answers. I confused reference type/value type with types beeing immutable. So keeping immutable instead of value type in mind my question stays the same. I edited the original question.

Please give me any further advice on this.

Thanks and regards

Jens

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900