In the static method, the method use compile-time or early binding. For this reason, we can access the static method without creating an instance. In a non-static method, the method use runtime or dynamic binding. So that we cannot access a non-static method without creating an instance.
A static method is a class method and belongs to the class itself. This means you do not need an instance in order to use a static method. A non-static method is an instance method and belongs to each object that is generated from the class.
In static class, you are not allowed to create objects. In non-static class, you are allowed to create objects using new keyword. The data members of static class can be directly accessed by its class name. The data members of non-static class is not directly accessed by its class name.
We can't declare outer (top level) class as static because the static keyword is meant for providing memory and executing logic without creating Objects, a class does not have a value logic directly, so the static keyword is not allowed for outer class.
I was wondering what are the general benefits (or drawbacks) of using a non-static class with a static method versus a static class with the same static method, other than the fact that I cannot use static methods from a non-static class as extension methods.
For example:
class NonStaticClass
{
public static string GetData()
{
return "This was invoked from a non-static class.";
}
}
Versus this:
static class StaticClass
{
public static string GetData()
{
return "This was invoked from a static class.";
}
}
What are the performance/memory implications of using one method over another?
NOTE: Suppose that I do not need to instantiate the class. My use-case scenario is limited to something like this:
Console.WriteLine(NonStaticClass.GetData());
Console.WriteLine(StaticClass.GetData());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With