possible private access modifier violation due to methods that return by reference

divyendu dutta 21 Reputation points
2021-09-18T23:34:38.687+00:00

Hey,
I've been reading up about methods that return a reference to a variable in C# and just wanted to clarify if the below scenario is an access modifier violation

using System;

class Program {

  private string name = "monty";

  public string Name {
    get{ return name; }
    set{ name = value; }
  }

  public ref string FoobarRef(){
    name += " python";
    return ref name;
  }

  public static void Main (string[] args) {
    Program prog = new Program();
    ref string localName = ref prog.FoobarRef();
    Console.WriteLine(localName); //monty python

    localName += " are very amicable"; //references prog.name

    Console.WriteLine(prog.Name);  //outputs monty python are very amicable
    Console.WriteLine(localName);  //outputs monty python are very amicable
  }

}

In the above code snippet, I'm able to access and change (via a reference ie. localName), a private field of the class (name) outside the class.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,320 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 57,241 Reputation points
    2021-09-19T19:09:15.453+00:00

    You are not accessing the private property, you are are accessing a public method that exposes the private. This is a pretty common practice with public methods and properties.

    Note: a ref is a pointer to a value, and you are exposing this pointer as public.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful