Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dynamic Variables from C++ Pointers

Tags:

c++

c#

Super simple C# question as I'm trying to pick up the language better. I'm coming from a C++ background and am a little unsure of the solution to not having pointers.

For example, if I wanted a single reference to a variable I would declare it as

class Foo{
private:
    SomeClassType* sct;
    SomeOtherClass* soc;
public:
    Foo(SomeClassType* xSct, SomeOtherClass* xSoc) : sct(xSct), soc(xSoc) {}
}

So in C# I would have to use I'm guessing either a static reference or maybe some other dynamic allocation way? I don't want 100's of these floating out there. I can't for the life of me seem to Google the right words to figure this out.

What is the equivalent in C#?

like image 451
sl133 Avatar asked Aug 13 '26 17:08

sl133


2 Answers

Super simple C# question

Actually this is a pretty deep question.

I'm coming from a C++ background and am a little unsure of the solution to not having pointers.

C# does have pointers but they are almost never used.

For example, if I wanted a single reference to a variable

There is the problem right there. Stop thinking I need a reference to a variable, so I need a pointer. Yes, pointers are an implementation of references to variables, but that is very much the wrong way to think about it in C#. In C# you can make references to variables in a couple different ways, but you almost never need to. What you do in C# is make references to objects, not to variables.

In C#, a value that is of a type that is a reference type is automatically a reference to an object of that type.

So:

class C 
{ 
    public int x; 
}

A value of type C is a reference to an instance of C; that's what "class" means in C#. So you can then say:

class D 
{
    public C c; 
}

And an instance of D has a field of type C. That's a variable. The variable's value is a reference to an instance of type C. That instance has a variable x of type int; that variable's value is not a reference to anything, it's just the integer.

like image 107
Eric Lippert Avatar answered Aug 16 '26 07:08

Eric Lippert


C#'s references would replace your pointers here:

class Foo {
  SomeClassType sct;
  SomeOtherClass soc;

  public Foo(SomeClassType xSct, SomeOtherClass xSoc) {
    // Note: No initializer list, we have to do those assignments manually
    sct = xSct;
    soc = xSoc;
  }
}

They actually act pretty much the same for most usages (exceptions would be pointer arithmetic, which would be useless here anyway). Access to members of those instances is always done with a dot . in C#; no -> like in C++.

In a way you can treat them like C++ references, just that you can re-assign them.

like image 26
Joey Avatar answered Aug 16 '26 06:08

Joey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!