0

I am working on a project that has nested Lists of classes. hence my code look like this when I want to get a variable.

MainClass.subclass1[element1].subClass2[element2].subClass3[element3].value;

I was wondering how I could get an alias for subClass3 so I can get all the variables in it without having to look in all the subclasses, like this.

subClass3Alias.value

in c++ this would be easy simply have a pointer pointing to it, but C# does not really have pointers.

user3813249
  • 313
  • 1
  • 4
  • 12

1 Answers1

4

No need for pointers – types in C# are usually reference types anyway, meaning that you can just copy them and they will refer to the original object (like pointers in C++):

var subclassAlias = MainClass.subclass1[element1].subClass2[element2].subClass3[element3];

Now you can use subclassAlias.value.

A slightly different thing occurs if your type happens to be a value type: in that case, the above will still work – but subclassAlias will be a value copy of the original value, meaning that changes to subclassAlias will not be reflected in the original object.

That said, this looks like suspicious code anyway – normally such deep levels of nesting are a sign of bad design and violate the Law of Demeter.

(Incidentally, in C++ you wouldn’t use pointers either.)

Community
  • 1
  • 1
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • It would be a variable containing a reference (most likely), aka a pointer. – Lasse V. Karlsen Jul 09 '14 at 14:50
  • 2
    It's probably best to use the proper terms to avoid confusion later. In C#, a pointer is rarely used, and is something different. A C# reference value functions much like a C++ pointer value, though. –  Jul 09 '14 at 14:53