Warm tip: This article is reproduced from stackoverflow.com, please click
c# design-patterns

return string when using the builder Pattern and Method chaining in C#

发布于 2020-03-27 15:41:05

I want to use the Builder pattern and use that by method chaining.

This is my class:

public class SQLGenerator : ISQLGenerator
{
    private readonly SQLGeneratorModel generatorModel;
    public SQLGenerator()
    {
        generatorModel = new SQLGeneratorModel();
    }

    public ISQLGenerator From(string TableName)
    {
        generatorModel.TabelName = string.Format("FROM {0}", TableName);
        return this;
    }

    public ISQLGenerator Select(List<string> SelectItems)
    {
        StringBuilder select = new StringBuilder();
        var lastItem = SelectItems.Last();
        foreach (var item in SelectItems)
        {
            if (!item.Equals(lastItem))
            {
                select.Append(item).Append(" , ");
            }
            else
            {
                select.Append(item);
            }
        }
        generatorModel.Select =string.Format("SELECT {0}", select.ToString());
        return this;
    }

This is how this class is used:

SQLGenerator generator = new SQLGenerator();
List<string> select = new List<string>();
select.Add("id");
select.Add("Name");
var str = generator.Select(select).From("AppUsers");
Console.WriteLine(str);

Now I expect a string to be returned like this: SELECT ID , NAME FROM APPUSER but it shows me this result in the console:

SqlPagingGenerator.Pattern.SQLGenerator

How can I show the string result?

Questioner
kia kia
Viewed
59
Ndubuisi Jr 2020-01-31 16:28

The reason for your error is that you are returning an object from the method not a string. All you have to do is to override the ToString method of your class to return the string you want.

    public class SQLGenerator : ISQLGenerator
    {
        ....
        public override string ToString()
        {
           return  $"{generatorModel.TableName} {generatorModel.Select}";
        }

    }