c# global class instance code example

Example 1: singleton

Singleton Design Pattern is basically limiting our class so that 
whoever is using that class can only create 1 instance from that class.
       
I create a private constructor which limits access to the instance of the class.
Than I create a getter method where we specify how to create&use the instance.
    - I am using JAVA Encapsulation OOP concept.

Example 2: singleton pattern

class Singleton:
    __instance = None
    def __new__(cls, *args):
        if cls.__instance is None:
            cls.__instance = object.__new__(cls, *args)
        return cls.__instance

Example 3: c# global function without class

// No. in c# everything is an object
// Make them static and put them in a static utility class
// This way you can execute a method from any object any time
// Program.cs:
using static Functions;
class Program
{
    static void Main()
    {
        Said("Hello World!");
    }
}
// Functions.cs
public static class Functions
{
    public static void Said(string message) => Console.WriteLine(message);
}
// NOTE: using static {namespace}

Tags:

Css Example