2

Hello everyone I am fairly new to C# and programming. I'm learning some bits and bytes about good practices when it comes to programming and declaring variables. I'm developing a POS system in C# and I need some help in understanding the practices in declaring variables to move forward.

My question is does C# have global variables? Where is it safe to declare variables in c#? below is a small program I'm experimenting and though if this is a good programming practice although this works perfectly fine.

private class SetDatObjects { public SqlConnection connection = new SqlConnection(); public SqlCommand command = new SqlCommand(); public SqlDataAdapter adapter = new SqlDataAdapter(); public SqlCommandBuilder commandBuilder = new SqlCommandBuilder(); DataSet dataset = new DataSet(); } private void DataGridViewBinding() { SetDatObjects SDO = new SetDatObjects(); SDO.connection.ConnectionString = @"Data Source=imadh\imadh;Initial Catalog=ITZone;Integrated Security=True"; } 

Thank you for answers.... Much appreciated

8
  • Does C# even have "global variables"? I wouldn't think it does. As for this class, it seems kind of unnecessary to me. Declaring variables isn't really a terrible thing. And for most of these it would be best to declare them within a using block which would dispose of them when they're done. I see no compelling reason for this SetDatObjects class. (And no, these are not static variables.) Commented Aug 2, 2016 at 18:25
  • thank you @David for your answer could you please elaborate on how to declare variables within a using block... I'm quite unclear about it Commented Aug 2, 2016 at 18:28
  • stackoverflow.com/questions/75401/uses-of-using-in-c-sharp Commented Aug 2, 2016 at 18:29
  • C# doesn't have global variables. All variables and methods must be part of a class. That being said, Class member variables are acceptable if they help describe/define the class or are used throughout the class' methods. In general, you want to keep variables to the narrowest scope possible. Commented Aug 2, 2016 at 18:32
  • @itsme86 thank you for your answer, it was very insightful. Commented Aug 2, 2016 at 18:45

1 Answer 1

3

As a general rule, you should try to declare your variables in the smallest possible scope. This will make your code more readable, prevent bugs and will free up resources sooner when not used.

Good pattern will be like this:

using (var conn = new SqlConnection()) using (var cmd = new SqlCommand(conn)) { // ... cmd.Execute(); // ... } 
Sign up to request clarification or add additional context in comments.

Comments