Search code examples
vb.netoperator-overloading

Does implementing and calling IsTrue operator create copy of the class instance


As operators must be shared and arguments are passed ByVal, will IsTrue(MyClass) operator create a copy? The class contains an array. I want to be able to do this:

If myClass1 Then
...

But without IsTrue procedure creating a copy.


Solution

  • This is really just a question about reference types and value types. When you pass a variable as an argument to a method parameter declared ByVal, a copy is made of the contents of that variable. If the variable is a value type then the variable contains the object so the object is copied. If the variable is a reference type then the variable contains a reference to the object so the reference is copied, not the object. If your type is a class then it's a reference type so clearly no object will be copied. It should be pretty clear that potentially large objects wouldn't be copied every time an operator was used.

    This is fundamental .NET programming. You should spend a bit of time researching and learning about value types, reference types, passing by value and passing by reference.