I have an application that needs to determine whether a user has made a change to an object. So, when the object is first loaded, I create a deep copy (using serialization/deserialization) and save the copy to a separate field. The copy becomes myCurrentObject, and the original becomes myOriginalObject.
Now I need to test myCurrentObject for changes, which I plan to do by comparing it to myOriginalObject. All I need is a boolean result indicating whether any changes have been made. I have already determined that a simple hashcode comparison won't work. GetHashCode() generates different results for the two objects, even when there are no changes.
I am getting ready to write a method to do a property-by-property comparison, but before I do, I thought I would check to see if there is a simpler and more reusable way to test myCurrentObject to see if it has changed from myOriginalObject.
Any suggestions? Thanks for your help.
Instead could you implement a OnPropertyChanged event on each of your properties then you could just see if the event was ever thrown. If you specifically implement INotifyPropertyChanged, you will get the added benefit that you can do WPF binding if you ever want to.
If that isn't possible, you could probably implement a solution with reflection that would traverse both objects looking for differences.
What if an event is raised when a property is changed?
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx
You can override the GetHashCode method to reflect your needs.
The hash code can only tell you that an object has definately changed, it cannot tell you that an object definately hasn't changed (because different objects can return the same hash code).
Do investigate the Object.Equals method
You could add a dirty flag that indicates any field has changed. Set the dirty flag in the property set.
public bool IsDirty { get { return m_IsDirty; } }
public string Name {
set
{
m_Name = value;
m_IsDirty = true;
}
}
I usually do these kind of test like this:
public string sodomizar(myObject object)
{
return object.prop1.ToString() + object.prop2.ToString();
}
then test:
if(sodomizar(object1)==sodomizar(object2))
{
doStuff();
}
I would consider using an abstract superclass containing two things:
a flag that declares whether 'track
changes' is on or not (default to
false)
a Dictionary instance
that contains keyed value history
... then call Base.TrackChange(string, object) in each property accessor upon which you are interested in change. Where the string passed is the name of the Property (use reflection/pull the property name from the stack trace :- means the code in each method can be precisely the same) ... and the object passed is simply the meta variable 'value'. Some careful reflection/stack trace checking might mean you can remove the string parameter on this method ... means you keep entity Class C# coding requirements to a minimum.
The flag is there because basic state initialisation of the object means that property changes (set accessor calls) may be made until the object is fully hydrated the first time.
The Dictionary is there to enable trawling the changes (auditing?) and so forth. Scale this back to a second bool if all you need is simple true/false on the 'IsDirty' question.
Something like:
public abstract Class EntityBase
{
private bool _changesAreTracking = false;
private Dictionary<string, object> _changes = null;
public EntityBase() {}
public TrackChange(string propertyName, object value)
{
if(_changesAreTracking)
{
if(_changes == null) { _changes = new Dictionary<string, object>(); }
_changes.Add(propertyName, value);
}
}
public void StartTrackChanges()
{
_changesAreTracking = true;
}
public bool HasChanged()
{
bool returnThis = false;
if(_changes != null && _changes.Keys.Count() > 0)
{
returnThis = true;
}
return returnThis;
}
public bool HasChanged(string propertyName)
{
bool returnThis = false;
if(_changes != null && _changes.Keys.Contains(propertyName))
{
returnThis = true;
}
return returnThis;
}
}
Related
I have a boolean variable, I want every change to its value to invoke a piece of code.
my current solution is the following:
bool _manualControl;
bool manualControl {
get {
return _manualControl;
}
set {
this._manualControl = value;
GlobalEventManager.ManualControlEvent?.Invoke(value);
}
}
this solution has two problems:
the value of "_manualControl" can be changed internally without invoking my piece of code, I want to prevent that.
I would prefer to avoid using two variables to get the desired behavior.
Is there any way to achieve what I want while avoiding these two specified issues?
You can set the property to be public and have a private backing field that can only be modified from within the class, which you have control of.
Or you could use an Aspect Oriented Programming framework like PostSharp, which would allow you to use an auto property and annotate it with the behaviour you desire. This would remove the need for you to have a backing field.
To me this sounds a bit like you want to solve an architectural problem, aka code smell. Why is it that you fear your field might be set outside your setter? Is it a particularly large class that a lot of people are chaning without really knowing what it is doing?
Why even have code in the setter? Like you could just redesign your code to have a method do what your setter code does and introduce that into your code flow / process.
And have a Unit Test validate your desired behavior.
If you want to:
ensure that the setter code always executes when a new value is assigned (inside and outside of the class)
avoid having two members in the class, that represent a single value
Then this can be approached by wrapping the value within a struct like one below:
struct Intercepted<T>
{
private readonly Action<T> _onChange;
private T _value;
public Intercepted(Action<T> onChange, T initialValue = default(T))
{
_onChange = onChange;
_value = initialValue;
}
public T Value
{
get
{
return _value;
}
set
{
_value = value;
_onChange?.Invoke(value);
}
}
}
In the class, ManualControl can now be represented with a single member, of type Intercepted<bool>:
public Intercepted<bool> ManualControl { get; } = new ManualControl(
onChange: newValue => {
GlobalEventManager.ManualControlEvent?.Invoke(newValue);
}
);
The value can be accessed like this:
// from within the class
if (ManualControl.Value) { ... }
// from outside
myObj.ManualControl.Value = true;
Now there is no way to change the value without triggering the setter code, both inside and outside the class.
Am I misunderstanding something about pass by reference?
SomeClass is the IObserver implementer:
bool value = false;
provider.Subscribe(new SomeClass(ref value));
while (!value)
{
provider.GetEvents() //triggers OnNext
}
In SomeClass:
public SomeClass(ref bool value)
{
this.value = value;
}
public void OnNext(object someUpdatedValue)
{
value = true;
}
Value never becomes true and the while loop never breaks. How come? Does assigning the value property of SomeClass to the reference of value not persist?
Edit: After seeing the first two responses my new question is this:
How can I achieve this kind of behavior without using static variables?
Pass by reference affects only the variable passed as the argument to the method. In your example, the value of false, which is what the variable value contained when you assigned it to this.value, is copied to the this.value field. Nothing more.
There's nothing magical in C# that will remember where that value came from and update the variable later, when the field to which its value was assigned is changed later.
Does assigning the value property of SomeClass to the reference of value not persist?
You aren't assigning "the reference of value". All that happens when you pass by-reference is that if the local variable itself is changed, then the variable that was passed is modified. When you use the value of the variable, you're only using the value, not the reference.
EDIT:
Without more context, it's impossible to say what the best way to approach this would be. But note that reference types achieve something similar to what you seem to be trying to do. For example:
class VolatileBoolWrapper
{
public bool Value { get { return _value; } }
private volatile bool _value;
public void SetValue(bool value)
{
_value = value;
}
}
VolatileBoolWrapper value = new VolatileBoolWrapper();
provider.Subscribe(new SomeClass(value));
while (!value.Value)
{
provider.GetEvents() //triggers OnNext
}
public SomeClass(VolatileBoolWrapper value)
{
this.value = value;
}
public void OnNext(object someUpdatedValue)
{
value.SetValue(true);
}
In that way, the VolatileBoolWrapper class acts as a go-between for the caller and callee.
<edit>
Note that I marked the field as volatile, and named the class Volatile... just to be safe. There's not enough context in the question for me to know what "triggers" actually means (i.e. does the same thread actually set the value, or is this something that involves interaction between threads).
If it happens that the call to OnNext() occurs within the same thread, strictly by virtue of the call to GetEvents(), then you can omit the use of volatile here (and ignore, or at least discount, my note about polling below).
</edit>
All that said, frankly: polling on a variable like this is pretty much always the wrong way to accomplish one's goals. There have always been much better approaches for things like this, but in modern C#, I would say that TaskCompletionSource is the best alternative. Like other mechanisms that came before it, it allows your waiting code to not continually use CPU time checking to see if the event has occurred; unlike them, it also provides an excellent mechanism for allowing that entire thread to continue executing, performing other work, only resuming at the await statement where you waited for the event when that event actually occurs.
The ref modifier affects the caller, not the callee. It allows you to reassign the caller's variable to "point to" a new value. For example:
bool myValue = true;
WithoutRef_YouCannotReassign(myValue);
Console.WriteLine(myValue); // myValue is still true
WithRef_YouCanReassign(ref myValue);
Console.WriteLine(myValue); // myValue is now false
void WithoutRef_YouCannotReassign(bool value) {
value = false;
}
void WithRef_YouCanReassign(bool value) {
value = false;
}
You're trying to pass out a reference to SomeClass.value. Normally, that'd work great by just swapping your assignment (remember, you're changing the caller's variable to point at something else)
public SomeClass(ref bool value)
{
value = this.value;
}
But, you've got another problem. Since a bool is immutable - even though your caller is pointing at the right value, you point your own value to something else later by overwriting it:
public void OnNext(object someUpdatedValue)
{
value = true; // value is now pointing somewhere else! the caller never got a reference to the somewhere else!
}
So, now, you actually need a wrapper to avoid having to overwrite SomeClass.value after you passed a reference out to it:
struct MyBoolWrapper
{
public bool Value { get; set; }
}
public SomeClass(ref MyBoolWrapper value)
{
value = this.value;
}
public void OnNext(object someUpdatedValue)
{
value.Value = true;
}
Now, this won't work because it's a struct (like bool is). structs are value types, and so the value of it gets copied back. When you change SomeClass.value, you're changing a different copy again! (This is one reason we tend to prefer immutable structs, like bool is).
So, let's change this to a class:
class MyBoolWrapper
{
public bool Value { get; set; }
}
This will work as expected since you end up passing back a reference to MyBoolWrapper (which doesn't change).
So, now we're working - but let's look at some cleanup. It seems a little silly for our caller to have to new a MyBoolWrapper just so that we can point it to something else. Let's change that:
MyBoolWrapper wrapper = null;
provider.Subscribe(new SomeClass(ref wrapper));
Well, now it seems silly that we set it to null. Since SomeClass is providing all the info, let's just make it an out (which, essentially, works the same as ref just without requiring it to be initialized):
MyBoolWrapper wrapper;;
provider.Subscribe(new SomeClass(out wrapper));
Of course, now it's not even clear why we can't just hold a reference to SomeClass directly, and get rid of this whole out/ref dance:
SomeClass someClass = new SomeClass();
provider.Subscribe(someClass);
while (!someClass.Value) {
provider.GetEvents();
}
class SomeClass {
public Value { get; private set; }
public void OnNext(object someUpdatedValue)
{
Value = true;
}
}
There - that's simpler. Since the caller has a reference to our instance that changes it's state (without changing it's identity), we don't have to worry about all of that method calling by-ref/by-val struct vs class mumbo-jumbo.
The C# "readonly" keyword is a modifier that when a field declaration includes it, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
Now suppose I do want this "assign value once" constraint, but I would rather allow the assignment be done outside of constructors, a lazy/late evaluation/initialization maybe.
How could I do that? and is it possible to do it in a nice way, for example, is it possible to write some attribute to describe this?
If I understand your question correctly, it sounds like you just want to set a field's value once (the first time), and not allow it to be set after that. If that is so, then all the previous posts about using Lazy (and related) may be useful. But if you don't want to use those suggestions, perhaps you can do something like this:
public class SetOnce<T>
{
private T mySetOnceField;
private bool isSet;
// used to determine if the value for
// this SetOnce object has already been set.
public bool IsSet
{
get { return isSet; }
}
// return true if this is the initial set,
// return false if this is after the initial set.
// alternatively, you could make it be a void method
// which would throw an exception upon any invocation after the first.
public bool SetValue(T value)
{
// or you can make thread-safe with a lock..
if (IsSet)
{
return false; // or throw exception.
}
else
{
mySetOnceField = value;
return isSet = true;
}
}
public T GetValue()
{
// returns default value of T if not set.
// Or, check if not IsSet, throw exception.
return mySetOnceField;
}
} // end SetOnce
public class MyClass
{
private SetOnce<int> myReadonlyField = new SetOnce<int>();
public void DoSomething(int number)
{
// say this is where u want to FIRST set ur 'field'...
// u could check if it's been set before by it's return value (or catching the exception).
if (myReadOnlyField.SetValue(number))
{
// we just now initialized it for the first time...
// u could use the value: int myNumber = myReadOnlyField.GetValue();
}
else
{
// field has already been set before...
}
} // end DoSomething
} // end MyClass
Now suppose I do want this "assign value once" constraint, but I would rather allow the assignment be done outside of constructors
Note that lazy initialization is complicated, so for all of these answers you should be careful if you have multiple threads trying to access your object.
If you want to do this inside the class
You can use the C# 4.0 built-in lazy initialization features:
http://msdn.microsoft.com/en-us/library/dd997286.aspx
http://msdn.microsoft.com/en-us/library/dd642331.aspx
http://sankarsan.wordpress.com/2009/10/04/laziness-in-c-4-0-lazyt/
Or for older versions of C#, just supply a get method, and check if you're already initialized by using a backing field:
public string SomeValue
{
get
{
// Note: Not thread safe...
if(someValue == null)
{
someValue = InitializeSomeValue(); // Todo: Implement
}
return someValue;
}
}
If you want to do this outside the class
You want Popsicle Immutability:
http://blogs.msdn.com/b/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx
http://msdn.microsoft.com/en-us/library/ms750509.aspx
http://csharpindepth.com/Talks.aspx (search for "popsicle immutability" and you'll find a video)
Basically:
You make the whole class writable, but add a Freeze method.
Once this freeze method is called, if users try to call setters or mutator methods on your class, you throw a ModifyFrozenObjectException.
You probably want a way for external classes to determine if your class IsFrozen.
BTW, I made up these names just now. My selections are admittedly poor, but there is no generically followed convention for this yet.
For now I'd recommend you create an IFreezable interface, and possibly related exceptions, so you don't have to depend on the WPF implementation. Something like:
public interface IFreezable
{
void Freeze();
bool IsFrozen { get; }
}
You can use the Lazy<T> class:
private readonly Lazy<Foo> _foo = new Lazy<Foo>(GetFoo);
public Foo Foo
{
get { return _foo.Value; }
}
private static Foo GetFoo()
{
// somehow create a Foo...
}
GetFoo will only be called the first time you call the Foo property.
This is know as the "once" feature in Eiffel. It is a major oversight in C#. The new Lazy type is a poor substitute since it is not interchangeable with its non-lazy version but instead requires you to access the contained value through its Value property. Consequently, I rarely use it. Noise is one of the biggest problems with C# code. Ideally, one wants something like this...
public once Type PropertyName { get { /* generate and return value */ } }
as oppose to the current best practice...
Type _PropertyName; //where type is a class or nullable structure
public Type PropertyName
{
get
{
if (_PropertyName == null)
_PropertyName = /* generate and return value */
return _PropertyName
}
}
How can I get a hash of a delegate function in C#. I want to be able to tell if different delegates are being sent into my function. My code looks something like this:
public string GetContent(Func<string, bool> isValid)
{
// Do some work
SomeFunctionToHashAFunction(isValid)
}
I would use .GetHashCode() but the .NET framework doesn't guarantee that these will be unique.
EDIT
I have some cached content that I'm validating, but I only want to validate it once. However, if the validation function changes, then I'll need to re-validate the cached content. I'm not sure if the ObjectIdGenerator will work in this instance since I need to identify if two anonymous functions have the same implementation.
By definition, a hash is not guaranteed to be unique, so hashing is not what you want.
Instead, you want to determine whether the instance of the delegate has been "seen" before. To do this, you could use ObjectIdGenerator:
private static readonly ObjectIdGenerator oidg = new ObjectIdGenerator();
public string GetContent(Func<string, bool> isValid)
{
bool firstTime;
oidg.GetId(isValid, out firstTime);
if (!firstTime)
{
...
}
}
However, even with this technique there are some pitfalls to be aware of:
ObjectIdGenerator stores a reference to each object you pass to it
Delegates to the same function are distinct objects, and would therefore return different IDs
Perhaps if you explain what it is you're trying to achieve, there may be a much better way to go about it.
EDIT: Given your updated requirements, I would just define the validation delegate as a property. If the property changes, you know you need to re-validate. GetContent() would therefore not need any parameters:
public Func<string, bool> IsValidHandler
{
get { return this.isValidHandler; }
set
{
this.isValidHandler = value;
this.requiresValidation = true;
}
}
public string GetContent()
{
if (this.requiresValidation && this.isValidHandler != null)
{
// do validation
this.requiresValidation = false;
}
// return content
}
You might even simplify further and do the validation when the IsValidHandler property is set (not in the GetContent method).
There is no (at least non completely hacky) way to hash anonymous function/delegate. Even if function implementation is the same, it might be a closure - so validation outcome might be different based on the context state. Consider this example:
public class Validator
{
public string SomeState { get; set; }
public Validator(string someState)
{
SomeState = someState;
}
public bool IsValid(string input)
{
return input == SomeState;
}
}
// assume your 'input' being validated is "foo"
GetContent((new Validator("foo")).IsValid); // IsValid returns true
GetContent((new Validator("bar")).IsValid); // IsValid returns false
So the only way be sure of whether the validation function is unique would be to have caller define uniqueness of validation implementation and have the caller pass that information to you. You would have to switch to using some kind of validator interface, something along these lines:
//
// Your code
//
public string GetContent(IValidator validator,
IEqualityComparer<IValidator> comparer)
{
// for tracking used validators, use instance
// of 'new HashSet<IValidator>(comparer)'
// this will give you a hashset of unique validators
}
public interface IValidator
{
bool IsValid(string input);
}
//
// Your callers code
//
public class Validator : IValidator
{
// same as Validator class code above
}
public class ValidatorEqualityComparer : IEqualityComparer<Validator>
{
public bool Equals(Validator v1, Validator v2)
{
return GetHashCode(v1) == GetHashCode(v2);
}
public int GetHashCode(Validator v)
{
int hCode = GetMyStringHash(v.GetType().GUID.ToString() + v.SomeState);
// as for GetMyStringHash() implementation for this example,
// you can use some simple string hashing:
// http://www.techlicity.com/blog/dotnet-hash-algorithms.html
return hCode;
}
}
Then you can call your method like this:
GetContent(new Validator("foo"), new ValidatorEqualityComparer());
So the most important part to note here, is that when implementing ValidatorEqualityComparer.GetHashCode() you use validator object state (object value based) hashing. Only this will ensure true uniqueness of validation logic.
Hashes are not intended to be unique. In terms of equality, the only thing you can use them for is to determine whether two objects are not the same. As such, they can be used as a quick first test; if the hashes are different, there is no use to do any further comparisons; the two objects are not the same. If the hashes do match, the objects may be the same, but they may also not be, so you need to perform some deeper analysis in order to determine equality.
Why not just use HashSet to store delegates? Then you can just use .Contains(isValid) to check if the delegate has been given already.
In other words, someone already solved this problem. No reason for you to also solve it.
GetHashCode WILL be unique between different object to a factor of 2^122, that seems pretty safe.
Otherwise, create a class, add a func property, and a bool that is, HasBeenSeen.
Should get the job done.
So I got into a friendly argument with a co-worker over a piece of code:
public sealed class NewObject
{
private string _stuff = string.Empty;
public string Stuff
{
get { return GetAllStuff(); }
}
private string GetAllStuff()
{
//Heavy string manipulation of _stuff
}
public NewObject(string stuffToStartWith)
{
_stuff = stuffToStartWith;
}
public static NewObject operator +(NewObject obj1, NewObject obj2)
{
if (obj1 == null)
throw new ArgumentNullException();
if (obj2 == null)
throw new ArgumentNullException();
NewObject result = new NewObject(string.Empty);
result._stuff = String.Concat(obj1._stuff, obj2._stuff);
return result;
}
}
The argument was over the operator override. My co-worker feels that it's not best programming practice to set values of private fields anywhere but the constructor. The solution proposed by my co-worker was to refactor the name of the Stuff property to AllStuff and add a property, Stuff, that has a get AND set accessor and use the new Stuff property in the operator override. Making it look like this:
public static NewObject operator +(NewObject obj1, NewObject obj2)
{
if (obj1 == null)
throw new ArgumentNullException();
if (obj2 == null)
throw new ArgumentNullException();
NewObject result = new NewObject(string.Empty);
result.Stuff = String.Concat(obj1.Stuff, obj2.Stuff);
return result;
}
I disagree. I feel the first way is better since it keeps the property read-only outside the class. My question is, which way is the best practice for object-oriented design?
You could give yourself a private set on the property (which would retain visibility or lack thereof while allowing you to use property syntax), but that doesn't really address the point.
Within the class, I say that variables are fair game. Anywhere outside, including inherited classes, should get and set the property, but within the declaring class I say it's OK to assign the private member.
The general issue has to do with a contract policy.
The notion of a (public set) property is that when it is called, other actions may be taken in addition to the semantic notion of changing state. For example, calling a setter may fire events, trigger a peripheral device and so on.
Your coworker is saying that by not using the property, you're side-stepping the contract and no events will be fired.
So here's you should do from your coworker's point of view:
this.Prop = CalculateSomeValue();
if (this.Prop < kPropMin) {
this.Prop = kPropMin;
}
else if (this.Prop > kPropMax * 2) {
this.Prop = kPropMax * 2;
}
this.Prop = this.Prop / 2;
Now, this is a contrived case, but I've just hit a possible heavyweight property up to three times in the get and up to three times in the set, and one of those might be illegal (setting to kHighLimit / 2). I can work around this by using a local and calling the set precisely once at the end. I'd rather just mess with the field, though.
I think a better approach is to take it pragmatically: use the property inside your class if and only if you want to invoke all the side-effects of a set or a get, otherwise obey the spirit of the property instead.
-- clarification --
By obey the spirit of the property, let's say that my set property looks like this:
bool PropValueOutOfRange(int val) {
return val < kPropMin || val > kPropMax;
}
public int Prop {
set {
if (PropValueOutOfRange(value))
throw new ArgumentOutOfRangeException("value");
if (PropValueConflictsWithInternalState(value))
throw new ArgumentException("value");
_prop = value;
NotifyPeriperalOfPropChange(_prop);
FirePropChangedEvent(/* whatever args might be needed */);
}
}
In this I've factored out a lot of the grungy details, but that lets me reuse them. So now I feel confident in touching the private field _prop because I have the same infrastructure for making sure that I keep it in range and to notify the peripheral and fire the event.
This lets me write this code:
_prop = CalculateSomeValue();
if (_prop < kPropMin)
_prop = kPropMin;
else if (_prop > kPropMax * 2)
_prop = kPropMax;
_prop /= 2;
NotifyPeripheralOfPropChange();
FirePropChangedEvent();
I'm using the same tools as those used to build the property so I'm working within the spirit of the property. I maintain correct range (but don't throw - I know better, I'm the implementer), hit the peripheral and fire events, and I do it thoughtfully, readably, and efficiently - not indiscriminately.
You're right
err... to elaborate, your private variables are yours to do as you please. If someone does an operation on you that changes the value of the object, (especially something like +), theres nothing wrong with modifying the value outside of the constructor. Thats the whole point of them being private.
Unless you want it immutable...
Update
The more i think about it, the more I believe your co-worker is confusing 'private' variables with 'constant' ones - or perhaps merging the two concepts. There is no reason that private variables have to remain the same throughout the life of the object, which is what your friend seems to be implying. const is for unchanging, private is for the object only, they are two very distinct patterns.
Update2
Also, his design falls apart if suddenly your object has more than just a string - and the variables are intertwined (think of a string object, that has a char* and a len, and must be maintained together). The last thing you want is for the user to have to deal with internal variables of an object. Let the object be an object and maintain its own internal values and present a single entity to the user.
I don't see what the benefit of his approach would be.
I personaly prefer to have no fields at all, hence I use auto-implemented private properties instead of private fields and public-get private-set properties if want to have public read-only properties.
If I have to add code to the property, I still only use the field inside of the property accessors and use the getters and setters everywhere else including the constructor.
I have to use fields, too, if I need readonly fields, but C# 4.0 will introduce read-only properties.
Further I would have avoided the whole problem by using the following code.
public static NewObject operator +(NewObject obj1, NewObject obj2)
{
return new NewObject(String.Concat(obj1.Stuff, obj2.Stuff));
}
My prefered implementation would be something like this.
public sealed class NewObject
{
private String Stuff { get; set; }
// Use a method instead of a property because the operation is heavy.
public String GetAllStuff()
{
// Heavy string manipulation of this.Stuff.
return this.Stuff;
}
// Or lets use a property because this.GetAllStuff() is not to heavy.
public String AllStuff
{
get { return this.GetAllStuff(); }
}
public NewObject(String stuffToStartWith)
{
this.Stuff = stuffToStartWith;
}
public static NewObject operator +(NewObject obj1, NewObject obj2)
{
// Error handling goes here.
return new NewObject(String.Concat(obj1.Stuff, obj2.Stuff);
}
}