Search code examples
c#static-methods

C# Static method modifying an object


Imagine something like this...

public class Result
{
    public string Name {get; set;}

    public int Score {get; set;}

    public bool Pass {get; set;}
}

And a static method...

public static Result SetPass(this Result result)
{
    result.Pass = result.Score > 50;

    return result;
}

My question is do I have to return the result or is it already modified in place? Could I make the return type void and then iterate through a collection of results and amend in place like this...

foreach (var result in results)
{
    result.SetPass();
}

or do I need to return the result object and re-assign?


Solution

  • Since Result is a class, it is currently modified on the single object - essentially in-place; this is passing a reference by-value. As such, there is no point having a return value here.

    If Result was a struct, you would need to either return a new value, or use (ref this Result result) (making it pass a value by-reference); note that the compiler is lenient in this case, and allows the ref to be used implicity in this scenario (ref usually needs to be explicit at both caller and callee).