ChevCast
ChevCast

Reputation: 59193

What is the difference between putting a static method in a static class and putting an instance method in a static class?

What is the difference between these two classes?

public static class MyClass
{
    public static string SayHello()
    {
        return "Hello";
    }
}

public static class MyClass
{
    public string SayHello()
    {
        return "Hello";
    }
}

Is the second SayHello method also static since it is on a static class? If so, is there any reason to include the static keyword on methods when they are defined in a static class?

Upvotes: 0

Views: 216

Answers (4)

Dustin Davis
Dustin Davis

Reputation: 14585

static classes are sealed, cannot contain instance members. Static methods are a part of the Type not the instance and static methods cannot access instance members. Static methods cannot be virtual but can be overloaded. Static methods also emit 'call' IL opcodes instead of 'callvirt'.

static classes have a static constructor that takes no arguments and it gets called before the first use of the type.

Upvotes: 0

Chris W
Chris W

Reputation: 1802

Static classes cannot be instantiated, so your second piece of code is not compilable. A non-static method can only be accessed in an instantiated class.

Upvotes: 1

user849425
user849425

Reputation:

"...Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created."

http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx

Upvotes: 0

Jalal Said
Jalal Said

Reputation: 16162

The second example is not even possible to do in c#, you will get compile time error:

'SayHello': cannot declare instance members in a static class

So you must declare members of static calss with static keyword.

Upvotes: 8

Related Questions