Adam S
Adam S

Reputation: 9245

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?

Upvotes: 3

Views: 3097

Answers (4)

VoodooChild
VoodooChild

Reputation: 9784

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502826

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.

Upvotes: 10

Richard Friend
Richard Friend

Reputation: 16018

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

}

LayoutTransformAnimation.LayoutAnims.AnimateLayoutTransform(something);

Upvotes: 2

chotchki
chotchki

Reputation: 4343

You could make it into a static method.

MSDN Example

Upvotes: 5

Related Questions