Static method vs instance method

  • Thread starter Thread starter MuZZy
  • Start date Start date
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
 
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.
 
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
 
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.
 
Back
Top