Jump to content
Xtreme .Net Talk

_SBradley_

Avatar/Signature
  • Posts

    29
  • Joined

  • Last visited

Everything posted by _SBradley_

  1. It's the same in C++ No, it's exactly the same thing. For example, in C#, you could have something like this: using System; class A { } class B : A { } class C : A { } class Test { static void byval(A a) { a = new C(); } static void byref(ref A a) { a = new C(); } static void Main() { A a = new B(); Console.Write(a + " => "); byval(a); Console.WriteLine(a); a = new B(); Console.Write(a + " => "); byref(ref a); Console.WriteLine(a); } } The corresponding C++ [is there a tag for including C++?] would look something like this: #include <iostream> class A { }; class B : public A { }; class C : public A { }; void byval(A* a) { a = new C(); } void byref(A*& a) { a = new C(); } int main() { A* a = new B(); std::cout << a << " => "; byval(a); std::cout << a << std::endl; a = new B(); std::cout << a << " => "; byref(a); std::cout << a << std::endl; } The results are, for C#: B => B B => C and, on my computer, for C++: 00312C50 => 00312C50 00312C70 => 00312C80
  2. In C#, everything is passed by value, unless either ref or out is specified on the parameter. For example, an int/Int32 is passed by value; a TrackBar reference is also passed by value. Read that last sentence again: the reference itself is passed by value! Think about the following method: void f(TrackBar tb) { ... } The parameter tb is passed by value. You can see this, as there is absolutely no way for tb to be altered on return to the caller: tb will definitely be referencing the same object (or be null) both before and after the call to f(). Of course, the object to which tb refers can be modified in any way you like. This does not mean that the tb reference itself is being passed by reference! Compare this to the following: void f(ref TrackBar tb) { ... } Now it is possible that tb could be altered, in the eyes of the caller, during the call to f(). That is, tb is being passed by reference. For example, tb could be referring to a TrackBar instance before the call to f(), but be null by the time the method returns. The moral of the story is this: everything (in C#) is passed by value, unless explicitly stated otherwise. Don't be confused between true pass-by-reference (the parameter is marked either ref or out) and simply passing an object reference by value.
  3. How about this: using Stuff = System.Int32; Then you can write such lovely code as: Stuff stuff = 5;
×
×
  • Create New...