Skip to main content
GameDev.net gamedev.net
🔒 Locked 🤖 Godot

C# feature: Extensions

Started by hspirdal Jun 12, 2008 at 11:20 PM 1 replies 1.5k views
Original Post
hspirdal
hspirdal
Hey guys, Looking at the extension feature from Nick Gravelyn's site, I cannot compile the code he uses as a test example:
Quote:
Extension methods must be defined in a non-generic static class
Has the extension feature been altered to only allow for static classes? Nick's test class: (yelds error as allready quoted)

    public class Sprite
    {
        public Texture2D Texture { get; set; }
        public Vector2 Position { get; set; }
        public Color Color { get; set; }

        public static void Draw(this SpriteBatch spriteBatch, Sprite sprite)
        {
            spriteBatch.Draw(sprite.Texture, sprite.Position, sprite.Color);
        }
    }

This example will compile however:

   public static class SpriteManager
    {
        public static void DrawSprite(this SpriteBatch spritebatch, Sprite sprite)
        {
            spritebatch.Draw(sprite.Texture, sprite.Position, sprite.Color);
        }
    }


SnprBoB86
SnprBoB86
Extension methods have always needed to be defined in a static class like your SpriteManager class, but they are typically given an "Extensions" suffix on the name of the class to be extended. For example: "SpriteBatchExtensions"

Nick just forgot to point out the static class bit in his tutorial, you should post a comment to him and let him know.

Also, I don't agree with Nick that this is appropriate use of extension methods. Instead, I would declare Sprite.Draw with the signature public void Draw(SpriteBatch batch) to be used as someSprite.Draw(spriteBatch). Why? Because it's simpler and extension methods don't really buy you anything here.

Extension methods are really as syntactical sugar. They are useful for saving typing when you have helper methods that can be identified by the target object and method name (2 things) rather than a namespace (well, a static class name), target object, and method name (3 things).

"user@microsoft.com".IsValidEmailAddress()
vs
EmailAddressHelpers.IsValid("user@microsoft.com")

In the Sprite case, you have:

spriteBatch.Draw(sprite)
vs
sprite.Draw(spriteBatch)

Why bother with the extension method? It just confuses things!

That said, Nick isn't necessarily wrong to suggest the use of extension methods here. It's just not the call I would have made :-)
hspirdal
hspirdal
Thank you for clearing that up, SnprBoB86. I guess when I read about the extension feature, I immediatly tried to use the feature, without knowing the reasoning behind it. I'll notify Nick of the potential pitfall that I just ran into.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.