When should I prefer either a static or a normal class? Or: what is the difference between them?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace staticmethodlar
{
class Program
{
static void Main(string[] args)
{
SinifA.method1();
}
}
static class SinifA
{
public static void method1()
{
Console.WriteLine("Deneme1");
}
}
public static class SinifB
{
public static void method2()
{
Console.WriteLine("Deneme2");
}
}
public class sinifC
{
public void method3()
{
Console.WriteLine("Deneme3");
}
}
public class sinifD : sinifC
{
void method4()
{
Console.WriteLine("Deneme4");
}
sinifC sinifc = new sinifC(); // I need to use it :)
}
}
Static classes contain static objects that can’t be instantiated multiple times. Usually what I use static classes for are to house static methods that provide calculations, general processing patterns, string output formats, etc. Static classes are light weight and don’t need instantiation.
For instance
System.IO.Fileis a static class with static a methodExists(). You don’t create a File object to call it. You invoke it like thisSystem.IO.File.Exists(filePath)Rather than doing this
System.IO.File myFile = new System.IO.File(filePath);if(myFile.Exists()){ /* do work */ }If you require several objects in software, then you use dynamic classes. For instance if you have an inventory system you may have several
Productobjects and in that case you would use a dynamic class such as this