Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Classes in C#? [closed]

Tags:

c#

class

I'm relatively new to the C# language however with a lot of help from Google searches and Stack Overflow I've done a number of apps already which include working with Office, System Services, Processes, WMI, SQL, Linq and Active Directory...

Though despite having success with getting these apps functional I am still unsure about many things in the C# language such as good code practise and using many of the keywords etc..

C# Classes; I know what I can do with them, I know about Constructors and Destructors, Instantiation and Properties but I'm unsure of when I should be using them. So far I have written all of my code in my Form1.cs file inside different Methods. These Methods do a range of different things with completely different APIs. This obviously means that trying to maintain that code can become quite difficult and I'm finding it increasingly frustrating to find anything inside my Form1.cs.

My question to you guys is should I be splitting my code up into different classes? I've attempted to split stuff related to SqlConnection and SqlCommands into a separate class but without instantiating that same class multiple times in my Form1.cs I can't see this being any easier or any benefit.

I've been trying to piece a new app together but this time keeping functionality in it's own class, I was hoping somebody could either tell me I'm stupid and doing it wrong or at least give me some guidance.

This app will eventually load my connection string from App.Config, connect to a SQL database and populate a DataSet with multiple tables from the database. This is by no means functional as it stands as I can't get my head around the whole Classes issue.

partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    string myConnectionString;

    private void Form1_Load(object sender, System.EventArgs e)
    {
        AppConfig cfg = new AppConfig();
        if (cfg.loadConfig())
        {
            myConnectionString = cfg.myConnectionString();
        }
        
        if (!String.IsNullOrEmpty(myConnectionString))
        {
            SQLConn SQL = new SQLConn();
            if (SQL.createConnection(myConnectionString))
            {
                MessageBox.Show("Connected!");
            }
        }
    }
}

class myDataSet
{
    DataSet DataSet()
    {
        DataSet ds = new DataSet();

        SQLConn sql = new SQLConn();
        
        return ds;
    }

    public void fillData()
    {
        try
        {
            SqlCommand sqlCmd = new SqlCommand("SELECT * FROM hardware");                
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

class SQLConn : IDisposable
{
    SqlConnection sqlConn;
    public bool createConnection(string myConnectionString)
    {
        sqlConn = new SqlConnection();
        sqlConn.ConnectionString = myConnectionString;
        try
        {
            sqlConn.Open();
            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return false;
    }

    public void Dispose()
    {
        if (sqlConn.State == ConnectionState.Open)
        {
            sqlConn.Close();
            sqlConn.Dispose();
        }
    }
}

class AppConfig
{
    Configuration cfg;

    public bool loadConfig()
    {
        try
        {
            cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (!File.Exists(cfg.FilePath))
            {
                MessageBox.Show("No configuration file");
            }
            return true;
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return false;
    }

    public string myConnectionString()
    {
        string connectionString = ConfigurationManager.ConnectionStrings["IT_ProjectConnectionString"].ConnectionString;
        return connectionString;
    }
}
like image 459
Robula Avatar asked Sep 05 '12 09:09

Robula


1 Answers

The principles behind OOP say more or less that you should split stuff up as much as possible so that related things are grouped together in their own class, like the SQL stuff in your example. Another, often used example is that of a car - if you need to deal with the data of cars, you would make a car class containing relevant variables like top speed, name, colour and appropriate methods like for example drive(double distance) or something like that.

If you don't want different objects of that class and need that same behaviour at several points, you can prevent multiple instances in several ways: if all points are in your Form1, you only need to instantiate your class once as a class member and you can use it throughout the Form1 class. If you need to access it from different classes, you can either have a global variable (which is considered bad practice by most) or make the class you need to access static - that way, you don't need to instantiate it at all.

If your app is really small, you might get away with putting it all in your Form1 class, but as you yourself noticed, it can get messy and confusing very quickly. Think of classes as an opportunity to sort your code. Think of what is connected with what, and what you would expect to find together, and put that stuff in classes. If you adhere to that, you end up with code that's less frustrating to find code in and that has a clear and logical structure. You can take advantage of things like inheritance once things get more complex and you can reuse classes that do stuff (again, database stuff for example) that you might need in different applications.

This is a very short and very rough description. I don't know any good books on the topic myself (except ones which are for total programming beginners, which seems inappropriate here), but I suggest to find one on OOP or searching for good introduction articles to that topic. Personally, I find the CodeProject to be a good source of articles. Here is one on OOP.

like image 194
Christian Avatar answered Oct 12 '22 23:10

Christian