question

divyendudutta avatar image
0 Votes"
divyendudutta asked divyendudutta commented

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

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.

dotnet-csharp
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

II don't see a violation although wonder why you are creating a new instance of program rather than another class.

0 Votes 0 ·

This isn't really production code. Just something to test quickly.

0 Votes 0 ·

Just something to test quickly.

Any test should be a test for something that would be done in a production environment else why do it, no sense to do something without a reason.

0 Votes 0 ·

If it doesn't crash or VS does not show any error, it is ok

0 Votes 0 ·

1 Answer

Bruce-SqlWork avatar image
1 Vote"
Bruce-SqlWork answered divyendudutta commented

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

This is a pretty common practice with public methods and properties.

Sounds good. This is what I was looking for.

Thanks!!


0 Votes 0 ·