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
Post a Comment