Click to See Complete Forum and Search --> : benefits of static
Jacob438
Nov 19th, 2002, 02:58 PM
If I have a class that has some functions in it. Is there any benefit to using static to declare the functions? I'm doing something like this:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconusingnon-blockingclientsocket.asp
and I was curious as to why they use static functions within the class. Thanks,
Jacob438
DevGrp
Nov 21st, 2002, 10:04 AM
They use statis methods, so that the class does'nt have to be instantiated to use the methods.
eg
class MyClass
{
public static MyMethod()
{
Console.Writeline("Class does'nt have to be instantiated to use this method");
}
}
MyClass.MyMethod();
}
You'll see these in utility classes. When you have a bunch of methods, you just stick them in a class and declare them static.
Also if you are going to be using static methods, the variables in that class have to be static too.
Jacob438
Nov 21st, 2002, 12:00 PM
ah, cool, thanks, I read the description in MSDN about static classes and even looked through the examples and I understood what it meant, but not what the point was, thanks a lot DevGrp, sometimes it helps to have something explained by somebody else.
Thanks,
Jacob438
DevGrp
Nov 21st, 2002, 05:55 PM
No prob :)
Lethal
Nov 21st, 2002, 06:31 PM
Also, if you are going to use it as a straight utility class, you may want to implement a private default constructor and/or static constructor. The private default constructor will block users from instantiating your class directly, and a static constructor can be used to initialize members (static) when the class is first loaded in memory.
DevGrp
Nov 21st, 2002, 08:29 PM
While you're at it, you can also used the sealed keyword to prevent the class from being inherited.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.