Static method vs instance method

M

MuZZy

Hi,

I'm retouching some utility classes used everywhere across our app, and
there are certain methods used everywhere and pretty frequently. I'm
changing them from instance methods to static ones, so to use them you
don't need to create an instance of that utility class.

So my question is - is there any difference/danger of using a static
method vs instance method.

Example:

//--------- CODE ---------------
class CUtil
{
public string GetColumn(string s)
{
string[] ss = s.Split('.');
if (ss.Length > 1)
return ss[1];
else if (ss.Length > 0)
return ss[0];
else return String.Empty;
}
}
//------ VERSUS: -------------
class CUtil
{
public static string GetColumn(string s)
{
... same implementation ...
}
}
// -------- END OF CODE -------


Any possible memory/performance issues?

Thank you,
MuZZy
 
J

Jon Skeet [C# MVP]

MuZZy said:
I'm retouching some utility classes used everywhere across our app, and
there are certain methods used everywhere and pretty frequently. I'm
changing them from instance methods to static ones, so to use them you
don't need to create an instance of that utility class.

So my question is - is there any difference/danger of using a static
method vs instance method.

If they're stateless, there's no danger. It does mean you can't make
them virtual and override them in a derived class, but that doesn't
sound like it's an issue here.
 
M

MuZZy

Jon said:
If they're stateless, there's no danger. It does mean you can't make
them virtual and override them in a derived class, but that doesn't
sound like it's an issue here.

Yeap, it's just a helper class of small functions like the one in the
sample, this class will not be inherited and will not have any
non-static members; i will actually hide the constructor as well so no
brick-head will try to screw with it:)

MuZZy
 
A

Anders Borum

Hello!

Mind you that the C# 2.0 language (if this is your platform) allows classes
to be marked with the "static" modifoer. This forces the compiler to allow
only static members - which is probably what you're looking for.

This btw. also relieves you from creating a private constructor (or should
you need to initialize data on first request, you could provide a static
constructor).

public static class Utility
{
public static void DoSomething() { .. }
}

I think such situations as the one you're referring to are prime candidates
for "static" promotings.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top