Share via

Build a Message

Ronald Rex 1,671 Reputation points
2023-10-12T19:27:36.2633333+00:00

Hi Friends. I have this method with a lot of if statements in it but I want to see if I can be more efficient in building my message. I'm just trying to get tips on how to make my code more terse and efficient. But I don't want a newline if the message is empty. Thanks !!!

public static bool Validation(AccountRequest request)
{

string message="";
string errmessage="";
 if (!Regex.IsMatch(request.Password, @"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{10,128}$"))
{
  if(message=="")
      {
        errmessage="Bad Password";
        message=message + errmessage;
       }
    else
      {
       errmessage="Bad Password";
       message=message + Environment.NewLine + errmessage;
      }
}

Developer technologies | .NET | Other
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Viorel 127K Reputation points
2023-10-12T19:40:34.2733333+00:00

Try this approach:

string message = "";

if( ... ) message += Environment.NewLine + "Bad Password";
if( ... ) message += Environment.NewLine + "Bad Username";
if( ... ) message += Environment.NewLine + "Bad E-mail";
. . .

if( message != "" ) message = message.Substring( Environment.NewLine.Length );

return message == "";

Or this:

string message = "";

if( ... ) message += "Bad Password" + Environment.NewLine;
if( ... ) message += "Bad Username" + Environment.NewLine;
if( ... ) message += "Bad e-mail" + Environment.NewLine;
. . .

return message == "";

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.