Share via


How to Break Long code lines in Visual Studio 2010 (C#)

Question

Tuesday, April 16, 2013 8:50 AM

hi to all

in vb this is easy just put  " _ &" but in C# I don't know how to do it

thanks

All replies (4)

Tuesday, April 16, 2013 8:53 AM ✅Answered

C# doesn't mind large gaps of white-space or new lines within it's code, unless to pertains to strings (otherwise you can just allow the code to wrap or press Enter to start a new line).

In your current case, you are working with strings, so just make sure that you are wrapping each of the individual strings within the appropriate quotes and use the "+" character to append them as seen below : 

SqlCommand sqlcmd = new SqlCommand("SELECT TopicsTitle,TopicContents,UserName,Avatar,NumberOfPost,uPoints,uType " +
                                     "FROM Topic, Registration " +
                                    "WHERE Topic.Category ='" + ilblTopic.Text + "'" +
                                      "AND LastPostDate ='" + DateTime.Parse("...") + "'");

You may also want to consider using the String.Format() method to more easily pass in your arguments and avoid a ton of concatenated strings : 

SqlCommand sqlcmd = new SqlCommand(String.Format("SELECT TopicsTitle,TopicContents,UserName,Avatar,NumberOfPost,uPoints,uType " +
                                                   "FROM Topic, Registration " +
                                                  "WHERE Topic.Category ='{0}' " + 
                                                    "AND LastPostDate ='{1}' ",ilblTopic.Text,DateTime.Parse("...")));

When handling SQL Commands like this however, the safest bet is to use SqlCommand.Parameters to populate your parameters.


Tuesday, April 16, 2013 8:54 AM ✅Answered

Just continue your code on a new line. ore let the code simply wrap around at the end of the line. 


Tuesday, April 16, 2013 9:05 AM

thanks very helpful

this is much better now

string sqlcondition;
            sqlcondition = "Select TopicsTitle,TopicContents,UserName,Avatar, NumberofPost,uPoints," +
            "uType FROM Topic,Registration WHERE Topic.Category ='" + ilblTopic.Text +
            "'AND LastPostDate ='" + DateTime.Parse(ilblLastReplyTime.Text) + "'";
            
            sqlcmd1 = new SqlCommand(sqlcondition , con);
            adapter1 = new SqlDataAdapter(sqlcmd1 );

Sunday, April 21, 2013 12:03 PM

C# is not line based, so you can split the statements anywhere but inside an identifier:

public static void somemethod(

int param1,

int param2,

int param3,

more params etc...

)