Shallow copy of object referenced array - arrays

I want to implement the ICloneable.Clone() function.
My class has some primitive members but also an array of referenced objects.
In this referenced object class, I don´t want to implement this function too, so I´m wondering if it is easily possible to do sth like MemberWise Clone from outside.
Public Function Clone() As Object Implements ICloneable.Clone
Return Me.MemberwiseClone
End Function
I have found sth like Array.Clone, but this only works for primitive Types?

You're almost there.
Public Function Clone() As Object Implements ICloneable.Clone
Dim copy = Me.MemberwiseClone
copy.SomeArray = copy.SomeArray.Select(Function(r) r.Clone).ToArray()
Return copy
End Function
Note that since MemberwiseClone is protected, you can't call MemberwiseClone on the objects in the array if those objects are not part of the same inheritance hierarchy as the object implementing this function.

Related

How can I populate an instance of an object with random values?

Is there any way I can give AutoFixture an instance of an object and have it go through all the setters and set random data? The wiki examples only show how to obtain an instance from AutoFixture, e.g.
var autoGeneratedClass = fixture.Create<ComplexParent>();
My example use case is a factory method which generate instances of objects with dynamic properties based on a configuration. I want to test that my methods correctly, detect and interact (e.g. copy) these dynamic properties.
dynamic dynamicPropertyObject1 = factoryMethod(configuration);
dynamic dynamicPropertyObject2 = factoryMethod(configuration);
dynamicPropertyObject1.propA = random.Next();
dynamicPropertyObject1.CopyTo(dynamicPropertyObject2);
Assert.That(dynamicPropertyObject2.propA, Is.EqualTo(dynamicPropertyObject1.propA);
Thanks
AutoFixture has a lot of built-in heuristics for creating objects, including some for factory methods.
If AutoFixture finds no public constructors on a type, it starts to look for factory methods; i.e. static methods that return objects of the type of the class that defines that static method, e.g.
public class Foo
{
public static Foo CreateFoo();
// ... other members
}
If, on the other hand, a factory method exists on another class, you'll need to help AutoFixture a bit. The easiest way would be to use the Customize method:
fixture.Customize<Foo>(c => c
.FromFactory(() => FooFactory.CreateFoo())
.WithAutoProperties());
When you subsequently ask a Fixture object for a Foo object, FooFactory.CreateFoo() will be invoked, and because of WithAutoProperties that object will be populated with data created by AutoFixture.

How to store immutable arrays in a variable stored property in Swift?

I would like my class to have a stored property that can be assigned immutable arrays. If I do this:
class MyClass{
var myItems:[String]
}
I can assign different arrays to my property, but the arrays will be mutable. If I do this:
class MyClass{
let myItems:[String]
}
My array is immutable, but I can't ever change what's assigned to it. Is there any way to have my cake not mutate it too?
The best I've come up with is creating a wrapper around the array, then using that type for the property, like so:
class MyClass{
struct ImmutableWrapper{
let array:[String]
}
var myItems:ImmutableWrapper
}
…which is not exactly elegant.
I'd propose a slightly more concise solution than #matt's excellent answer, which again takes advantage of access modifiers. Instead of specifying a separate private variable, and exposing a public/internal computed variable that only provides a getter, you can let Swift do this for you by using private(set):
class MyClass {
private(set) var myItems = [String]()
}
This specifies that the setter should be private to the current file scope. The getter retains the default access level (public/internal) so outside classes can still retrieve a copy of myItems (a copy since arrays are structs, so are passed by value*).
But you might then think you can just call a mutating method like append() on myItems, and in doing so modify it from outside the class (after all, we're getting var myItems, not let myItems). But Swift is smart enough to recognise that the array should be immutable from outside MyClass:
let object = MyClass()
object.myItems.append("change me")
// ^ ~~~~~~
// Immutable value of type '[(String)]' only has mutating members named 'append'
So this achieves a very similar effect to the old Objective-C paradigm of maintaining a private NSMutableArray, and exposing a public readonly NSArray that creates an immutable copy of the private array when called. Much more elegant though, don't you think?
*In actual fact Swift is really smart with passing by value, and may not even make a copy of the array until the point it is modified, and even then may only keep track of the changes (internally). This means you can assign an array with many thousands of items without incurring a massive performance penalty.
The question is oddly posed, since your first myItems is not an array of various arrays, it's just an array of Strings. However, I'll try to discuss the matter in a more general way.
Swift does not distinguish mutable from immutable arrays in the way Cocoa NSArray does. But why do you need this? Cocoa needs it because an NSArray is a class, so if it were mutable, it could be changed behind MyClass's back. But in Swift, Array is a value type, so that can't happen.
So what's the problem you are really trying to solve? You should ask yourself what contract you are trying to get outside objects to fulfill, and try to write that contract into the structure of MyClass. Your array of structs is a perfectly reasonable approach. I think, though, that what you're after here might actually be privacy, not immutability. For example, I might say this:
class MyClass{
private var myItemsHidden = [String]()
var myItems:[String] {
get {
return myItemsHidden
}
set {
myItemsHidden = newValue
}
}
}
Now, assuming MyClass is alone in its own file (because private in Swift means private to a file), myItemsHidden can be manipulated in any way you like from inside MyClass, so presumably MyClass knows not to mutate any subarrays or whatever it is you are trying to prevent. It is up to MyClass what it allows itself to do with myItemsHidden.
But from outside MyClass, myItemsHidden does not exist; there is only myItems, and the only thing anyone can do to it is get it and set it. (If they get it and change it, the original is unaffected. They cannot mutate the original.) If your purpose is to prevent anyone from outside setting myItems at all, delete the setter function:
class MyClass{
private var myItemsHidden = [String]()
var myItems:[String] {
get {
return myItemsHidden
}
}
}
Now myItems is merely a dispensed (vended) array and no more.
If the idea is that other classes should be allowed to add new arrays to an array of arrays, you could add a MyClass method that lets them do that. In other words, now that this thing is private, it is up to you what kind of access you give others to it. MyClass becomes the gatekeeper for what other classes can do with this value, because the value itself is hidden behind the private wall.
You can probably try NSArray. The array itself is immutable and the variable can be assigned again.
class MyClass{
var myItems:NSArray
}

Scala: Use case for Array.toArray?

Scala.Array includes a function toArray, as an implicit import from ArrayOps.
Are there any use cases for Array.toArray or will it always return a copy of the object?
ArrayOps inherits toArray from GenTraversableOnce (and a default implementation is provided in TraversableOnce)
In case of an Array it's pointless, but the method is there for all the other subclasses of GenTraversableOnce, like Map, List, Set and many others.
Analogously, Map inherits a pointless toMap method, List a toList, Set a toSet and so on.
In the specific case of toArray, the default implemention provided in the TraversableOnce trait is overridden by ArrayOps.
Calling toArray on an Array will return a new one only if the runtime class of the destination type is different, otherwise it will just cast the Array to the appropriate type and return the same instance.
So, generally speaking, calling toArray on an instance of Array is useless, although not significantly expensive.

CObject, CStringArray and error C2248

class MyClass : public CObject
{
public:
MyClass();
private:
CStringArray m_myArray;
};
causes error c2248
What's wrong with this ?
I think it's related to the fact that CStringArray and MyClass both derive from CObject.
Legacy class derived from CObject currently uses CustomArray it just seems wrong to me so I would like to replace it by CStringArray.
Microsoft compiler error C2248 means "Members of a derived class cannot access private members of a base class."
I can only assume you're trying to directly reference MyClass::m_myArray from somewhere in your code, without using a public accessor function.
Update
The real answer is that the problem is caused by the copy-constructor for MyClass, attempting to copy m_myArray, but it can't, because CObject derived classes aren't copyable by default. The solution would be to write a copy constructor yourself, and rather than attempt to copy the array, copy the contents one at a time, from the source array to the destination array. Either that or use std::vector (which you should be doing anyway, as MFC containers are horrible).
You are trying to access some private member of CObject. Since both your MyClass and CStringArray derive from CObject, without more context it is impossible to know the exact problem.
The only idea that comes to mind, basically because I've fallen in the trap many times, is that CObject's copy constructor is private, so if you are trying to copy either the CStringArray or your own class, explicit or implicitly, you'll get the error.
UPDATE:
I've just taken a look at CObject's declaration and the assignment operator, too, is private. Everything else is either public or protected.
Error C2248 says "Members of a derived class cannot access private members of a base class."
CStringArray class dosn't expose Copy constructor and assignment operator, look in code for such places and replace the code with elemenet by elemnet copy.

C# - Pass a struct to a form by reference and return value?

I have a struct:
struct Order
{
public string orderNumber;
public string orderDetail;
}
I then assign some values in Form1 and try to pass them by reference (ref) to Form2:
(Form1)
Order order = new Order();
order.orderNumber = "1234";
order.orderDetail = "Widgets";
Form2 frm2 = new Form2(ref order);
Is it possible to store the values in Form2 so that when Form2 is completed processing the values it will return the updated struct values to Form1?
In this scenario there would be a button that would close the form after validating the data.
One pattern that's sometimes useful is to define a class something like:
class Holder<T> {public T value;}
Such a class makes it possible to pass and mutate value types with code that requires reference types. Using such an approach, a routine which accepted a structure by reference and was supposed to pop up a modal dialog and fill in the structure from it, could create a Holder<thatStructType>, pass that to the form, and then copy the data from that Holder back to the passed-in reference. While in your particular scenario, it may be better to have the data-holding thing simply be a class, structures have the advantage that one can know that no outstanding references to them exist; if a routine declares a structure and passes it by reference to some outside code, then once that code returns the values in that structure won't change unless or until the routine writes them itself or passes the structure by reference to some other code. By contrast, if a routine exposes a class reference to outside code, there's no telling what that code may do with it.
Incidentally, the Holder class is also useful in a number of other scenarios. For example, if one has a Dictionary<String, Holder<Integer>> myDict, one may use Threading.Interlocked.Increment(myDict(myKey).Value)) to perform a thread-safe increment of the indicated item, much more efficiently than would be possible with a Dictionary<String, Integer>.
What I think you're asking is if Form2 can store a reference to the order structure that was passed in the constructor. The answer is no. If you want to store references, use a reference type (a class).

Resources