C
C#2y ago
Thinker

Calling a static abstract method without a generic type [Answered]

If I have this code with a static abstract member Bar in the interface IFoo, is there any way (besides reflection) to call Bar on an instance of IFoo without the explicit type of the instance?
IFoo f = GetFoo();
f.Bar(); // ???

static IFoo GetFoo() =>
new Foo();

interface IFoo {
static abstract void Bar();
}
class Foo : IFoo {
public static void Bar() =>
Console.WriteLine("bar");
}
IFoo f = GetFoo();
f.Bar(); // ???

static IFoo GetFoo() =>
new Foo();

interface IFoo {
static abstract void Bar();
}
class Foo : IFoo {
public static void Bar() =>
Console.WriteLine("bar");
}
12 Replies
Thinker
Thinker2y ago
I know it'd be trivial to do this using reflection, but like... it's reflection
var type = f.GetType();
var map = type.GetInterfaceMap(typeof(IFoo));
var bar = map.TargetMethods.First(m => m.Name == "Bar");
bar.Invoke(null, Array.Empty<object?>());
var type = f.GetType();
var map = type.GetInterfaceMap(typeof(IFoo));
var bar = map.TargetMethods.First(m => m.Name == "Bar");
bar.Invoke(null, Array.Empty<object?>());
Like Bar is there, it has to exist in the type of f, but it's inaccessible without an explicit type, which is impossible to get with just an instance of something.
333fred
333fred2y ago
Use an instance method
Thinker
Thinker2y ago
hmm I mean that doesn't really solve the issue
333fred
333fred2y ago
Well, you're trying to use a static method like an instance method here It doesn't seem like a realistic scenario
333fred
333fred2y ago
My suggestion is to rethink what you're trying to accomplish
Thinker
Thinker2y ago
Well I mean, this isn't a practical example. The only real use is that methods which call static abstract members have to have type parameters, which can become an issue if you either only have the interface type or if the type cannot be inferred and you have to manually write out some big declaration. Though I agree that yes this is barely practical anyway
333fred
333fred2y ago
The only real use is that methods which call static abstract members have to have type parameters
yes If you don't have this, you're using a square peg to go in a round hole
Thinker
Thinker2y ago
It's still slightly annoying
333fred
333fred2y ago
It should be
Thinker
Thinker2y ago
I mean... fair, there's a clear distinction between static and instance, but this still to me feels like one of the major drawbacks of static abstracts
Accord
Accord2y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server
More Posts