locked
What is this c# capability called? RRS feed

  • Question

  •  

     Hi,

         Haven't had a chance to get any formal training in c# and I'm curious what this capability in c# is called.  When you take a variable and then dot and then some action to take on that variable and you can stack the actions. What is that called? Like as follows:

    yline.Contains(args[1].ToUpper()))

       It seems like some kind of OO concept like inheritance or encapsulation.

                              ... Flash

    Thursday, June 10, 2010 6:34 PM

Answers

  • It's called a fluent interface and is not really a C# specific functionality. Typically this is achieved by returning the current instance. So say you have SetColor(), SetSize(), and SetBitmap() methods in a class called Text. You'd now have:

    Text SetSize(int size)
    {
    ...
    return this;
    }

    Text SetColor(...)
    {
    ...
    return this;
    }

    etc.

    So you can now call:

    _text.SetSize(9).SetColor(Colors.Black).SetBitmap(bitmap);


    http://blog.voidnish.com
    • Marked as answer by etlman Thursday, June 10, 2010 10:00 PM
    Thursday, June 10, 2010 6:49 PM

All replies

  • It's called a fluent interface and is not really a C# specific functionality. Typically this is achieved by returning the current instance. So say you have SetColor(), SetSize(), and SetBitmap() methods in a class called Text. You'd now have:

    Text SetSize(int size)
    {
    ...
    return this;
    }

    Text SetColor(...)
    {
    ...
    return this;
    }

    etc.

    So you can now call:

    _text.SetSize(9).SetColor(Colors.Black).SetBitmap(bitmap);


    http://blog.voidnish.com
    • Marked as answer by etlman Thursday, June 10, 2010 10:00 PM
    Thursday, June 10, 2010 6:49 PM
  • For more info on fluent interfaces, see this Wikipedia link:

    http://en.wikipedia.org/wiki/Fluent_interface


    http://blog.voidnish.com
    Thursday, June 10, 2010 6:51 PM
  • Nishant,

        Thanks, and the wikipedia reference was helpful.  The way visual studio implements the fluent interface is incredible.  You can know nothing about the interface and it shows you all the options you have at each successive method call.  I'm impressed.

                                                     ... Flash

    Thursday, June 10, 2010 9:59 PM