I am quite new to C# and am moving over from a mediocre knowledge of Pascal, so theres quite a bit new construct to learn. There is probably 2 very simple answers to my questions, but I have done some research and have not found any explanation I can relate too, so I would be grateful if someone could help me out.
First Question
What is the difference between declaring something with just its type and declaring it as well as making it equal to a "new" of the same type?
//Simple declaration
Int myInteger;
Random myRand;
//Making it equal to the same type
Int myInteger = new Integer();
Random myRand = new Random();
Second Question
I am fully trying to understand how Static works, but struggling and just end up making everything static because you need static variables inside your static main and so on. I know its something to do with only running the program once, but would really need a simple and clear explanation of it before I can move on to fully understanding the complications of it, maybe a with a metaphor would help.
Thanks for the help, and I look forward to replies!
Loading
VulpesPosted Jul 11, 2012, 7:06 AM
Random myRand;
myRand = new Random();
and this:
Random myRand = new Random();
The latter is really just short-hand for the former.
Notice that for basic types such as int, you don't need to use 'new' at all. This line:
int myInteger = new int();
is just the same as this:
int myInteger = 0;
You only need to declare a member static if it applies to the class as a whole rather than a specific instance of it. It follows that you don't need an instance variable to access a static member, you just use the class name.
Notice in particular that the Main() method must always be static. If it were not, then you'd need to create an instance of the class in which it's placed to access it and so it wouldn't be the first method to be executed when the application begins.
Deepak GoyalPosted Jul 13, 2012, 9:53 AM
Benjamin AshtonPosted Jul 11, 2012, 2:31 PM
VulpesPosted Jul 11, 2012, 9:00 AM
Benjamin AshtonPosted Jul 11, 2012, 8:42 AM
VulpesPosted Jul 11, 2012, 8:01 AM
Benjamin AshtonPosted Jul 11, 2012, 7:22 AM