In python, an instance method self points to the class instance, just like this in C#.
In python, a class method self points to the class. Is there a C# equivalent?
This can be useful, example:
Python example:
class A:
values = [1,2]
@classmethod
def Foo(self):
print "Foo called in class: ", self, self.values
@staticmethod
def Bar():
print "Same for all classes - there is no self"
class B(A):
# other code specific to class B
values = [1,2,3]
pass
class C(A):
# other code specific to class C
values = [1,2,3,4,5]
pass
A.Foo()
A.Bar()
B.Foo()
B.Bar()
C.Foo()
C.Bar()
Results in:
Foo called in class: __main__.A [1, 2]
Same for all classes - there is no self
Foo called in class: __main__.B [1, 2, 3]
Same for all classes - there is no self
Foo called in class: __main__.C [1, 2, 3, 4, 5]
Same for all classes - there is no self
This can be a great tool so that common code in a class context (without an instance) can provide customised behaviour that is defined by the subclass (without requiring an instance of the subclass).
It seems to me that C# static methods are exactly like pythons static methods, in that there is no access to which class was actually used to invoke the method.
But is there a way to do class methods in C#??
Or at least determine which class invoked a method, for example:
public class A
{
public static List<int> values;
public static Foo()
{
Console.WriteLine("How can I figure out which class called this method?");
}
}
public class B : A
{
}
public class C : A
{
}
public class Program
{
public static void Main()
{
A.Foo();
B.Foo();
C.Foo();
}
}
There is no way to do this using regular static methods. Possible alternatives include:
1) Virtual, overridden instance methods:
2) Extension methods:
3) Assuming A and B have a default constructor: