Sobes.tech
Junior — Middle

What is the difference between a non-static class and a static class in programming?

sobes.tech AI

Answer from AI

A static class in programming is a class that cannot be instantiated and contains only static members (methods, properties). It is used to group functions and data that do not depend on a specific object.

A non-static class is a regular class, instances of which can be created. It can contain both static and non-static members, and the state of each object is stored separately.

Main differences:

  • Creating instances:

    • A static class cannot be created (new StaticClass() will cause an error).
    • A non-static class can be instantiated and used to create objects.
  • Class members:

    • In a static class, all members must be static.
    • In a non-static class, there can be both static and non-static members.
  • Usage:

    • A static class is suitable for utility functions that do not require state.
    • A non-static class is used when you need to store state and object behavior.

Example of a static class in C#:

public static class MathUtils
{
    public static int Add(int a, int b) => a + b;
}

// Usage:
int sum = MathUtils.Add(3, 4);

Example of a non-static class:

public class Person
{
    public string Name { get; set; }

    public void SayHello()
    {
        Console.WriteLine($"Hello, my name is {Name}");
    }
}

// Usage:
Person p = new Person { Name = "Alice" };
p.SayHello();
What is the difference between a non-static class and… - sobes.tech