Results 1 to 6 of 6

Thread: benefits of static

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jul 2001
    Location
    everywhere
    Posts
    111

    benefits of static

    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/de...ientsocket.asp

    and I was curious as to why they use static functions within the class. Thanks,

    Jacob438

  2. #2
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    They use statis methods, so that the class does'nt have to be instantiated to use the methods.

    eg
    Code:
    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.
    Dont gain the world and lose your soul

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Jul 2001
    Location
    everywhere
    Posts
    111
    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

  4. #4
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    No prob
    Dont gain the world and lose your soul

  5. #5
    PowerPoster Lethal's Avatar
    Join Date
    Oct 2000
    Location
    Ohio
    Posts
    2,496
    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.

  6. #6
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    While you're at it, you can also used the sealed keyword to prevent the class from being inherited.
    Dont gain the world and lose your soul

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width