Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
Impact of using the 'ref' keyword for string parameters in methods in C#?

As a programmer who don't have a good idea about the .NET pipeline, I was wondering if using ref strings as parameters are good for performance in C#?

Let's say I have a method like this:

public int FindSomething(string text)
{
    // Finds a char in the text and returns its index
}

When I use this method, the compiler creates a copy of the text for the method, right?

But if I use the ref keyword:

public int FindSomething(ref string text)
{
    // Finds a char in the text and returns its index
}

.. the compiler should only send the text's pointer address...

So is it good for performance using ref like this?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

When I use this method, the compiler creates a copy of the text for the method, right?

No, it doesn't. string is a reference type, and the compiler will create a new stack variable which points to the same string represented at a given memory address. It won't copy the string.

When you use ref on a reference type, there won't be a copy of the pointer to the string created. It will simply pass the already created reference. This is useful only when you want to create an entirely new string:

void Main()
{
    string s = "hello";
    M(s);
    Console.WriteLine(s);
    M(ref s);
    Console.WriteLine(s);
}

public void M(string s)
{
    s = "this won't change the original string";
}

public void M(ref string s)
{
    s = "this will change the original string";
}

So is it good for performance using ref like this?

The performance gains won't be noticeable. What will happen is other developers getting confused as to why you used ref to pass the string.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!