Re: Assigning a reference to a variable



Jon.. In C++ if *p is a very large object then passing p may avoid a
call to the copy constructor. In C++ classes use value semantics by
default, but in C# classes use reference semantics. So in C# you can
simply return a reference to an object and not worry about a call to the
copy constructor.

We can demonstrate this difference in C++/CLI since C++/CLI supports
both value semantics and reference semantics, unlike C#. So in C++/CLI
if you have ref class SomeClass you can create an object using reference
semantics as in:

SomeClass^ someClass= gcnew SomeClass(); or you can use value semantics
as in:

SomeClass someClass();

SomeClass^ someClass1= someClass does not call the copy constructor.

SomeClass someClass2= someClass does call the copy constructor, but only
in C++/CLI. I don't know of any equivalent in C#.

Another reason to use indirection is to provide read only access to a
variable. This is possible in C++ using the const key word, but const is
not supported in C#. To proved read only access to a read/write
variable, in C# you can wrap a reference to the read/write class in a
wrapper class that simply provides pass through get only access to the
variable using delegation.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
.



Relevant Pages

  • Re: Inherited Methods and such
    ... Now, what you want is to get in the constructor of some S derived from T, ... I have no problem with the semantics of object ... wrong to call it "dispatch on the operations of T." ... procedure Register; ...
    (comp.lang.ada)
  • Re: Returning by value (here we go again!)
    ... > and as such the copy constructor wouldn't need to be ... This can be achieved with move semantics: ... substr to construct another string. ... into an existing string a temporary is still created. ...
    (comp.lang.cpp)
  • Re: Intellisence rounds of the default values
    ... SomeClass; ... Intellisense did not give me any help though I would have expected ... truncate the way you had observed. ... is that as I was entering the implementation of the constructor ...
    (microsoft.public.vstudio.development)
  • Re: Java Interface usage
    ... > constructor for SomeClass. ... > available to SomeClass without this code in the constructor ... > public interface SomeWords{ ...
    (comp.lang.java.programmer)
  • Re: Constructor good for loading file contents?
    ... the same file through its existence, then put it in the constructor. ... > SomeClass s = new SomeClass; ... > I can think of one case when there's a need for a separate Load()> method. ... > XmlDocument x = new XmlDocument; ...
    (microsoft.public.dotnet.languages.csharp)