Results 1 to 17 of 17

Thread: Static and non classes

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    Static and non classes

    Stupid question.....

    What is the benefit of using Static classes? Why would you use it? Why not create a standard instiatable class (new keyword) and have functions in that to do the same job as a static class?

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  2. #2
    Interweb adm/o/distrator Paul M's Avatar
    Join Date
    Nov 2006
    Location
    Australia, Melbourne
    Posts
    2,306

    Re: Static and non classes

    Static classes can be used/accessed from anywhere in the project without actually declaring a new instance of it. Now for when to use them ....

    Say you have a class that returns the brand name of your car as an example, it really isn't associated with an object, so there is no reason to the unnecessary and create an instance. So you would just do this instead...

    C# Code:
    1. static class CarTypeInfo
    2. {
    3.     public static string GetCarType() { return "cartype"; }
    4.     //etc..
    5. }
    instead of...

    C# Code:
    1. class CarTypeInfo
    2. {
    3.     public string GetCarType() { return "cartype"; }
    4.     //etc..
    5. }

    Also note a static class can only contain static methods

  3. #3
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Static and non classes

    Have a look at this article.

  4. #4
    Interweb adm/o/distrator Paul M's Avatar
    Join Date
    Nov 2006
    Location
    Australia, Melbourne
    Posts
    2,306

    Re: Static and non classes

    Quote Originally Posted by Hack
    Have a look at this article.
    Yes or you can have a look at a more detailed one ^

  5. #5

    Thread Starter
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    Re: Static and non classes

    thanks. i am aware of how to use them and the declaration but just wondered why you would use it, what the benefit is. I know the CLR will automatically load the static classes since it doesnt require for it to be instantiated hence improving performance slightly.... but still overall the concept i dont quite get. Perhaps ideal for say using it as a "helper" class where you can pass in an object to update to SQL. example:


    public static class DataHelper {

    public static bool UpdateAccount(Account accountToUpdate)
    {
    //SQL Stuff here
    }

    }

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  6. #6
    KrisSiegel.com Kasracer's Avatar
    Join Date
    Jul 2003
    Location
    USA, Maryland
    Posts
    4,985

    Re: Static and non classes

    It's useful for when you don't need a class, just a method to do something.

    For example, why should I have to create an instance of a Convert class if all I want / need to run in the ToDouble method it contains? The concept of static is in VB.Net and has been in C++ for a while as well other languages so it's a useful construct.
    KrisSiegel.com - My Personal Website with my blog and portfolio
    Don't Forget to Rate Posts!

    Free Icons: FamFamFam, VBCorner, VBAccelerator
    Useful Links: System.Security.SecureString Managed DPAPI Overview Part 1 Managed DPAPI Overview Part 2 MSDN, MSDN2, Comparing the Timer Classes

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Static and non classes

    I don't know if this is true in C#, but if you have ever written in VB.NET, and have used a module (as opposed to a class) to hold some common data, or common functions, then you are using static members.
    My usual boring signature: Nothing

  8. #8
    Lively Member
    Join Date
    Oct 2006
    Location
    USA
    Posts
    122

    Re: Static and non classes

    I have often wondered what is the true benefit of static classes.

    They can't be inherited....
    Why make a whole class static for one method...you can declare a static method in a public class....

    I would be led to think the only purpose is to hold common values: variables, properties, etc. I would say not to use a static class for an object that you want throughout the application, because a static class really isn't an object and that is what the singleton pattern is for.

    my two cents

    -zd

  9. #9
    Frenzied Member axion_sa's Avatar
    Join Date
    Jan 2002
    Location
    Joburg, RSA
    Posts
    1,724

    Re: Static and non classes

    That would be a restriction/limitation (depending on your point of view) to the .net languages: all methods must be contained within a class.
    Whilst you certainly could drop them into an externally visible non-static class, you would (by default) still be able to create an instance of that class. Bit pointless, eh? In versions below 2.0, you would add a private default constructor to prevent instantiation: 2.0 added the ability to mark the class as static to allow you to skip that step.

    From a slightly lower level of detail... Using the VS2008 C# compiler on the following class:
    Code:
    namespace Sandbox
    {
    	public class StaticSample
    	{
    		public static void FooBar()
    		{
    			Console.WriteLine("Hello world");
    		}
    	}
    }
    The IL is as follows; notice the constructor that was generated:
    .class public auto ansi beforefieldinit Sandbox.StaticSample
    extends [mscorlib]System.Object
    {
    .method public hidebysig static void FooBar() cil managed
    {
    // Code size 13 (0xd)
    .maxstack 8
    IL_0000: nop
    IL_0001: ldstr "Hello world"
    IL_0006: call void [mscorlib]System.Console::WriteLine(string)
    IL_000b: nop
    IL_000c: ret
    } // end of method StaticSample::FooBar

    .method public hidebysig specialname rtspecialname
    instance void .ctor() cil managed
    {
    // Code size 7 (0x7)
    .maxstack 8
    IL_0000: ldarg.0
    IL_0001: call instance void [mscorlib]System.Object::.ctor()
    IL_0006: ret
    } // end of method StaticSample::.ctor

    } // end of class Sandbox.StaticSample
    Marking the class as static:
    .class public abstract auto ansi sealed beforefieldinit Sandbox.StaticSample
    extends [mscorlib]System.Object
    {
    .method public hidebysig static void FooBar() cil managed
    {
    // Code size 13 (0xd)
    .maxstack 8
    IL_0000: nop
    IL_0001: ldstr "Hello world"
    IL_0006: call void [mscorlib]System.Console::WriteLine(string)
    IL_000b: nop
    IL_000c: ret
    } // end of method StaticSample::FooBar

    } // end of class Sandbox.StaticSample
    Also worth noting - 3.0+ have extension methods - required to be static for good reason. Creating a single class for a single method (see the "limitation" comment in the first paragraph) is entirely up to the person writing the code.

    Apart from synchronisation objects and other private members, I wouldn't condone using static variables - fair asking for trouble; there are other means of maintaining state application wide - thread context, web context, etc.

    As to the singleton pattern - from a coder's perspective, I would positively hate having to write Convert.Instance().Insert method here. From a pattern perspective, it's used when you wish to restrict instantiation. As you can see, marking a class as static means you can't instantiate a static class. Static classes also make good simple factories, or mediators.

  10. #10
    Interweb adm/o/distrator Paul M's Avatar
    Join Date
    Nov 2006
    Location
    Australia, Melbourne
    Posts
    2,306

    Re: Static and non classes

    Quote Originally Posted by Shaggy Hiker
    I don't know if this is true in C#, but if you have ever written in VB.NET, and have used a module (as opposed to a class) to hold some common data, or common functions, then you are using static members.
    They are shared members, im pretty sure they are at the least

    But one thing i have noticed with modules is that if i add one project to another and try to access a member from the other projects module, it won't work but with a class it will. So in the end they do have there benefits.

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Static and non classes

    Quote Originally Posted by Paul M
    They are shared members, im pretty sure they are at the least

    But one thing i have noticed with modules is that if i add one project to another and try to access a member from the other projects module, it won't work but with a class it will. So in the end they do have there benefits.
    That's not true. A Public member of a Public module is accessible outside an assembly just the same as Public members of Public classes. When compiled a module is implemented as a class so you ARE accessing a member of a class when you access a member of a module.

    This is all really simple. Static members are members that logically belong to a class and not an instance of that class. If every member of a class is like that then it is logical to declare the class static too. You don't have to, but it's logical. A static class is basically a collection of utility functions, generally all related to one area of functionality.

    Take the File and Directory classes in the .NET Framework for example. Nobody every creates a File object or a Directory object. All useful members of those two classes are static. As such it would have been logical to declare the classes themselves static. The authors chose not too for whatever reason. In fact, I don't think there's a static class in the Framework. That said, if creating an instance of a class cannot possibly be useful, as in the File and Directory classes, then declaring the class static is logical.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12
    Interweb adm/o/distrator Paul M's Avatar
    Join Date
    Nov 2006
    Location
    Australia, Melbourne
    Posts
    2,306

    Re: Static and non classes

    I don't believe it is, i have tried everything and it never works.

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Static and non classes

    Quote Originally Posted by Paul M
    I don't believe it is, i have tried everything and it never works.
    VB Runtime functions like MsgBox and InStr are declared in modules in the Microsoft.VisulaBasic.dll assembly. The fact that you can call them in your own code is proof enough.

    Have you actually declared your module(s) public? Classes are Public by default but modules are Friend by default, so you have to add the Public key word yourself. That's because modules should generally not be exposed publicly.
    Last edited by jmcilhinney; Feb 9th, 2008 at 02:01 AM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  14. #14
    Interweb adm/o/distrator Paul M's Avatar
    Join Date
    Nov 2006
    Location
    Australia, Melbourne
    Posts
    2,306

    Re: Static and non classes

    Yes thats what i do of course, it just never works. Those modules in the assembly could have been in a different language though?

  15. #15
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Static and non classes

    Quote Originally Posted by Paul M
    Yes thats what i do of course, it just never works. Those modules in the assembly could have been in a different language though?
    That makes no difference. All assemnlies are in MSIL. The language they were developed in makes no difference. If you reference an assembly in C# that was written in VB then any public modules will simply be seen as classes, because that's exactly what they are compiled as.

    I have attached a VS 2005 solution to this post. It contains a VB application, a C# application, a VB library and a C# library. Both applications have references to both libraries and both applications are able to access members of the C# class and the VB module. I don't know what you're doing wrong but public is public.

    I'll leave this topic alone now because it's well of the original topic of this thread.
    Attached Files Attached Files
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  16. #16
    Member
    Join Date
    Nov 2007
    Posts
    48

    Re: Static and non classes

    If I get the idea of Static classes right, then it would mean that that code Paul M posted...

    C# Code:
    1. static class CarTypeInfo
    2. {
    3.     public static string GetCarType() { return "cartype"; }
    4.     //etc..
    5. }
    Can simply be used like this?

    C# Code:
    1. CarTypeInfo.GetCarType();
    Without needing to make an instance of the class, like so?

    C# Code:
    1. CarTypeInfo myCar = new CarTypeInfo;
    (I'm rather new to C#, so this code might be off, but you'll get the idea).

  17. #17
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Static and non classes

    Quote Originally Posted by SanderK
    If I get the idea of Static classes right, then it would mean that that code Paul M posted...

    C# Code:
    1. static class CarTypeInfo
    2. {
    3.     public static string GetCarType() { return "cartype"; }
    4.     //etc..
    5. }
    Can simply be used like this?

    C# Code:
    1. CarTypeInfo.GetCarType();
    Without needing to make an instance of the class, like so?

    C# Code:
    1. CarTypeInfo myCar = new CarTypeInfo;
    (I'm rather new to C#, so this code might be off, but you'll get the idea).
    It's not a case of not needing to create an instance. It's the case that you specifically do not creat an instance. Static members aren't members that have a handy feature of not needing an instance to be created. They are specifically members of the class and not members of an instance, so they are called on the class and not on an instance. Your code is correct but your logic is not quite right.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

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