change value by reference when using an extension method












0















I want to create an error message string. It should contain multiple hints to fix the errors.



First I created something like this



string errorMessage = string.Empty;

if (1 == 1)
errorMessage += "- hint 1n";

if (2 == 2)
errorMessage += "- hint 2n";

if (3 == 3)
errorMessage += "- hint 3";

// do something with errorMessage


And I thought about cleaning it up. I created an extension method



public static void AppendIf(this string s, bool condition, string txtToAppend)
{
if (condition)
s += txtToAppend;
}


And call it within my class



string errorMessage = string.Empty;

errorMessage.AppendIf(1 == 1, "- hint 1n");
errorMessage.AppendIf(2 == 2, "- hint 2n");
errorMessage.AppendIf(3 == 3, "- hint 3");

// do something with errorMessage


But errorMessage stays empty. I thought this acts like the ref keyword so what is wrong with my extension method?










share|improve this question




















  • 4





    Well, this does not act like the ref keyword... that's basically all there is to it. string is an immutable object; slapping on an extension method does not make it mutable. You want a StringBuilder.

    – Jeroen Mostert
    Nov 22 '18 at 10:35






  • 1





    if (1 == 1)? What's the point?

    – SeM
    Nov 22 '18 at 10:35








  • 1





    you probably want to return a new string from your extension method

    – Rahul
    Nov 22 '18 at 10:36











  • @JeroenMostert thanks, I will have a look.

    – MHComputech
    Nov 22 '18 at 10:38











  • @SeM just an example

    – MHComputech
    Nov 22 '18 at 10:38
















0















I want to create an error message string. It should contain multiple hints to fix the errors.



First I created something like this



string errorMessage = string.Empty;

if (1 == 1)
errorMessage += "- hint 1n";

if (2 == 2)
errorMessage += "- hint 2n";

if (3 == 3)
errorMessage += "- hint 3";

// do something with errorMessage


And I thought about cleaning it up. I created an extension method



public static void AppendIf(this string s, bool condition, string txtToAppend)
{
if (condition)
s += txtToAppend;
}


And call it within my class



string errorMessage = string.Empty;

errorMessage.AppendIf(1 == 1, "- hint 1n");
errorMessage.AppendIf(2 == 2, "- hint 2n");
errorMessage.AppendIf(3 == 3, "- hint 3");

// do something with errorMessage


But errorMessage stays empty. I thought this acts like the ref keyword so what is wrong with my extension method?










share|improve this question




















  • 4





    Well, this does not act like the ref keyword... that's basically all there is to it. string is an immutable object; slapping on an extension method does not make it mutable. You want a StringBuilder.

    – Jeroen Mostert
    Nov 22 '18 at 10:35






  • 1





    if (1 == 1)? What's the point?

    – SeM
    Nov 22 '18 at 10:35








  • 1





    you probably want to return a new string from your extension method

    – Rahul
    Nov 22 '18 at 10:36











  • @JeroenMostert thanks, I will have a look.

    – MHComputech
    Nov 22 '18 at 10:38











  • @SeM just an example

    – MHComputech
    Nov 22 '18 at 10:38














0












0








0








I want to create an error message string. It should contain multiple hints to fix the errors.



First I created something like this



string errorMessage = string.Empty;

if (1 == 1)
errorMessage += "- hint 1n";

if (2 == 2)
errorMessage += "- hint 2n";

if (3 == 3)
errorMessage += "- hint 3";

// do something with errorMessage


And I thought about cleaning it up. I created an extension method



public static void AppendIf(this string s, bool condition, string txtToAppend)
{
if (condition)
s += txtToAppend;
}


And call it within my class



string errorMessage = string.Empty;

errorMessage.AppendIf(1 == 1, "- hint 1n");
errorMessage.AppendIf(2 == 2, "- hint 2n");
errorMessage.AppendIf(3 == 3, "- hint 3");

// do something with errorMessage


But errorMessage stays empty. I thought this acts like the ref keyword so what is wrong with my extension method?










share|improve this question
















I want to create an error message string. It should contain multiple hints to fix the errors.



First I created something like this



string errorMessage = string.Empty;

if (1 == 1)
errorMessage += "- hint 1n";

if (2 == 2)
errorMessage += "- hint 2n";

if (3 == 3)
errorMessage += "- hint 3";

// do something with errorMessage


And I thought about cleaning it up. I created an extension method



public static void AppendIf(this string s, bool condition, string txtToAppend)
{
if (condition)
s += txtToAppend;
}


And call it within my class



string errorMessage = string.Empty;

errorMessage.AppendIf(1 == 1, "- hint 1n");
errorMessage.AppendIf(2 == 2, "- hint 2n");
errorMessage.AppendIf(3 == 3, "- hint 3");

// do something with errorMessage


But errorMessage stays empty. I thought this acts like the ref keyword so what is wrong with my extension method?







c#






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 10:39









S.Akbari

30.3k93673




30.3k93673










asked Nov 22 '18 at 10:32









MHComputechMHComputech

25913




25913








  • 4





    Well, this does not act like the ref keyword... that's basically all there is to it. string is an immutable object; slapping on an extension method does not make it mutable. You want a StringBuilder.

    – Jeroen Mostert
    Nov 22 '18 at 10:35






  • 1





    if (1 == 1)? What's the point?

    – SeM
    Nov 22 '18 at 10:35








  • 1





    you probably want to return a new string from your extension method

    – Rahul
    Nov 22 '18 at 10:36











  • @JeroenMostert thanks, I will have a look.

    – MHComputech
    Nov 22 '18 at 10:38











  • @SeM just an example

    – MHComputech
    Nov 22 '18 at 10:38














  • 4





    Well, this does not act like the ref keyword... that's basically all there is to it. string is an immutable object; slapping on an extension method does not make it mutable. You want a StringBuilder.

    – Jeroen Mostert
    Nov 22 '18 at 10:35






  • 1





    if (1 == 1)? What's the point?

    – SeM
    Nov 22 '18 at 10:35








  • 1





    you probably want to return a new string from your extension method

    – Rahul
    Nov 22 '18 at 10:36











  • @JeroenMostert thanks, I will have a look.

    – MHComputech
    Nov 22 '18 at 10:38











  • @SeM just an example

    – MHComputech
    Nov 22 '18 at 10:38








4




4





Well, this does not act like the ref keyword... that's basically all there is to it. string is an immutable object; slapping on an extension method does not make it mutable. You want a StringBuilder.

– Jeroen Mostert
Nov 22 '18 at 10:35





Well, this does not act like the ref keyword... that's basically all there is to it. string is an immutable object; slapping on an extension method does not make it mutable. You want a StringBuilder.

– Jeroen Mostert
Nov 22 '18 at 10:35




1




1





if (1 == 1)? What's the point?

– SeM
Nov 22 '18 at 10:35







if (1 == 1)? What's the point?

– SeM
Nov 22 '18 at 10:35






1




1





you probably want to return a new string from your extension method

– Rahul
Nov 22 '18 at 10:36





you probably want to return a new string from your extension method

– Rahul
Nov 22 '18 at 10:36













@JeroenMostert thanks, I will have a look.

– MHComputech
Nov 22 '18 at 10:38





@JeroenMostert thanks, I will have a look.

– MHComputech
Nov 22 '18 at 10:38













@SeM just an example

– MHComputech
Nov 22 '18 at 10:38





@SeM just an example

– MHComputech
Nov 22 '18 at 10:38












2 Answers
2






active

oldest

votes


















2














You could not use this ref modifier, please check compiler feature request.



However you can get the same result by using the StringBuilder type:



public static void AppendIf(this StringBuilder s, bool condition, string txtToAppend)
{
if (condition)
s.Append(txtToAppend);
}


So, your code will be:



string errorMessage = new StringBuilder();

errorMessage.AppendIf(1 == 1, "- hint 1n");
errorMessage.AppendIf(2 == 2, "- hint 2n");
errorMessage.AppendIf(3 == 3, "- hint 3");


NB: please avoid executing code like str += anotherStr; inside the loop, because this method has O(N^2) complexity, where N is count of chars. Please check details in this question.






share|improve this answer































    4














    string is immutable, which means that it creates a new string every time you append to it, so it is impossible.



    However, you can use StringBuilder to achieve it:



    public static class StringBuilderExtensions
    {
    public static StringBuilder AppendLineIf(this StringBuilder builder, bool condition, string line)
    {
    // validate arguments
    if (condition)
    builder.AppendLine(line);
    return builder;
    }

    public static StringBuilder AppendIf(this StringBuilder builder, bool condition, string line)
    {
    // validate arguments
    if (condition)
    builder.Append(line);
    return builder;
    }
    }

    StringBuilder builder = new StringBuilder();
    builder.AppendLineIf(1 == 1, "- hint 1");
    builder.AppendLineIf(2 == 2, "- hint 2");
    builder.AppendLineIf(3 == 3, "- hint 3");

    string result = builder.ToString();
    // do something with result


    You can also chain these calls, if it looks better for you:



    string result = new StringBuilder()
    .AppendLineIf(1 == 1, "- hint 1")
    .AppendLineIf(2 == 2, "- hint 2")
    .AppendLineIf(3 == 3, "- hint 3")
    .ToString();





    share|improve this answer
























    • Like this solution more than the other one because of returning StringBuilder instead of void from your extension methods.

      – Stefan Illner
      Nov 22 '18 at 11:05











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428945%2fchange-value-by-reference-when-using-an-extension-method%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    You could not use this ref modifier, please check compiler feature request.



    However you can get the same result by using the StringBuilder type:



    public static void AppendIf(this StringBuilder s, bool condition, string txtToAppend)
    {
    if (condition)
    s.Append(txtToAppend);
    }


    So, your code will be:



    string errorMessage = new StringBuilder();

    errorMessage.AppendIf(1 == 1, "- hint 1n");
    errorMessage.AppendIf(2 == 2, "- hint 2n");
    errorMessage.AppendIf(3 == 3, "- hint 3");


    NB: please avoid executing code like str += anotherStr; inside the loop, because this method has O(N^2) complexity, where N is count of chars. Please check details in this question.






    share|improve this answer




























      2














      You could not use this ref modifier, please check compiler feature request.



      However you can get the same result by using the StringBuilder type:



      public static void AppendIf(this StringBuilder s, bool condition, string txtToAppend)
      {
      if (condition)
      s.Append(txtToAppend);
      }


      So, your code will be:



      string errorMessage = new StringBuilder();

      errorMessage.AppendIf(1 == 1, "- hint 1n");
      errorMessage.AppendIf(2 == 2, "- hint 2n");
      errorMessage.AppendIf(3 == 3, "- hint 3");


      NB: please avoid executing code like str += anotherStr; inside the loop, because this method has O(N^2) complexity, where N is count of chars. Please check details in this question.






      share|improve this answer


























        2












        2








        2







        You could not use this ref modifier, please check compiler feature request.



        However you can get the same result by using the StringBuilder type:



        public static void AppendIf(this StringBuilder s, bool condition, string txtToAppend)
        {
        if (condition)
        s.Append(txtToAppend);
        }


        So, your code will be:



        string errorMessage = new StringBuilder();

        errorMessage.AppendIf(1 == 1, "- hint 1n");
        errorMessage.AppendIf(2 == 2, "- hint 2n");
        errorMessage.AppendIf(3 == 3, "- hint 3");


        NB: please avoid executing code like str += anotherStr; inside the loop, because this method has O(N^2) complexity, where N is count of chars. Please check details in this question.






        share|improve this answer













        You could not use this ref modifier, please check compiler feature request.



        However you can get the same result by using the StringBuilder type:



        public static void AppendIf(this StringBuilder s, bool condition, string txtToAppend)
        {
        if (condition)
        s.Append(txtToAppend);
        }


        So, your code will be:



        string errorMessage = new StringBuilder();

        errorMessage.AppendIf(1 == 1, "- hint 1n");
        errorMessage.AppendIf(2 == 2, "- hint 2n");
        errorMessage.AppendIf(3 == 3, "- hint 3");


        NB: please avoid executing code like str += anotherStr; inside the loop, because this method has O(N^2) complexity, where N is count of chars. Please check details in this question.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 '18 at 10:47









        Manushin IgorManushin Igor

        1,060818




        1,060818

























            4














            string is immutable, which means that it creates a new string every time you append to it, so it is impossible.



            However, you can use StringBuilder to achieve it:



            public static class StringBuilderExtensions
            {
            public static StringBuilder AppendLineIf(this StringBuilder builder, bool condition, string line)
            {
            // validate arguments
            if (condition)
            builder.AppendLine(line);
            return builder;
            }

            public static StringBuilder AppendIf(this StringBuilder builder, bool condition, string line)
            {
            // validate arguments
            if (condition)
            builder.Append(line);
            return builder;
            }
            }

            StringBuilder builder = new StringBuilder();
            builder.AppendLineIf(1 == 1, "- hint 1");
            builder.AppendLineIf(2 == 2, "- hint 2");
            builder.AppendLineIf(3 == 3, "- hint 3");

            string result = builder.ToString();
            // do something with result


            You can also chain these calls, if it looks better for you:



            string result = new StringBuilder()
            .AppendLineIf(1 == 1, "- hint 1")
            .AppendLineIf(2 == 2, "- hint 2")
            .AppendLineIf(3 == 3, "- hint 3")
            .ToString();





            share|improve this answer
























            • Like this solution more than the other one because of returning StringBuilder instead of void from your extension methods.

              – Stefan Illner
              Nov 22 '18 at 11:05
















            4














            string is immutable, which means that it creates a new string every time you append to it, so it is impossible.



            However, you can use StringBuilder to achieve it:



            public static class StringBuilderExtensions
            {
            public static StringBuilder AppendLineIf(this StringBuilder builder, bool condition, string line)
            {
            // validate arguments
            if (condition)
            builder.AppendLine(line);
            return builder;
            }

            public static StringBuilder AppendIf(this StringBuilder builder, bool condition, string line)
            {
            // validate arguments
            if (condition)
            builder.Append(line);
            return builder;
            }
            }

            StringBuilder builder = new StringBuilder();
            builder.AppendLineIf(1 == 1, "- hint 1");
            builder.AppendLineIf(2 == 2, "- hint 2");
            builder.AppendLineIf(3 == 3, "- hint 3");

            string result = builder.ToString();
            // do something with result


            You can also chain these calls, if it looks better for you:



            string result = new StringBuilder()
            .AppendLineIf(1 == 1, "- hint 1")
            .AppendLineIf(2 == 2, "- hint 2")
            .AppendLineIf(3 == 3, "- hint 3")
            .ToString();





            share|improve this answer
























            • Like this solution more than the other one because of returning StringBuilder instead of void from your extension methods.

              – Stefan Illner
              Nov 22 '18 at 11:05














            4












            4








            4







            string is immutable, which means that it creates a new string every time you append to it, so it is impossible.



            However, you can use StringBuilder to achieve it:



            public static class StringBuilderExtensions
            {
            public static StringBuilder AppendLineIf(this StringBuilder builder, bool condition, string line)
            {
            // validate arguments
            if (condition)
            builder.AppendLine(line);
            return builder;
            }

            public static StringBuilder AppendIf(this StringBuilder builder, bool condition, string line)
            {
            // validate arguments
            if (condition)
            builder.Append(line);
            return builder;
            }
            }

            StringBuilder builder = new StringBuilder();
            builder.AppendLineIf(1 == 1, "- hint 1");
            builder.AppendLineIf(2 == 2, "- hint 2");
            builder.AppendLineIf(3 == 3, "- hint 3");

            string result = builder.ToString();
            // do something with result


            You can also chain these calls, if it looks better for you:



            string result = new StringBuilder()
            .AppendLineIf(1 == 1, "- hint 1")
            .AppendLineIf(2 == 2, "- hint 2")
            .AppendLineIf(3 == 3, "- hint 3")
            .ToString();





            share|improve this answer













            string is immutable, which means that it creates a new string every time you append to it, so it is impossible.



            However, you can use StringBuilder to achieve it:



            public static class StringBuilderExtensions
            {
            public static StringBuilder AppendLineIf(this StringBuilder builder, bool condition, string line)
            {
            // validate arguments
            if (condition)
            builder.AppendLine(line);
            return builder;
            }

            public static StringBuilder AppendIf(this StringBuilder builder, bool condition, string line)
            {
            // validate arguments
            if (condition)
            builder.Append(line);
            return builder;
            }
            }

            StringBuilder builder = new StringBuilder();
            builder.AppendLineIf(1 == 1, "- hint 1");
            builder.AppendLineIf(2 == 2, "- hint 2");
            builder.AppendLineIf(3 == 3, "- hint 3");

            string result = builder.ToString();
            // do something with result


            You can also chain these calls, if it looks better for you:



            string result = new StringBuilder()
            .AppendLineIf(1 == 1, "- hint 1")
            .AppendLineIf(2 == 2, "- hint 2")
            .AppendLineIf(3 == 3, "- hint 3")
            .ToString();






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 22 '18 at 10:46









            Yeldar KurmangaliyevYeldar Kurmangaliyev

            24.5k93666




            24.5k93666













            • Like this solution more than the other one because of returning StringBuilder instead of void from your extension methods.

              – Stefan Illner
              Nov 22 '18 at 11:05



















            • Like this solution more than the other one because of returning StringBuilder instead of void from your extension methods.

              – Stefan Illner
              Nov 22 '18 at 11:05

















            Like this solution more than the other one because of returning StringBuilder instead of void from your extension methods.

            – Stefan Illner
            Nov 22 '18 at 11:05





            Like this solution more than the other one because of returning StringBuilder instead of void from your extension methods.

            – Stefan Illner
            Nov 22 '18 at 11:05


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428945%2fchange-value-by-reference-when-using-an-extension-method%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'