Static Class or Objects [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When to Use Static Classes in C#
sorry if the question is meaningless or stupid am trying to create a windows service in which i have few class files each class file has some functions that calls another class file.
For example
class file one has a method to create email like
public bool CreateEmail()
{
try
{
//code here
}
catch (Exception ex)
{
//Write to Log
to create log call function from **another class file**
}
}
and many more calls like this.I would like to know if Using static class is better or creating object for each class and calling the methods will be better.Which is the recommended way?

Ask yourself
How relevant is this method to your object.
Does it alter the state of your object in anyway.
If its relevant and does change your object state ,then you should have the method inside the class.If not then you dont need to have that method in your class
In your case from the look of it,its quite clear that its not going to alter any state,rather it needs some information from the other object to send the mail.So i would definitely make this a util class(static class) and use it whenever i need.

Think about:
Do you need to do unit test, if yes, static class is not good and cannot be mocked in case you follow design for test ability.
Single responsibility principle, don't put every method into one so-called utility class. Group methods in separate classes which are relevant together and follow SRP.
Classes should have meaningful names. Utility, util or helper are not meaningful names

If you are only using the class files to group the methods, and wont be needing instances of the class for anything other than calling those methods, then you should use a static class - thats what they are for.

I would like to know if Using static class is better or creating object for each class and calling the methods will be better.
If it is a multi-threaded environment and logging requires some data to be shared across multiple calls, Create separate instance for each call. otherwise, go for static class and methods.

Related

What is the benefit of using a static method over a normal method without a class?

im pretty new to C# and i was a little confused about the use of static methods over regular methods. From what i understand, the only benefit they offer is that they require no object in order to be called. But if thats the case, wouldn't it just be more convenient not to assign this method to a class and to define it in the main program page. Is there any real benefit to static methods?
Edit: What i mean by "wouldn't it be more convenient not to assign this method to a class" is to not create a seperate class where i can put this new method in. Wouldn't it just be more convenient to keep this method in the main program's class.
If you define it in the "main program page" it wouldn't be as easy to use throughout the application, it would only be available from that 1 file.
Imagine you have a static class MyStaticClass, you could then use those functions throughout the application, not only on the main program file, but in any file, etc.
MyStaticClass.MyStaticMethod();
in a standard class you would have to do something like
new MyClass().MyMethod();
in other words the reason for a "static" is that you do not have to "new" an instance of the object.
In Addition to answer of JBoothUA, I can say if you are writing some common method that doesn't below to your domain class. Each class can use that method (like some conversation logic...) should be static.
Whenever you are calling method with new classname.methodname each and every time new instance of class created. That occupying disk memory.
While calling static method didn't require any more space

Whether to use static class or not [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I will write code in which I need class which holds methods only. I thought it is good idea to make class static. Some senior programmer argue that do not use static class. I do not find any good reason why not to use static class. Can someone knows in C# language there is any harm in using static class. Can static class usage required more memory than creating object of class? I will clear that my class do not have single field and hence property too.
For further information I will explain code also.
We have product in which we need to done XML handling for chart settings. We read object from XML file in class Library which holds chart related properties. Now I have two Layers first is product second class Library and XML related operations. Actually senior programmers want independent class to read and write XML. I make this class static.
In another situation I have class of chartData. In that class I want methods like whether Line of Axis,series of chart is valid or not. Also whether color of chart stores in ARGB format or plain color name. They do not want those methods in same project. Now can I make class static or create object.
If your class does not have to manage state then there is absolutely no reason to not declare it static.
In C# some classes even have to be static like the ones that have extension methods.
Now if there's a chance that it requires state in the future, it's better to not declare it as static as if you change it afterwards, the consumers will need to change their code too.
One concern is that statics can be harder (not impossible) to test in some situations
The danger of static classes is that they often become God Objects. They know too much, they do too much, and they're usually called "Utilities.cs".
Also, just because your class holds methods only doesn't mean that you can't use a regular class, but it depends on what your class does. Does it have any state? Does it persist any data that's being modified in your methods?
Having static classes is not bad, but could make you think why you have those methods there. Some things to keep in mind about that:
if the methods manage behavior for classes you have in your project, you could just add the methods to those classes directly:
//doing this:
if(product.IsValid()) { ... }
//instead of:
if(ProductHelper.IsValid(product)) { ... }
if the methods manage behavior for classes you can't modify, you could use extension methods (that by the end of the day are static! but it adds syntactic sugar)
public static bool IsValid( this Product product ) { ... }
//so you can do:
if(product.IsValid()) { ... }
if the methods are coupled to external services you may want to mock, using a non-static class with virtual methods or implementing an interface will let you replace the instance with a mock one whenever you need to use it:
//instead of:
StaticService.Save(product);
//you can do:
public IService Service {get;set;}
...
Service.Save(product);
//and in your tests:
yourObject.Service = new MockService(); //MockService inherits from your actual class or implements the same IService interface
by the other hand, having the logic in non-static classes will let you make use of polymorphism and replace the instance with another one that extends the behavior.
finally, having the logic in non-static classes will let you use IoC (inversion of control) and proxy-based AOP. If you don't know about that, you could take a look at frameworks like Spring.net, Unity, Castle, Ninject, etc. Just for giving you an example of what you could do with this: you can make all the classes implementing IService log their methods, or check some security constraints, or open a database connection and close it when the method ends; everything without adding the actual code to the class.
Hope it helps.
It depends on the situation when to use static classes or not. In the general case you create static classes when you do not need to manage state. So for example, Math.cs, or Utility.cs - where you have basic utility functions - eg string formatting, etc.
Another scenario where you want to use static is when you expect the class to not be modified alot. When the system grows and you find that you have to modify this static class alot then its best to remove the static keyword. If not then you will miss out on some benefits of OOD - eg polymorphism, interfaces - For example you could find that I need to change a specific method in a static class, but since you can't override a static method, then you might have to 'copy and paste' with minor changes.
Some senior programmer argue that do not use static class.
Tell him he is a traineee, not even a junior. Simple. The static keyword is there for a reason. if your class only has methods without keeping state - and those cases exist - then putting them into a static class is valid. Point.
Can someone knows in C# language there is any harm in using static class.
No. The only valid argument is that your design isbroken (i.e. the class should not be static and keep state). But if you really have methods that do not keep state - and those cases exist, like the "Math" class - then sorry, this is a totally valid approach. There are no negatives.

Static Class inside Normal class for ASP.Net

I know that making a class static in a ASP.Net project will cause that class's runtime properties to be available to all sessions on the web server.
My question is this: If I declare nested classes static, but the container not, does the sharing of the classes across sessions still apply?
Example:
public class FooContainer
{
public static class Bar
{
}
public static class dog
{
}
}
Yes; a static nested class has the same behaviour as any other static class. The only time nested classes behave differently is when the outer class is generic type (the nested type is then implicitly generic via the parent, so FooContainer<X>.Bar would be independent of FooContainer<Y>.Bar).
And just be careful: static for sharing data between sessions is fraught with danger. Synchronize like a paranoid thing. Personally I would need a very good reason to do this... and it needs careful implementation. I only use that approach for things like configuration caching, and even then I'm insanely careful about it.
Ultimately, yes.
The nested static classes are compiled just the same as root-level static classes (Marc wisely notes subtle differences where generics are involved) - the only difference is the qualifying of the path of the type, but this is only natural in any environment and not a side-effect at all.
When I see someone say "static data" and "ASP.NET" in the same sentence all sorts of alerts go off.
Yes, as Marc said, static classes will be static even if they are nested, you just need to call them via the containing class
MyStaticClass.StaticField = 3; ///wont work
MyInstanceClass.MyStaticClass.StaticField = 3; // works
Any instantiable class can have static methods/properties/constructors, making a class explicitly static just has the added benefit that you can't make something non-static my mistake, clarifying the purpose and intent of the class.
But beware, static classes in ASP.net are trully static on an application level, so if you have multiple users, they will all see the same static data, regardless of authorizations, and a change of that data will affect all users who use it.
So a static variable might be the right place to put something that is read once from the db, and then just displayed, i.e. the current version of the application, or the application's start time, but it's a very wrong place to put user-specific data like language preferences, usernames, etc, etc...

Regarding Static class in c# [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When to Use Static Classes in C#
why anyone would write a static class. we can declare a static method in any class and just call that method without creating class instance. so please tell me in what type of situation a person would create a static class and also tell me what are the main differences between static class and normal class.
thanks
A static class cannot be instantiated. It's main uses are to make it clear that the class has no instance methods and to prevent people from accidentally trying to "new" the class.
Generally I would advise you not to write static classes.
There are cases where you want them though
Extension methods have to live on static classes. This is the best reason to have a static class.
If you do have a bunch of static methods that don't make sense as extension methods and don't fit into your object model then there might be room for a collection of static methods. This is particularly the case when you cannot redesign your app.
Sometimes this happens because you are dealing with some 3rd party stuff that you cannot change. Then if you end up with a class with only static methods on it - you should make it static since anyone creating an instance is clearly not understanding what you have done.
Having said all of that for the most part my advices is avoid static methods, classes and data. I am not saying never use them - just try not to.
A static class cannot contain any constructors, only a static constructor that is called first time one of its members is accessed.
That is basically the difference. Performance wise we also get another for free by the compiler since it can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are also sealed and therefore cannot be inherited.
http://msdn.microsoft.com/en-us/library/79b3xss3(v=VS.100).aspx
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type.
Another valid point is that Extension Methods has to be declared in a static class
http://en.wikipedia.org/wiki/Extension_method
The new language feature of extension methods in C# 3.0, however, makes the latter code possible. This approach requires a static class and a static method.
In static class all method all static. we can not declare normal method in static class.
differences between static class and normal class.
We can not create object of static class, when we use method of static class just use classname.MethodName but in normal class we have to first create object of class then we can access method of normal class.
static class ex.
Class1.functionname();
normal class ex.
Class1 cs = new class1();
cs.functionname();
functionname should not be private.
The difference is that you can't instantiate a static class. So you'd make a class static if you don't want it ever being instantiated. This is useful in cases when you're dealing with threading issues, and you want all threads to be guaranteed to use the same instance of your class.
A more philosophical scenario is when you have a class that doesn't need to be instantiated, such as (for example) you're building a database application and you create one class to do all the database access stuff. It's basically just a collection of methods. Then making the class static simply becomes a step to make your design more consistent.

C# share code between classes

In Visual Studio 2008 using C#, what is the best way to share code across multiple classes and source files?
Inheritance is not the solution as the classes already have a meaningful hierarchy.
Is there some neat feature that's like a C include file that let's you insert code anywhere you want in another class?
EDIT:
ok, i guess we need a concrete example...
There are several hundred classes in the domain with a well thought out class heirarchy. Now, many of these classes need to print. There is a utility printer class that handles the printing. Let's say there are 3 different print methods that are dependent on the class that is being printed. The code that calls the print method (6 lines) is what I'm trying to avoid copying and pasting across all the different client class pages.
It'd be nice if people wouldn't assume they knew more about the domain that the op - especially when they specifically mention techniques that don't fit...
If you have functionality that you use frequently in classes that represent very different things, in my experience that should fall into just a few categories:
Utilities (e.g. string formatting, parsing, ...)
Cross-cutting concerns (logging, security enforcement, ...)
For utility-type functionality you should consider creating separate classes, and referencing the utility classes where needed in the business class.
public class Validator
{
public bool IsValidName(string name);
}
class Patient
{
private Validator validator = new Validator();
public string FirstName
{
set
{
if (validator.IsValidName(value)) ... else ...
}
}
}
For cross-cutting concerns such as logging or security, I suggest you investigate Aspect-Oriented Programming.
Regarding the PrintA vs. PrintB example discussed in other comments, it sounds like an excellent case for the Factory Pattern. You define an interface e.g. IPrint, classes PrintA and PrintB that both implement IPrint, and assign an instance of IPrint based on what the particular page needs.
// Simplified example to explain:
public interface IPrint
{
public void Print(string);
}
public class PrintA : IPrint
{
public void Print(string input)
{ ... format as desired for A ... }
}
public class PrintB : IPrint
{
public void Print(string input)
{ ... format as desired for B ... }
}
class MyPage
{
IPrint printer;
public class MyPage(bool usePrintA)
{
if (usePrintA) printer = new PrintA(); else printer = new PrintB();
}
public PrintThePage()
{
printer.Print(thePageText);
}
}
You can't just load in code that you'd like to have added into a class in C# via a preprocessor directive like you would in C.
You could, however, define an interface and declare extension methods for that interface. The interface could then be implemented by your classes, and you can call the extension methods on those classes. E.g.
public interface IShareFunctionality { }
public static class Extensions
{
public static bool DoSomething(this IShareFunctionality input)
{
return input == null;
}
}
public class MyClass : Object, IShareFunctionality
{
public void SomeMethod()
{
if(this.DoSomething())
throw new Exception("Impossible!");
}
}
This would allow you to reuse functionality, but you cannot access the private members of the class like you would be able to if you could, say, hash include a file.
We might need some more concrete examples of what you want to do though?
A C# utility class will work. It acts like a central registry for common code (or like the VB.NET Module construct) - it should contain code that's not specific to any class otherwise it should have been attached to the relevant class.
You don't want to start copying source code around if you don't have to because that would lead to code update problems considering the duplication.
As long as the source doesn't need to retain state, then use a static class with static method.
static public class MySharedMembers {
static public string ConvertToInvariantCase(string str) {
//...logic
}
// .... other members
}
If the classes are in the same namespace, there's no need for an include analog. Simply call the members of the class defined in the other function.
If they're not in the same namespace, add the namespace of the classes you want to use in the usings directives and it should work the same as above.
I'm confused by the question: it seems you need to work on your basic OO understanding.
Checkout extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx
I don't know of a way to include portions of files but one thing we do frequently is to add an existing file and "link" it from its current location. For example, we have an assemblyInfo.cs file that every project refers to from a solution directory. We change it once and all the projects have the same info because they're referring to the same file.
Otherwise, suggestions about refactoring "common" routines in a common.dll are the best thing I've come up with in .Net.
I am not sure exactly what you mean by a "meaningful" structure already, but this sounds like a place where you could use base class implementation. Though not as "verbose" as C++ multiple inheritance, you might get some benefit out of using chained base class implementation to reuse common functions.
You can preserve class hierarchy, at least visually and override behavior as needed.
Pull out the repetitive code into services. The repetitive code is a clue that there might be some room for refactoring.
For example, create a "PrintingService" which contains the logic needed to print. You can then have the classes that need to print have a dependency on this service (either via the constructor or a parameter in a method which requires the service).
Another tip i have along these lines is to create interfaces for base functionality and then use the interfaces to code against. For example, i had bunch of report classes which the user could either fax, email, or print. Instead of creating methods for each, i created a service for each, had them implement an interface that had a single method of Output(). I could then pass each service to the same method depending on what kind of output the user wanted. When the customer wanted to use eFax instead of faxing through the modem, it was just a matter of writing a new service that implemented this same interface.
To be honest I can't think of anything like includes in Visual C#, nor why you would want that feature. That said, partial classes can do something like it sounds what you want, but using them maybe clashes against your "classes already have a meaningful hierarchy" requirement.
You have many options, TT, extension method, delegate, and lambda

Categories

Resources