2

This question already has an answer here:

I am just being picky and really wanted some of my code to look, feel, and be used a specific way but am not sure if its possible.

I have a class I created that can be used like this

Query("ServerName", "TSQL").Run()

sample:

 class Query
    {
        public string serverName { get; set; }
        public string tSQL { get; set; }
        public Query(string ServerName, string TSQL)
        {
            serverName = ServerName;
            tSQL = TSQL;
        }

        public void Run()
        {
            //DO STUFF
        }
    }

is it possible to create a class and sub classes so that I use it like this

Query.Server("ServerName").TSQL("TSQL").Run()

marked as duplicate by gnat, user40980, Bart van Ingen Schenau, amon, 9000 Dec 15 '14 at 17:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

7

Yes, what you're referring to is method chaining. You would add these methods to your class, and the return for each method would be the class itself.

class Query
{
    public string serverName { get; set; }
    public string tSQL { get; set; }
    public Query(string ServerName, string TSQL)
    {
        serverName = ServerName;
        tSQL = TSQL;
    }

    public void Run()
    {
        //DO STUFF
    }  

    public Query Server(string svrName)
    {
        serverName = svrName;
        return this;
    }

    public Query TSql(string tsql)
    {
        tSQL = tsql;
        return this;
    }
}

As long as each method in the chain returns the updated object in question rather than void or some other class it will function just fine. Given the simplistic nature of this usage, I wouldn't actually recommend chaining as a useful feature here, but it certainly can be applied.

  • 4
    +1 Also sometimes called Fluent Interface – Eric King Dec 11 '14 at 22:15
  • 1
    wrong link @EricKing - here is the correct one :) – gnat Dec 11 '14 at 22:18
  • thanks for the quick response and answer, exactly what I was looking for. – Hakubex Dec 12 '14 at 14:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.