views:

104

answers:

4

Hi all. I currently have a function that looks like this:

public void AnimateLayoutTransform(object ControlToAnimate)
{
//Does some stuff
}

I use this function in a lot of different projects, so I want it to be very reusable. So for now I have it in a .cs file, enclosed in a namespace and a class:

namespace LayoutTransformAnimation
{
    public class LayoutAnims
    {
        public void AnimateLayoutTransform(object ControlToAnimate)
        {
            //Do stuff
        }
    }
}

The problem with this is that to use this one function in a given project, I have to do something like

new LayoutTransformAnimation.LayoutAnims().AnimateLayoutTransform(mygrid);

Which just seems like a lot of work to reuse a single function. Is there any way to, at the very least, use the function without creating a new instance of the class? Similar to how we can Double.Parse() without creating a new double?

+5  A: 

You could make it into a static method.

MSDN Example

chotchki
might be best to include a sample static method/class?
Mauro
+2  A: 
namespace LayoutTransformAnimation 
{ 
    public class LayoutAnims 
    { 
        public static void AnimateLayoutTransform(object ControlToAnimate) 
    { 
        //Do stuff 
    } 
} 

}

LayoutTransformAnimation.LayoutAnims.AnimateLayoutTransform(something);
Richard Friend
+9  A: 

One option is to make it a normal static method. An alternative - if you're using C# 3.0 or higher - is to make it an extension method:

public static class AnimationExtensions
{
    public static void AnimateLayoutTransform(this object controlToAnimate)
    {
        // Code
    }
}

Then you can just write:

mygrid.AnimateLayoutTransform();

Can you specify the type of the control to animate any more precisely than "Object"? That would be nicer... for example, can you only really animate instances of UIElement? Maybe not... but if you can be more specific, it would be a good idea.

Jon Skeet
+2  A: 

I find it useful to have a static util class with static methods in them which can be used within the project namespace.

public static class YourUtilsClass
{

    public static Void YourMethod()
    {
        //do your stuff
    }   

}

You can call it like so: YourUtilsClass.YourMethod()

VoodooChild