Any way for a class to prevent outside code from declaring variables of its type?
Posted
by
supercat
on Stack Overflow
See other posts from Stack Overflow
or by supercat
Published on 2011-01-06T00:26:24Z
Indexed on
2011/01/06
1:53 UTC
Read the original article
Hit count: 566
Is it possible for a class of exposing a type for function returns, without allowing users of that class to create variables of that type? A couple usage scenarios:
- A Fluent interface on a large class; a statement like "foo=bar.WithX(5).WithY(9).WithZ(19);" would be inefficient if it had to create three new instances of the class, but could be much more efficient if the WithX could create one instance, and the other statements could simply use it.
- A class may wish to support a statement like "foo[19].x = 9;" even when foo itself isn't an array, and does not hold the data in class instances that can be exposed to the public; one way to do that is to have foo[19] return a struct which holds a reference to 'foo' and the value '19', and has a member property 'x' which could call "foo.SetXValue(19, 9);" Such a struct could have a conversion operator to convert itself to the "apparent" type of foo[19].
In both of these scenarios, storing the value returned by a method or property into a variable and then using it more than once would cause strange behavior. It would be desirable if the designer of the class exposing such methods or properties could ensure that callers wouldn't be able to use them more than once. Is there any practical way to accomplish that?
© Stack Overflow or respective owner