tags:

views:

54

answers:

3

Hi all,

I want to customize a object's behavior before the object is created. I think maybe add some hooks in the object constructor and do the change there would be a choice. Is there any way to do so in .net? Thanks a lot in advance!

EDIT:

Here is a example:

Assume we have a class Kid which use Perform method to get credit in the class.

public class Kid
{
    public void Perform() { ... }
}

And the School conduct to lectures:

public class School
{
    public void Chemistry() {
        // The school have a good chemistry teacher, so every kid study well
        // Kid.Perform() is modified to reflect that 
        Kid tom = new Kid();
        tom.Perform();
    }

    public void Biology() {
        //This class is boring, everyone will nap in 5~10 min
        // Kid.Perform() use a random number to simulate how 
        //long this kid can hold it.
        Kid tom = new Kid(); tom.Perform();
        Kid jerry = new Kid(); jerry.Perform();
    }
}

We want every kid perform in the same way and I do not want:

  1. Change class Kid because it is generated from a 3rd party tool and widely used somewhere else.
  2. Use inheritance.
A: 

You would simply add logic to the object's constructor. If you are referring to the process of hooking into the allocation of memory etc then that's not available in .NET.

public class MyClass
{
    public MyClass()
    {
        // Constructor logic here...
    }

    public MyClass(string name)
    {
         // Overloaded constructor logic here...
    }
}
Adam
The object is generated by a 3rd party tool. Wrap the class can solve my problem but means lots of refactoring works which I'm not so satisfied. Is there anyway else? Thanks!
Roy
Well, along the same vain you can use an extension method to provide an `Initialize` method, but this would be functionally similar to wrapping it.
Adam
+2  A: 

In your case you would have to add your logic after calling the constructor. You could write a factory method which does this; replacing new SpecialObject() with MyExtendedSpecialObject.Create() shouldn't be too difficult.

public static class MyExtendedSpecialObject
{
    public static SpecialObject Create()
    {
        var newObject = new SpecialObject();

        // Do something with newObject

        return newObject;
    }
}
Daniel Rose
Yes, lots of people use factory method. But I'm modifying legacy code. and an "injection" way is preferred.
Roy
@Roy: A simple search and replace shouldn't be too difficult. AFAIK such injection as you want isn't possible (except perhaps through something like aspect-oriented programming?).
Daniel Rose
A: 

You can use System.Activator to create the instances. You can also 'hook' into the activator and perform your checks.

MaLio