0

I just noticed that i am able to pass private object to another class by a reference

I would guess this should not be possible but it works fine

Here an example

private static StreamWriter swYandexErrors; // in classA

 csLogger.logAnyError(ref swYandexErrors, $"msg", E); // in classA

// in class csLogger
    public static void logAnyError(ref StreamWriter swError, 
string srError, Exception E = null)
    {
        lock (swError)
        {
            swError.WriteLine("");
            swError.Flush();
        }
    }
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
  • 1
    Why would you expect this to not be possible? `private` hides a value from the classes outside the class it is declared in. You can still pass it to functions within that class. – Jamadan Apr 05 '17 at 09:47
  • @DarthJam so passing into other classes are not a problem. i see – Furkan Gözükara Apr 05 '17 at 09:49
  • What is the problem? You still call it inside your classA. If you could pass it from outside of classA: an instance of ClassA or another class, it is problem. – TriV Apr 05 '17 at 09:51

1 Answers1

6

private means just private for that variable, not for the actual instance which is referenced by that variable. So the reference swYandexErrors which is private in your class is of course not visible to the other one. However as you´re passing the instance by reference you can of course access the instance within your first class.

To be more clear the following does not work in class csLogger and causes a compiler-error as you can´t access swYandexErrors within csLogger:

public static void DoSomething()
{
    ClassA.swYandexErrors.Read();
}

As an aside: you don´t even need the ref-keyword in your method, as you don´t re-assign the passed StreamWriter. All you´re doing is to call members on the passed instance.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • ty for the answer. yes i know i dont need ref word since it is reference type but putting ref makes it explicitly more clear when reading :) – Furkan Gözükara Apr 05 '17 at 10:31
  • Don´t do this to identify you´re calling or changing the members of your instance. See this post: http://stackoverflow.com/questions/41802039/pass-reference-type-by-reference-to-indicate-it-will-be-modified – MakePeaceGreatAgain Apr 05 '17 at 10:40
  • but visual studio does not explicitly shows which objects are reference type or not. so i just want to be sure also. also i didnt get why it may be bad to give ref word? – Furkan Gözükara Apr 05 '17 at 12:06
  • It seems you misunderstand what `ref` means. Anyway I can´t see any reason to know if a variable is a reference- or a value-type. In doubt you´ll get a compiler-error very soon if you use the whrong one. – MakePeaceGreatAgain Apr 05 '17 at 12:10
  • Ok after playing a bit with few examples i understood. ref value is only needed when the object is re-composed by new assigment – Furkan Gözükara Apr 05 '17 at 12:15