Click to See Complete Forum and Search --> : Global Variables


Taggi
December 26th, 2006, 08:51 AM
Hallo! Me again! :eek:

Well, is in C# a posibility to define variables global?

For example is something like this possible?

class proggi
{
public Connection;

void run()
{
A.Init();
B.Use();
}
}
class A
{
public void Init()
{
// Initialise Connection in class proggi
}
}
class B
{
public void Use()
{
// Use Connection in class proggi
}
}

I know that it is easy, if I "put" the varibale Connection into the Parameter list of Init and Use. But is there a possibility to avoid this?

Thanks for help!

Taggi

petes1234
December 26th, 2006, 09:07 AM
Hallo! Me again! :eek:

Well, is in C# a posibility to define variables global?

For example is something like this possible?

class proggi
{
public Connection;

void run()
{
A.Init();
B.Use();
}
}
.
.
.
Taggi

Making proggi public won't help?:

public class proggi
{
.
.
.
}

Taggi
December 26th, 2006, 09:18 AM
Hallo!

Sometimes I doubt in my brain...

Well...

Declaration:
public static Connection;

Use:
proggi.Connection = something;

I have tried without declaring the class proggi public and it Works too!

Thanks for Help.

Taggi

Andy Tacker
December 27th, 2006, 04:47 AM
public class proggi
{
static Connection m_Conn;
public static Connection GetConnection()
{
return m_Conn;
}
}

klintan
December 27th, 2006, 04:01 PM
In general, avoid global variables. It makes the code harder to maintain and test.

In C#, a field or property can be made global by making it static.

For ADO.Net connections, there is no need for a global variable. It is better to rely on connection pooling.

dcell59
January 2nd, 2007, 07:46 PM
It's OK to use global variables (we can use GOTO now, too :-)), but I think it's better to handle that kind of thing as a member of a class that has the lifetime you need. For example, in a web server, you already have several global variables available to use (such as Application) that you can add this kind of thing to. In a Windows Forms app, you have Program.

TheCPUWizard
January 2nd, 2007, 08:03 PM
public class proggi
{
static Connection m_Conn;
public static Connection GetConnection()
{
return m_Conn;
}
}


ANDY A BigSlap to you. :mad:

Assuming this is some type of ADO or Communication conntection they should *always* be inside of a using statement.

MadHatter
January 3rd, 2007, 01:00 AM
public class proggi
{
static Connection m_Conn;
public static Connection GetConnection()
{
return m_Conn;
}
}


ANDY A BigSlap to you. :mad:

Assuming this is some type of ADO or Communication conntection they should *always* be inside of a using statement.

I have a hard time reading a lot of your posts... absolutes are for idiots. if its in a using statement than by the time he gets it it will be disposed. using statements are a lazy mans way of closing out and disposing the object. I use using statements where they make sense, but you cannot wrap a complex DAL inside a single using statement (especially if you pool that connection across many places in your application).

TheCPUWizard
January 3rd, 2007, 09:52 PM
I have a hard time reading a lot of your posts... absolutes are for idiots. if its in a using statement than by the time he gets it it will be disposed. using statements are a lazy mans way of closing out and disposing the object. I use using statements where they make sense, but you cannot wrap a complex DAL inside a single using statement (especially if you pool that connection across many places in your application).


My apologies for being overly brief (not being sarcastic), my life is rather hectic right now, perhaps fewer and better posts would be a good idea. :)

"Absolutes are for Idiots". True, but some things are 99.999xxx% that it is easier to write it that way.

The idea is that you should NOT create an object whichimplements IDisposable, and then pass it out of the containing scope. FxCop will complain mightly on this one.

Both the Company I am working for, and my previous employer (a small company owned by Bill), have strong rules against this. If FxCop reports warnings on your code, you can not even check it into source control.

Try writing (and it can be done) some code that passes an IDisopsable object out of scope and guarentees 100% (not 99.995%) that the object will be disposed in All circcumstances (except a Rude Process Abort)....

Would you be willing to do this? (And agree to pay me $10 for every loophole I find that will avoid Dispose being called).

A bug in production could (and almost certainly would) cost more that $10.

MadHatter
January 3rd, 2007, 10:31 PM
writing frameworks, and writing business applications are often 2 very different beasts. business applications are much less likely to cause as much problems for as many people as something infragistics or microsoft writes. It wasn't until recently that ms started doing fxcop on their source code, because a lot of 1.0 and 1.1 code doesn't even pass all the rules.

TheCPUWizard
January 4th, 2007, 07:09 AM
It wasn't until recently that ms started doing fxcop on their source code, because a lot of 1.0 and 1.1 code doesn't even pass all the rules.


100% Agreement, but the times they are a changing :)

And dont forget FxCop is 100% (well almost) customizable. If you decide to be stricter or looser on coding practices, I strongly recomment taking the time to customize FxCop (or another tool) rather than ignoring errors/warnings.

At 2am (where we have all been), it is easy for a human to make silly mistakes. An automated process will run just as reliabily at any time.

Zaccheus
January 4th, 2007, 08:11 AM
The idea is that you should NOT create an object whichimplements IDisposable, and then pass it out of the containing scope. FxCop will complain mightly on this one.

Forms, Streams, many many classes implement IDisposable.

Why should I not pass these out of the containing scope?
Or rather, how can you write any meaningful application without doing so?
:confused:

TheCPUWizard
January 4th, 2007, 10:13 PM
Psuedo Code (its late :) )

using (stream s = new stream)
{
dostuff with stream;
}


need more power, use a delegate.


void SomeMethod(SomeDelegate d)
using (stream s = new stream)
{
d(s);
}

MadHatter
January 4th, 2007, 11:42 PM
yes, always use a using statement to make cpuwizard happy. by all means, if you have a disposable object, dispose of it right after you create it, never dispose of an idisposable object yourself (leave that to the compiler to do) never dispose of your idisposable objects inside your dispose method, and always use the lazy using brackets (and go ahead and try to use automatic disposal on idisposable objects that dont support automatic disposal), never implement idisposable in your class that contains disposible objects, never use finializers, or any other conventions, just use disposable objects in the context of a using statement, and use objects in a using statement...

pretty solid logic.

Zaccheus
January 5th, 2007, 06:07 AM
TheCPUWizard - how would you create forms which contain other controls? ;)

TheCPUWizard
January 8th, 2007, 07:35 AM
TheCPUWizard - how would you create forms which contain other controls?


Here we are talking about member variables, this changes things (at least from a perspective point).

The controls are created as part of the Forms Construction Process (technically during one of the startup events), and need to live for the life of the form.

Since the form implements IDisposable it can reliably call Dispose on all os the consituent controls. (And the base class in-fact does this)

Therefore, the reality is that the scope of the controls never leaves the scope of the creator (the form).

Note: If you try to take a reference to a forms control, and then close (dispose) the form, you will find that you are holding onto a "disposed" reference. :)

TheCPUWizard
January 8th, 2007, 07:46 AM
yes, always use a using statement to make cpuwizard happy. by all means, if you have a disposable object, dispose of it right after you create it, never dispose of an idisposable object yourself (leave that to the compiler to do) never dispose of your idisposable objects inside your dispose method, and always use the lazy using brackets (and go ahead and try to use automatic disposal on idisposable objects that dont support automatic disposal), never implement idisposable in your class that contains disposible objects, never use finializers, or any other conventions, just use disposable objects in the context of a using statement, and use objects in a using statement...

pretty solid logic.

1) The CPUWizard is happy, regardless of if one writes great, good, medicore, poor or no code at all (unless you are employed by me or are one of my vendors). The point is that great code will make you happy, as well as your boss, company, and customers (if you are a professional developer).

2) IDisposable means that the class contains some resource which may significantly impact system performance and should be used for the minimal amount of time. There is no such thing as "automatic disposal". In many applications it may be minutes, hours or even days before the garbage collector runs, and then it only invokes finalizers, and never (directly) calls Dispose().

3) "never implement idisposable in your class that contains disposible object" actually (assuming you are talking about contains member variables which implement IDisposable" then you should (almost) always implement IDisposable. A much bigger question is doues the design actual require that your class contain member variables which implement IDisposable (the answr is many times, yes; but also often, no....)

4) "never use finializers" They really should be avoided where ever possible. The overhead of cleaning up resources via finalizers is significantly higher than explicit cleanup.

5) j"ust use disposable objects in the context of a using statement". This is an ideal situation. I have repeatedly posted the challenge of someone developing code that does not use the internal structure of a using block, that is not succiptable to at least one leak. Remember the following are equivilant:


using (Class instance = new Class())
{
/// Code
}


and

{
Class instance = null;
try
{
instance = new Class();
/// Code
}
finally
{
if (instance != null)
instance.Dispose();
}
}


But which is more readable????

Zaccheus
January 8th, 2007, 08:01 AM
Here we are talking about member variables, this changes things (at least from a perspective point).
Right, so what you are saying is merely: Always make certain that Dispose will be called when an object which you created is no longer needed.

In principle I agree, but even that is not always possible. Conside for example System.IO.File.Open (http://msdn2.microsoft.com/en-us/library/system.io.file.open.aspx) method which creates and returns a disposable object.

Hard rules which say "never ever" usually don't work, not even 99.999xxx% of the time.
:)

TheCPUWizard
January 8th, 2007, 03:45 PM
Look at the example on the link that you posted. :) :) :)


using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}

MadHatter
January 8th, 2007, 04:10 PM
1) The CPUWizard is happy, regardless of if one writes great, good, medicore, poor or no code at all. glad to hear it. I really could care less.

2) IDisposable means that the class contains some resource which may significantly impact system performance and should be used for the minimal amount of time. There is no such thing as "automatic disposal". placing an IDisposable object in a using statement is an automatic mechanism for disposal is it not? the IL code that is generated from it places the call to dispose on the instance, so yes.

3) "never implement idisposable in your class that contains disposible object" guess sarcasm is a stranger to you.

4) "never use finializers" They really should be avoided where ever possible. The overhead of cleaning up resources via finalizers is significantly higher than explicit cleanup. there goes that absolute reasoning again. they have their place. they do slow down destruction, but are good for unmanaged resources.

5) j"ust use disposable objects in the context of a using statement". This is an ideal situation. I have repeatedly posted the challenge of someone developing code that does not use the internal structure of a using block, that is not succiptable to at least one leak. Remember the following are equivilant:


using (Class instance = new Class())
{
/// Code
}


and

{
Class instance = null;
try
{
instance = new Class();
/// Code
}
finally
{
if (instance != null)
instance.Dispose();
}
}


But which is more readable???? as Zaccheus pointed out, and you obviously missed, going back to what you originally said, File.Open leaves scope with an IDisposable object, which you swore never to do.


unless you were the only guy at microsoft who was tasked with writing all the rules of fxcop and the code analysis tool, then you have just as much room for error in saying what is right and what is wrong as any of us do.

Coming in somewhere and saying:


ANDY A BigSlap to you. :(

Assuming this is some type of ADO or Communication conntection they should *always* be inside of a using statement. to me just shows ignorance and intolerance for other peoples ways of coding. In fact, regarding that statement, if you opened and closed a connection each time you needed a data structure for an enterprise level application, you generate a DOS on the database. So I think that you'd better watch how you say what you say, and if you're going to present an absolute on .NET, you'd better get Anders Hejlsberg or Bill Gates to come back you up.