Easiest way to re-use a function without instantiation a new class

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?

Answers


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.


You could make it into a static method.

MSDN Example


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()


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

}

LayoutTransformAnimation.LayoutAnims.AnimateLayoutTransform(something);

Need Your Help

Using strings to set folder path VB.Net

vb.net visual-studio-2010

I have been asked by my colleagues to write a program that allows us to enter a job number and it will take us to the proper folder within our database (SolidWorks EPDM). The structure of the fold...

How to get URL within content with JQuery or Javascript

javascript jquery cordova

I am building an Application with PhoneGap which has a lot of URLs that are updated on a regular basis. Therefore I need to code a way to capture the URL and redirect it to the external browser. The