Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
I am new to VS & C# so please bear with me ...

When programming in VB, I can set up a Module called Definitions and within that I can define any and all Variables that I will use throughout the entire Program.

Can I do anything similar in VS2010 .net C# when defining Classes ?
Posted

Using static data and making it application-global is a bad thing. One big problem is the lack of synchronization methods for using them in different threads. You are not going to play with the idea of designing a really advanced applications without threading, are you? There are ways to avoid static data — at all, or in almost all situations.

I would advise you to use a static class only to declare a set of "global" constants and read-only objects, nothing else. Well, you can also use this approach for something else if your application is really simple.

Beyond that, you really want to be more serious. So, you can better use the Singleton design pattern, see:
http://en.wikipedia.org/wiki/Singleton_pattern[^],
http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29[^].

You can find good code samples here: http://csharpindepth.com/Articles/General/Singleton.aspx[^].

My other advice would be to avoid extra singletons. Here is the example: suppose you have a main form or a main window in you UI. This object already plays the role of a singleton, so you can put your application-global class with the declarations as a member of it instead of creating a separate singleton. The less singletons or static objects, the better.

—SA
 
Share this answer
 
v3
Comments
fjdiewornncalwe 20-Jan-12 12:48pm    
+5.
Sergey Alexandrovich Kryukov 20-Jan-12 13:04pm    
Thank you, Marcus.
--SA
[no name] 20-Jan-12 13:21pm    
Well said :-)
Sergey Alexandrovich Kryukov 20-Jan-12 14:05pm    
Thank you, Collin.
--SA
Generally, you shouldn't need global variables; most interactive applications have a single startup class (a main form, in the case of a desktop UI application), and other forms will be children (logically speaking of that one). So the main form can create them, hook onto event handlers or expose callback hooks, and the main form (or the model class behind it, if you're doing things properly) can be the repository for what is open and so on.

There are rare cases where this doesn't work, for example if your application doesn't have a concept of 'the main form' and instead needs to show a variety of similar forms that all have equal precedence. This is unusual so I won't go into it in detail, but if you think this is what you need, please respond under this solution explaining your problem in a bit more detail.

Looking at what you posted in Solution 2, I think you are making a very typical mistake for mainframe or DOS programmers trying to write UI apps: you still think in terms of 'screens' and translate one screen to one form. This is not how users will expect to interact with an application on a graphical OS and in general it's the wrong design approach for the UI. Depending on the complexity of the application, two good approaches (which can be combined through the use of 'Advanced ...' buttons) are: (i) to include everything on one form, but in tabs, one tab per old screen (roughly speaking), and (ii) for rarely used options, show a dialog box (modal form) to edit just those values. Both of those can be done within the scope of one form class, as in (i) everything is obviously present there, and in (ii) the main form can spawn the modal editors and handle updating the model on close.
 
Share this answer
 
Comments
Gary Heath 20-Jan-12 10:47am    
Yes, to a certain degree, you are right, my mind (which isn't surprising after working that way for over 30 years !) still tends to think "here's some data, how do I deal with it", rather than "here is everything you could ever want, what do you want to do" !!! It isn't easy getting my head round it, especially the naming conventions, hooks, model classes, modal forms, etc.

I am trying to write a program for a friend of mine who runs a PBM game to speed things up for him. In the long run it is my job to rewrite the game in C# using .net & SQL Server, and as part of my learning curve I am writing this program (creating this Project !).

I couldn't see an option for using Tabs, so I decided on a MenuStrip across the top of the Form that splits his options, rather than create an interactive Form which changes it's layout depending on his choices within ComboBox dropdowns, I thought that would be less complicated and of course it allows me to design the Forms within VS2010 rather than code them.

Option 1 is to maintain the database, add new leagues, modify names, delete old leagues, then within that, to rename, add and delete Teams within each league. Option 2 is to generate a Cup competition from that SQL data & create a .Txt file for him to use in the processing that he does on his Atari Emulator (hence the need for the update / rewrite that I am looking at). Option 3 (not needed yet) will be to automatically read and process the results from the processed turn, some 2 or 3 weeks later.

As you see, there are three very distinct processes that make up the whole thing, and I do want to encompass them within the one Project to make things easier for him to process as much as anything else, as he's even more of a dinosaur than I am !!!

Is that enough detail :-) ?!?!?
BobJanova 20-Jan-12 12:20pm    
The TabControl is something that you can drop into the graphical UI designer and then add tabs to, onto which you can add other controls. Three tabs for the three 'functions' would be my default approach here.
Sergey Alexandrovich Kryukov 20-Jan-12 12:12pm    
There a are many good thought you share in this post, and I voted 4. Why not 5? I think you narrowed down the subject just a bit too much (why startup class, why forms? not only), but, more importantly, you did not discuss one design pattern which is totally relevant and is a must-to-consider when it comes to this topic -- the Singleton.

I tried to complement this in my answer, please see.
--SA
BobJanova 20-Jan-12 12:21pm    
The difference between a singleton and a static reference to an object is quite small. I tend to stay away from singletons in discussions if possible since they are far easier to abuse by overuse than by not using them at all (imho). Although I must admit I simply forgot about that pattern ;)
Sergey Alexandrovich Kryukov 20-Jan-12 13:08pm    
Yes, in a rudimentary implementation, not in the cultured one. The really big difference is abstracting out of access to a static instance. In a good singleton implementation, all the static data it totally private. It gives you a way to apply, say, locking important for threading or control access in any other way.

Yes, this is simple: of course you just forgot this pattern, and I reminded you. :-)
--SA
What you need to use in C# to achieve a similar functionality is a "static" class with public static properties.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 20-Jan-12 12:22pm    
Yes, but this should be best avoided. You need to explain the danger of it and explain where it is more or less acceptable. (I did not vote this time.)

I tried to explain it in my answer. A must-consider pattern here is the Singleton -- please see.
--SA
fjdiewornncalwe 20-Jan-12 12:48pm    
You are absolutely correct. It was just a quick one to give him something to chew on.
Where do I do this ? I'm sorry, but I am very new to this and have been trying to learn the basics, but every time I try and do something, it seems I want to do things that are beyond the scope of my lessons thus far ... and being a mainframe programmer by trade, I just want to get on with the code as I fully understand the logic !!!

I have a Form that calls a new form on the clicking of a toolstrip, this is my code :

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace KA_EMail_League_Cup
{
    public partial class KALCForm1 : Form
    {
        public KALCForm1()
        {
            InitializeComponent();
        }

        KALCForm1 firstForm = new KALCForm1();
        KALCForm2 secondForm = new KALCForm2();
        KALCForm3 thirdForm = new KALCForm3();
        KALCForm4 fourthForm = new KALCForm4();

        private void KALCleagueMaintenanceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            secondForm.Show();
            firstForm.Hide();
        }
    }
}


If I try to code something similar on the Second Form, to switch to the Third Form it gets flagged as errors, as these definitions, presumably, are within the Form1 code, hence my request ... so what code do I need so that the lines ...

C#
KALCForm1 firstForm = new KALCForm1();
KALCForm2 secondForm = new KALCForm2();
KALCForm3 thirdForm = new KALCForm3();
KALCForm4 fourthForm = new KALCForm4();


... get picked up by all my Forms ?!?

Thanks in advance ...
 
Share this answer
 
Comments
BobJanova 20-Jan-12 10:14am    
Q&A questions aren't like a thread, if you want to respond to a particular answer you should use 'Have a question or comment' underneath that answer. That starts a discussion thread and will alert the person to whom you are responding.
Sergey Alexandrovich Kryukov 20-Jan-12 12:23pm    
There is a different problem with this code I explained in my other answer and suggested a better solution. Please see (about form collaboration).
--SA
I want to add another answer based on your code sample. You probably think it is related to your original question, but it is not. What you do is: you keep referenced to several forms in another form, supposedly a main form. Even though this is just fine for a simple application, it might complicate some things because such pattern does not guard you from creating of strong coupling between form during development. It can easily lead to a loss of supportability during further development. Simply put, you give one form too much access to another form; and later it can make your code resisting the changes and even invite some bugs.

You really need loose coupling. You can find some motivation here: http://en.wikipedia.org/wiki/Loose_coupling[^].

Now, what to do with those form references? This is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class and passing the interface reference instead of reference to a "whole instance" of a Form. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].

—SA
 
Share this answer
 
Comments
Gary Heath 20-Jan-12 12:41pm    
My head is spinning !!! I think I am going to have to read these posts and your links quite a few times before I even begin to comprehend !!!
I think we'd need to know much more about your specific application scenario to give you more focused advice here. Whether "threading" is required, and used (the issue discussed by SAK above), for example.

"Static classes" can be used as "libraries" of function calls that are used across all classes: several .NET objects themselves have exactly this structure and purpose by design: consider "String," for example.

Whether or not to use a static class, or a singleton class, can depend on the nature of the relatively changing, or fixed, data that needs to be communicated across selected classes, shared among all classes, or exposed only by some special means (such as an interface).

Complicating the variety of choices you have here is the fact that static members (fields, methods, properties, etc.) can be implemented within Classes that are dynamically instantiated via 'new.

imho, that is a technique of choice (via using a static Property) in exposing one object, or datum, from a dynamically instantiated Class to outside "consumers" of said object, or datum. But note, there are those who really don't like this approach and have fervent beliefs that this should be done only via Interfaces !

Those ... static whatevers defined inside a dynamically instantiated class ... will be "visible/accessible" to any other Class by specifying the full "design-time path" to the static entity ... and not visible/accessible to any instance of the Class you have created using 'new: for example:
// here we assume the static entity is in another NameSpace
// than the one it is "accessed" from: so the NameSpace
// must be also included in the "full path"
SomeOtherNamespace.SomeClassname.SpecificStaticWhatEverName
You could have created many instances of 'SomeClassName using 'new, and none of them will "expose" the internal static 'SpecificStaticWhatEverName.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900