Hacker News new | past | comments | ask | show | jobs | submit login

Coming from the .NET world, where extension methods are just syntactic sugar for static methods, the "bug" described in the article wasn't surprising to me. However, it did make me stop and think about how the example would look in C#. This was what I came up with:

    public interface IGreeter {
    }
    
    public static class GreeterExtensions {
        public void Greet(this IGreeter greeter) {
            // If you have CA turned on,
            // you'll get a warning for not
            // using the parameter "greeter"
            Console.WriteLine("Hello, World!");
        }
    }
    
    public class BaseGreeter : IGreeter {
        public abstract void Greet();
    }
    
    public class LazyGreeter : BaseGreeter {
        public override void Greet() {
            Console.WriteLine("sup");
        }
    }
    
    IGreeter greeter = new LazyGreeter();
    
    // This has to be GreeterExtensions.Greet(greeter),
    // because IGreeter is an empty interface
    greeter.Greet();

I think the syntax in C# makes it clearer that you're doing something funky mixing inheritance with extension methods. If you wanted to do it the "correct" way, I think it would look something like:

    public interface IGreeter {
        void Greet();
    }
    
    public class BaseGreeter : IGreeter {
        // Edit: abstract method wouldn't be equivalent to example
        // public abstract void Greet();
        public virtual void Greet() {
            Console.WriteLine("Hello, World!");
        }
    }
    
    public class LazyGreeter : BaseGreeter {
        public override void Greet() {
            Console.WriteLine("sup");
        }
    }
    
    IGreeter greeter = new LazyGreeter();
    greeter.Greet();

Which is more complicated than the idiomatic way of providing default behavior with inheritance:

    public class Greeter {
        public virtual void Greet() {
            Console.WriteLine("Hello, World!");
        }
    }
    
    public class LazyGreeter : Greeter {
        public override void Greet() {
            Console.WriteLine("sup");
        }
    }


    Greeter greeter = new LazyGreeter();
    greeter.Greet();

I'm not a huge fan of the Swift syntax; specifically, IMO, the declaration `class BaseGreeter: Greeter {}` hides where the implementation of `greet` is coming from. Without the method declaration it looks like it's being inherited from the protocol extension, when it's really not.



C# is one of those languages that I absolutely love and wish I had any reason or excuse to use. But it only seems used in .NET apps which are inherently harder to write than web apps which is why I learned Electron instead.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: