Hi,All
Can anyone tell me that which is a better approach in C#.net:
-Create static class and call its properties and methods directly
-Create public class and first instantiate the object then call them?
Thanks in Advance
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Asim SaeedPosted Jan 17, 2011, 10:28 AM
Thanks to all
knightsPosted Jan 14, 2011, 10:24 AM
If you are looking to call methods in an application from any where in the program.Then Static class is the option.
Otherwise if the desin requirement is that you need a class in a seprate file and your main application will be creating different objects OBJ1,OBJ2 etc and you are looking to process each object seprately on different methods then you need to have a public class.
Perfomance wise read the following, courtesy of [http://www.velocityreviews.com/forums/t117353-advantages-of-static-vs-instance-methods.html]
The reason why static functions are faster is because of the way programming languages implement objects. For example, suppose class A has function void f() that increments a variable of class A called "counter". When the compiler processes class A is, it creates the code of function f() only once; there is no need to create this code for each instance. Therefore, when the program runs there is only one copy of f() in the memory. When the programmer invokes x.f() and y.f(), how does the code know which copy of f() to run? Well, since there is only one f(), the same function is run all the time. But, you wonder, how does the code know which "counter" to increase. What you do not see is that the function f() actually takes an additional parameter called "this". The "this" pointer tells f() on which instance it should operate. The "this" pointer is added by the compiler by default. Now, in this example, the "this" pointer cannot be resolved at compile time. For example, the program can have an "if-statement" such that the address of x can be one of several options. In other words, the compiler does not know where instance "x" will sit in the memory. Hence, the compiler will have to resolve the address in run time. This takes time.
With static functions, on the other hand, no "this" pointer is passed because the function can be called without an instance. Even if there is an instance x of class A and you call the static function g() of that instance as in x.g(), it will be equivalent to A.g() because g() is not allowed to use any instance variables (only static variables of the class). In other words, there is no resolution process taking place at run time. Hence, static methods are faster and should be chosen when possible.
Dorababu MekaPosted Jan 14, 2011, 6:55 AM
Asim SaeedPosted Jan 14, 2011, 6:54 AM
Thanks
Dorababu MekaPosted Jan 14, 2011, 6:01 AM