Share:

Static Self Object For Every Class - Amit Padhiyar - Saatody

Self is object name of itself class. For example, If developer create two objects in two different classes. Then if you want use non static method and those objects are newly created. So If first object value is X. and second object value is Y. But here, The problem is if you create third object and try to access value of first or second class object then you will get null object so self object help you to retrieve first or second class value.
public class ClassName{
    public static ClassName Self = null;
}
I declare some rules to use Self object.

Don't use Self object in origin class.


public class ClassName{
    public string MSG = "Hello WPF!";
    public static ClassName Self = null;
    
    public void print(){
        // Wrong
        System.Console.WriteLine("MSG: " + Self.MSG);
        
        // Right
        System.Console.WriteLine("MSG: " + MSG);
    }
}

Error could occur due to below example

public class ClassName{
    public string MSG = "";
    public static ClassName Self = null;
}
public class Language{
    public Language(string lang){
        ClassName CN = new ClassName();
        CN.MSG = lang;

        // Use First Method
        ClassName.Self = CN;

        // Or

        // Use Second Method
        if (ClassName.Self == null){
            ClassName.Self = CN;
        }
    }
}
public class PrintFirst{
    public static void Main(string[] args){
        Language l1 = new Language("C#");
        Language l2 = new Language("Java");
        Language l3 = new Language("Python");

        // If You Use First Method
        System.Console.WriteLine("MSG: " + ClassName.Self.MSG);  // Python

        // Or

        // If You Use Second Method
        System.Console.WriteLine("MSG: " + ClassName.Self.MSG);  // C#

        System.Console.ReadKey();
    }
}


Comments

Popular posts from this blog

Get Color From Pixel C# WPF | Saatody | Amit Padhiyar

Basic Audio Operations With MP3 And Wave Files Using NAudio C#

Create Drag And Drop Operation Between DevExpress GridControl And Custom WPF UI | Saatody | Amit Padhiyar