user7127000 user7127000 - 4 years ago 99
C# Question

Equivalency between pointers and function parameters in C++ and C#

Let me know if any of my following understanding is inaccurate.


  1. MyClass m = new MyClass()
    <--->
    MyClass * m = new MyClass;

  2. ??? (no C# equivalent) <--->
    MyClass m(5,"foo");

  3. void SomeMethod(ref Widget w)
    <--->
    void SomeMethod(Widget & w)
    or
    void SomeMethod(Widget * * w)

  4. void SomeMethod(Widget w)
    <--->
    void SomeMethod(Widget * w)

  5. ???
    (no C# equivalent) <--->
    void SomeMethod(const Widget)

  6. ???
    (no C# equivalent) <--->
    void SomeMethod(const & Widget)

  7. void SomeMethod(out Widget w)
    <---> ??? (no C++ equivalent)


Answer Source

C# and C++ are quite different, more than their names would suggest, but I will try anyway:

MyClass m = new MyClass() <---> MyClass * m = new MyClass;

Roughly equivalent, except that C# will collect m after it is no longer in use. With C++ you must remember to delete the object. In C++ it is more idomatic to allocate to the stack or use a smart-pointer.

??? (no C# equivalent) <---> MyClass m(5,"foo");

C# does not give you much control over where objects are allocated. However, it has struct types that can avoid heap allocation.

void SomeMethod(ref Widget w) <---> void SomeMethod(Widget & w) or void SomeMethod(Widget * * w)

These are similar, but in C# ref should usually be avoided.

void SomeMethod(Widget w) <---> void SomeMethod(Widget * w)

The main difference here is that in C++ anyone with a pointer to an object may delete it. In C# the garbage collector handles the deletion. C# is a bit like using std::shared_ptr, but with cycle-detection.

??? (no C# equivalent) <---> void SomeMethod(const Widget)
??? (no C# equivalent) <---> void SomeMethod(const & Widget)

C# does not have a powerful notion of const like C++ does. Typically the entire type must be made immutable using the readonly keyword on each field.

void SomeMethod(out Widget w) <---> ??? (no C++ equivalent)

In C++ taking an object by reference can achieve the same as out variables. out variables are usually bad practice, so this keyword is a form of documentation.

Most importantly, take the time to understand how code is meant to be written in each language. Many of the concepts are shared, but to really take advantage of a technology, you should work with it, rather than try to force one paradigm into another.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download