In a C# application I am working on I have a very long identifier as follows:-
foo.bar.bwah.blah.whatever.very.very.huge
Whenever I to reference this object it’s an absolute nightmare, and unfortunately I do need to reference it a lot:-
var something = foo.bar.bwah.blah.whatever.very.very.huge.a; var somethingElse = foo.bar.bwah.blah.whatever.very.very.huge.b; foo.bar.bwah.blah.whatever.very.very.huge.c = 12;
etc. etc.
I want to update this code using a far smaller alias of some kind, the problem is however that I want to change the underlying reference, and have the alias update also without explicitly updating the alias.
Currently if I do the following:-
foo.bar.bwah.blah.whatever.very.very.huge.a = 'hello'; string shorter = foo.bar.bwah.blah.whatever.very.very.huge.a; foo.bar.bwah.blah.whatever.very.very.huge.a = 'world'; Console.WriteLine(shorter);
It will output ‘hello’. What I want to achieve is something like the following:-
foo.bar.bwah.blah.whatever.very.very.huge.a = 'hello'; string** shorterPointer = &foo.bar.bwah.blah.whatever.very.very.huge.a; foo.bar.bwah.blah.whatever.very.very.huge.a = 'world'; Console.WriteLine(**shorter);
Which would output ‘world’ as required.
I believe you can achieve something like this using unsafe code in C#, however I cannot do that, I have to use safe code only.
Does anybody have any ideas how I might achieve this?
Please Note: This question is not about strings being immutable, I know they are – in fact I assumed they are for the purposes of the question. It might perhaps be simpler if I used some other type… so when I assign ‘hello’ to a then ‘world’ to a, I am instantiating different objects on each occasion, hence my stored reference to a becomes invalid after re-assignment.
One way out is to use one or a pair of lambdas.
For example:
Now, you can use getter and setter to read and write the long identifier.
However, since your dots are member accessors, the easiest way of going about it is to take a reference to the immediate parent, like so:
This is good practice in any case, as a long dotted expression like this is a violation of the Law of Demeter, which inhibits the flexibility of the codebase – it requires too much information in too many places.