Converting some code from Swift to C#. There's a need in a base class's static method implementation to know which concrete type that method was called against.
In Swift, when in an instance method, you use self
(lowercase) to get that instance. This is equivalent to using this
in C#. To get the instance type, you use Self
(uppercase) which is the equivalent of C#'s this.GetType()
.
However, Swift also lets you use lower-cased self
from within a static method to get the type the static was called against (as opposed to the type where it was defined.) I'm trying to find if C# has something similar. We're using C# 9 if it matters.
Here's a simple example showing what we're after. Note, this will not compile. It's example only since self
isn't known to C#.
public class BaseClass {
public static void DoSomethingStatic(){
// Looking for the equivalent of Swift's 'self' in a static method
// which returns the concrete type, including when called from a derived class
Debug.WriteLine($"Static method called on the type {self.FullName}.");
}
public void DoSomethingInstance(){
// Swift's 'Self' in an instance method is equivalent to C#'s `this.GetType()`
Debug.WriteLine($"Instance method called on the type {this.GetType().FullName}.");
}
}
public class MyClass : BaseClass {}
Now this is easily possible with instance methods thanks to using this.GetType()
:
var myClass = new MyClass();
myClass.DoSomethingInstance();
Output:
Instance method called on the type MyClass.
But we're hoping to achieve the same thing from a static exposed via the base class, like this...
MyClass.DoSomethingStatic();
Output:
Static method called on the type MyClass.
So is this possible in C#9?