0

In C# I have two class with one static function. First class is defined as static and another is not.

public static class TestClass1
{
    public static string TestFunc()
    {
        ....
    }
}

public class TestClass2
{
    public static string TestFunc()
    {
        ....
    }
}

I can call these functions as

TestClass1.TestFunc();
TestClass2.TestFunc();

What is the difference between these two type of usage, or is there any? (This function is called more than million times in a day. My first concern is about memory and performance)

slim
  • 40,215
  • 13
  • 94
  • 127
GorkemHalulu
  • 2,925
  • 1
  • 27
  • 25
  • 1
    The question is *not* language agnostic, as the concept of "static class" has a completely different meaning in C# and Java - let alone other languages. – Jon Skeet Jun 13 '14 at 11:46
  • With java, a class which is not nested cannot be static, see following link http://stackoverflow.com/questions/3584113/why-are-you-not-able-to-declare-a-class-as-static-in-java – shin Jun 13 '14 at 11:47
  • I have removed the Java and language-agnostic tags, since OP is using C#. – slim Jun 13 '14 at 11:50

2 Answers2

2

In the case of C#, there is no functional difference, except that only methods in static classes can be declared as an extension methods, i.e. with a this SomeType name first parameter. Which neither example attempts to do here. Other than that: they are identical.

If you aren't expecting any instances of the type to be created (i.e. it is intended to be a utility class), then you should use static class. The main point of this is that it prevents creation, subclassing, etc. Prior to static class, in old C# versions, you would have to do:

public abstract class MyType {
    private MyType() {}

    // ...methods...
}

to get something remotely comparable.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

There is no difference in using static functions from a static class or a non-static class. (Except the one mentioned by Marc Gravell)

The attribute 'static' for a class means: 'abstract sealed'. This indicates that such a class is intended to contain only static functions. I think it is considered to be a better programming style, if one writes static helper-functions into a static class.

Martin Tausch
  • 714
  • 5
  • 20