-8

May someone explain me the difference between these two classes?

I am always using the first one, but I the the second one often as well.

public static class Test
{
    public static void Method()
    {

    }
}


public class Test
{
    public static void Method()
    {

    }
}
simonc
  • 41,632
  • 12
  • 85
  • 103
SharpNoiZy
  • 1,099
  • 2
  • 11
  • 22
  • 2
    `static` classes can only have static methods, fields and properties. So in your first example class `Test` may only have static members and in the second one both, static and instance members. – Leri Feb 14 '13 at 09:12
  • 4
    [What query do you have that is not answered in the documentation](http://msdn.microsoft.com/en-us/library/98f28cdx.aspx)? – ta.speot.is Feb 14 '13 at 09:12
  • 6
    Did you do any research? Come oooonnnn..! – Soner Gönül Feb 14 '13 at 09:12
  • http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.80%29.aspx should help – AurA Feb 14 '13 at 09:13
  • instead of typing a question here you must have typed in google thousands of results will be available – NetStarter Feb 14 '13 at 09:30
  • @Christian, your question is an exact duplicate. To prevent downvotes always do a relevant search on SO first. – nawfal Feb 14 '13 at 11:07

3 Answers3

8

The first class is static, which means:

  • You can't use it as a type argument
  • You can't use it as a variable type
  • It will have no instance constructors (whereas your non-static class implicitly has a public parameterless constructor)
  • It will be implicitly abstract and sealed (even though that combination can't be static
  • It cannot contain any non-static members
  • It can contain extension methods (if it's a top level, non-generic static class)

Basically for utility classes which are only meant to contain static members, using a static class expresses that intent clearly and lets the compiler help you enforce that usage.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

A static class cannot ever be instantiated, and can only have static members. In your second code snippet, you could create create an instance of Test, but not in the first.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

Static class can only contain static member with is the first one. Second one is non static class and can contain both static and not static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded, reference.

Adil
  • 146,340
  • 25
  • 209
  • 204