I've seen static methods written (but I've never run the code) which uses instance data from another class (instance based).
Usually, instance data work with instance methods and likewise for static fields/methods. What is the implication of working on static data in an instance method? I'm assuming it is frowned upon but I can't find any details on what will happen under the hood. Also, what about instance methods working with static data?
Thanks
There is no problem having a static method use object instances or an instance method using static data.
The framework is full of methods that demonstrates this. The very commonly used String.Concat method for example is a static method that takes one or more object instances. (A Concat method call is what the compiler produces whenever you use the + operator to concatenate strings.)
The Int32.MaxValue is a static property, there is obviously no problem using that in an instance method.
I don't see a problem working on instance data from another object within a static method.
I assume that you mean, for example, passing an object's instance variable to a static method via a parameter, and that method then working on that variable.
Static just means you don't get this, but you could get otherobject->something
I don't think it would be any more frowned upon than just using a static method would be in the first place.
When working with static data in an instance method, the only implication I can think of is synchronization in a multithreaded application. I can't think of any adverse implications when working with instance data from a static method. However, just because something can be done doesn't mean it should be done.
Here is a concrete example you provided.
Class A is instance based and has an
instance field called ProductPrice of
double. Class B is static and has a
static method called
PlayAroundWithPrice(double price), and
the coder passes in the ProductPrice
field.
Obviously, there is nothing technically illegal with this example, but it goes against the grain for me. First of all, the ProductPrice field of Class A is obviously public since Class B can operate on it. For the purposes of encapsulation, I personally always make fields private and use a public property to access them. Second, because ProductPrice is a public field instead of a public property, there's no way for Class A to prevent ProductPrice from being set to invalid values (negative values, for example). Third (as stated above), if this example occurs in a multithreaded program, there could be synchronization issues. Fourth, I guess this is the real rub, why have a static method on Class B to operate on the field of Class A? Why not put the static method on Class A?
I don't know that I'd go as far as making this a hard-and-fast rule (perhaps simply a rule-of-thumb), but I would restrict using static methods for when you do not want to pay for the cost of constructing an object just to use the method.
For example, in the project I work on, I have an IPHeader class that will fully construct an IPHeader instance from a byte buffer. However, in most cases, I only need a couple of values from the IPHeader. So to avoid the costs associated with creating and garbage-collecting an IPHeader instance, I added a couple of static methods that will extract the values from the byte buffer directly.
I hope I've understood your question correctly.
Basically, instance methods has a hidden this parameter which is used to pass the instance the method is supposed to work on. This is the reason static methods cannot access instance data without explicit reference (as they cannot know which instance of object they should access).
Considering this, I don't see any special difference between static and instance methods. They are both methods and has more similarities than differences.
Both static data and instance data are prone to threading issues, however, instances are much less likely to be used between threads. As a consequence, accessing static fields might require more care (regarding syncronization issues).
There should be no problem. Recently I had a scenario where I needed each instance of a class to have a different, but reproducible random seed. I kept a private static int in the class, and incremented it for every instantiation, and used that as the seed.
It worked fine.
I don't think there is anything inherently wrong with using static data in an instance method but I think you need to really limit the types of data you use. The advantage / disadvantage of this approach is that a single data change can alter the behavior of all objects of a particular type. This makes changing that type of data very risky. I tend to constrain uses of this to the following scenarios
Immutable values - Nothing can change so there is nothing to worry about
Global Objects - I strongly refrain from doing this but I've found that occasionally the evils of having a global object outweigh the risks. These objects are carefully monitored though and heavily tested.
Related
[Webmethod]
Public static string GetAge(List<int> input1, string input2)
{
Cust cu=Cust.CalAge(input1,input2)
cu.agemodify=true;
}
An AJAX call calls this Webservice.
CalAge is a static method inside class Cust.
agemodify is a boolean field inside class Cust.
I understand that all non static fields/local variables have
different copies on the stack per thread even in a static method. Is
that correct? So these are thread safe and are not shared resources.
agemodify is therefore thread safe?
My understanding is that List<int> is thread safe as a parameter
to a static method because for int, immutability doesn't apply. Is
that correct? I know list <T> isn't threadsafe. What about just
<T>s as parameters if T is immutable or Objects if they are
immutable? e.g. public static int GenMethod<TFirst,TSecond>(),
GetMethod(List<object> o1, object o2). Just Object vs
List<Object>. I don't want to use System.Collections.Concurrent.
My understanding is that because Webmethod is static, any classes
further down the stack need not be instantiated, and therefore,
might as well be static because there will only be one Webmethod
"instance" throughout. Is that correct? Is it better to have a
dedicated webservice (wcf/asmx) wrt thread safety instead of static
webmethods on an aspx page?
Unfortunately, your question is bordering on being too broad. You seem to be conflating several different and completely unrelated concepts, as if they somehow relate to each other in a meaningful way even though they don't. I'm skeptical that in the context of a Stack Overflow answer, it would be possible to unravel all of the misconceptions represented here.
That said, I'll make a try. At the very least, I hope that with the below, there is enough information that you can go back to review the primary sources (e.g. MSDN, other documentation) and correct your understanding. In the best case, perhaps the below is sufficient to get you entirely back on track.
I understand that all non static fields/local variables have different copies on the stack per thread even in a static method. Is that correct? So these are thread safe and are not shared resources. agemodify is therefore thread safe?
"Is that correct?" — No. It's borderline gibberish. A local variable declared in a method has a new instance, and hence a new copy of whatever value was passed or initialized in the method, for each call to the method. So, yes in the case of the local variable, each time the method is called in different threads, there are new copies, but this has nothing to do with the threads. It's all about the method call.
As for non-static fields, these may or may not be stored on the stack†, so any conclusion based on an assumption that they are stored on the stack is necessarily wrong. For reference types you only get a new copy for each instance of the object. For value types, you get a new copy of each field for each instance of the value type as well, but since you get a new instance of the value type each time it's assigned to a new variable, there can be many more copies. But again, nothing to do with threading, and nothing to do with the stack (since value types can exist either on the stack on the heap).
"agemodify is therefore thread safe?" — There is not enough code to answer that question. You would need to provide a good Minimal, Complete, and Verifiable code example for anyone to answer that definitively. If the Cust type is a reference type, and the CalAge() method always creates a new instance of the type, or the Cust type is a value type, then I would say that yes, the field is thread safe.
Otherwise, not necessarily.
† For that matter, that local variables are stored on the stack is just an implementation detail. It's not likely to change for regular local variables, but there's no requirement in C# that they be handled that way. They could be stored anywhere, as long as the compiler preserves the semantics of a local variable, and indeed this is exactly what happens in a variety of contexts in C#, such as captured local variables, and local variables found in special methods like iterator methods and async methods.
My understanding is that List<int> is thread safe as a parameter to a static method because for int immutability doesn't apply. Is that correct? I know List<T> isn't threadsafe. What about just <T>s as parameters if T is immutable or Objects if they are immutable? e.g. public static int GenMethod<TFirst,TSecond>(),
GetMethod(List<object> o1, object o2). Just Object vs List<Object>. I don't want to use System.Collections.Concurrent.
Again, all that mostly doesn't make any sense. The value of the input1 variable, being a local variable, is inherently thread safe because a new copy exists for each call to the method. But that's just the variable. The List<int> object itself is not affected by this at all, and is decidedly not thread-safe. Only if each thread executing the method gets a unique instance of the List<int> object could you say that would be thread-safe.
As for values of a type parameter T go, there is nothing about generics that would make these inherently thread-safe. As far as thread-safety is concerned, T is just another type. The fact that you don't know the type when the generic type or method is compiled is irrelevant, and does not in any way help make values of that type thread-safe.
My understanding is that because Webmethod is static, any classes further down the stack need not be instantiated, and therefore, might as well be static because there will only be one Webmethod "instance" throughout. Is that correct? Is it better to have a dedicated webservice (wcf/asmx) wrt thread safety instead of static webmethods on an aspx page?
Sorry, more mostly meaningless combinations of words. What is meant by "classes further down the stack"? If you call a method that needs to use a string value, for example, do you really think that means you get to use some mythical static version of the string type, just because the caller is static?
No, the rules about what needs to be static and what doesn't don't have much to do with the caller. The only thing the caller affects is that a non-static caller wouldn't need to provide an explicit instance reference to use other non-static members in the same class, because there's an implicit this reference in that context. Otherwise, a static method calling instance members still needs an instance reference. And if you can make members that the static method uses also be static, that is better because then you don't have to provide that instance.
But just because the caller itself is static, that doesn't automatically mean you get to avoid instantiating objects within the call context. If you need to access instance members of some type, you'll still need an instance of that type.
As far as the web service-specific stuff goes, that all depends on the nature of the values being used in your method. There's not enough context in your question to provide any sort of definitive discussion regarding that.
Straight up question: If I run code analysis, it tells me to make methods static even in nonstatic classes.
As far as I know, static methods are JITed and run on the Type-Object in the Heap. So wouldn't make a method static in a non static class mean, that the instance has to search the type object in the Heap and run the method there?
Wouldn't that mean a performance issue? Sure it would not be that big of a deal, but I'd still be interested on this.
No, it doesn't work like that.
A static method is actually (imperceptibly) more efficient than a non-static one because (a) it does not have a hidden "this" pointer passed to it and (b) because it's static, the framework doesn't have to do anything about it being virtual (although that last point also applies to non-virtual member methods too, of course).
Here is an in-depth article about CLR runtime type handling. In particular, look at the information there about the MethodTable and the Method Slot Table.
Here's another good article from Joe Duffy. It doesn't explicitly talk about static methods, but it does explain how method calls are made at the lowest (assembler) level, so you would be able to see why a static method call is efficient.
Good post about performance comparsion of static methods vs instance methods: Performance of static methods vs instance methods
TLDR:
Mostly the performance costs of instance vs static are below
negligible.
What costs there are will generally come where you abuse
static for instance or vice-versa. If you don't make it part of your
decision between static and instance, you are more likely to get the
correct result.
There are rare cases where static generic methods in another type
result in fewer types being created, than instance generic methods,
that can make it sometimes have a small benefit to turn rarely used
(and "rarely" refers to which types it's used with in the lifetime of
the application, not how often it's called). Once you get what he's
talking about in that article you'll see that it's 100% irrelevant to
most static-vs-instance decisions anyway.
I think the point is that you're not calling a static method upon an instance, but on the class itself. Any method that does not directly rely on instance information could (and based upon code analysis also should) be marked static and then be called like this:
NonstaticClass.TheStaticMethod();
instead if this
NonstaticClass inst = new NonstaticClass();
inst.TheStaticMethod();
This is because less overhead is required to look up and run a static method than a non-static method on a class instance.
I use static methods for things I really MEANT to be static. I use ReSharper for better code quality. Sometimes ReSharper suggests that a method can be made static.
When I got the following class:
public class WhatEverClass {
private string DoSomethingFancy(string input)
{
string fancyStuff;
// Fancy Stuff here
return fancyStuff;
}
public WhatEverClass() {
string awesome=DoSomethingFancy("some fancy string");
}
}
ReSharper might say "DoSomethingFancy can be made static".
I know it could be made static, but is there a good reason to really do this? Or should I just ignore these suggestions?
By defining a method static, so a procedure that computes something, you manifest an intent to a consumer of your API about statelessness of your function.
When we use static function, we do not expect it saves a state of computation or some computed internal value somewhere in it's internal static private variables, so the next call to that function may have different result even with the same parameters passed during the first call.
In short: whenever you see a function that just executes an action over parameter and not preserve some state, it is a good candidate for making it static.
If your method doesn't need to say or change the state of an instanciated object, then it should be static.
The usual notion is , if you are not creating an instance of anything, you could declare it static. As to where it should be used, ReSharper gives you suggestions based on standard programming practices. However, i take 'standard programming practices' with a grain of salt. Its a matter of personal programming preference for some. Here is a detailed reference on the topic :
http://msdn.microsoft.com/en-us/library/79b3xss3.aspx
Because you will invoke the WhatEverClass() method from outside the class by creating WhatEverClass instance. So the value for every instance will be different, because the variable is local, and will be created every time you create an instance of the class.
But if you want to keep the same value for all instances, then you can make it static so it will be created once in a memory and all instances will use it.
Beware the consequences of making a method static!
By making your method static, you make it that much harder for consumers to stub out your implementation of the algorithm and replace it with one of their own (obviously if the method is private you have no such worries).
Consumers of your static method have your implementation baked in to their code - they cannot use dependency injection to resolve a specific instance of your algorithm (without a bit of work). This makes their system that much harder to test, and in general lends itself to a less extensible code base.
If the method DoSomethingFancy does not use anything in the object WhatEverClass then it should, in my book, be made static since it does not in fact have anything to do with the object in which it is used.
I'm new to c sharp and programming generally. I have a quick question - what is best practise with regards to static/non static variables.
I have a variable,private int x, which belongs to class y. To access this variable, i need to reference y. If x was static however, i can access this variable with no references to y.
Which is the best way to go, in a situation whereby several methods within the class y will be referencing this value ?
Hope this makes sense, and my question isn't too basic !
Many thanks
You need to think about static variables as belonging to the class, not to instances of the class.
If, in all instances of the class this variable should be identical, use a static variable.
If not, use an instance variable.
In general having public static variables is bad practice - it is a shared global resource and if you change it you need to synchronize access to it. Having global state is something you want to avoid as much as possible.
Best practice is to avoid public static. In OOP, class is meant to hide its members. Static is actually not a member of the instance but of the type.
Static comes handy if you are implementing singleton pattern. But then again they need to be made private and accessible through a public property.
You need to read Static Classes and Static Class Members (C# Programming Guide).
Well I can't conclusively say that one is better, because they serve different purposes.
Are you familiar with OOP? In OOP, static objects or members of a class that can be accessed directly from the class, while non-static members can only be accessed from the instance it belongs to.
C# follows a similar principle for the methods. The static methods can by accessed directly from the class, while non-static methods (or instance methods as I like to call them) have to be accessed from an instance. That is why instatiating needs to be done for instance methods, while for static methods it's just not needed, and furthermore impractical (see below).
In OOP, static variables are used for values which cannot be stored by an instance variable. Example: supposed you wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?
The methods use a similar principle. They should be used for procedures for which it is impractical to do within an instance of a class. I tend to use them for broad procedures (not a technical term), meaning those that do not require me to instantiate an object. Example, adding two parameters. (This usage may or may not be correct, but I believe it is)
However, if you wanted to add two properties of an object, the method cannot be static, because as you would soon realize, static methods cannot access instance methods or variables within a class. Of course that makes sense because that static method would not know which instance of the class the get these from unless it were told, since it is not part of an instance itself)
For the sake of no further complicating things, I'll stop here. Let me know if you misunderstood anything.
Your choice depends on your architecture.
Static makes part of a Type, others make part of an instance of that type. If you want have some shared state (say) between different instances of the same type, use static. If you want that every instance have it's own value, independent from others, use instance fields.
In both cases, by the way, avoid to expose like a public fields, but use properties.
I completely agree with Mr Oded:
If, in all instances of the class this variable should be identical, use a static variable.
If not, use an instance variable.
Yes, adding static to a class member basically means you can access it without an instance, and only outside any instance. And yes, it becomes a global resource, or even a global variable if you will.
But I think there's at least another (heavily edited) good point to be made here...
Using static members as global vars go against OOP
This means once you set a static member you can't pass it around as an object. The more you use static as global var, the more difficult it is for unit testing / mocking classes.
There is a solution for that, Singletons. But they should never come without warnings!
At other hand, if you're sure you really need global vars, take a look at the Toolbox pattern. It's a not well known extension of Singleton pattern. It's so unknown in fact, if you google for it you won't find it with those keywords (toolbox pattern).
So plan ahead. Read more. Get to know about every option so you can decide better. Even get a book. Object Oriented Programming is more about applying concepts that will help in the long run than just making things work now.
In general if you want to have a variable public, either static or instance, you must wrap it in a property and expose it like that. This is for sure a principle that you will love to follow.
But despite some of the other answers I cannot say don't use static. Static is not the devil that you should avoid in any case. What you have to do will decide if you are going to use static or not, as long as you keep your program clean and easy to maintain.
Easily speaking, and not in the language of the elders, static stands for something that don't belong to any instance of this class but has an effect on them. An example of a static property in a class that generates instances is for example a factor, which should be global for all instances of the class, to take part in a calculation that is done inside instances. To this case, and to my opinion, it is better to have this factor declared as static rather that have it in every single instance. Especially if this factor changes in the lifetime of your program to affect the next calculation.
You need to ask a question to youself: why I need x to be static?
If you make x static it means that x is a part of all objects of class A, but when x is not static it means, than x is a part only of one object.
In geleral using of static fields is painfull for bug tracking, but in some cases this is very helpfull.
I suggest you to look in using of singelton http://en.wikipedia.org/wiki/Singleton
I found that there are two type of methods called static methods and instance methods and their differences.
But still I couldnt understand the advantages of one over another.
Sometimes i feel that static methods are not 100% object oriented.
Are there any performance differences between this two.
Can someone help?
In a perfect OO world there probably wouldn't be any need for static methods (I think Eiffel doesn't have them, either). But at the end of the day what matters is not OO-pureness of your code (C# has enough concepts that aren't strictly pure OO, like extension methods, for example) but rather what you're getting done.
You can use static methods for general helper methods (that don't need a general helper class or state on their own) or things like Color.FromARGB() which behave slightly contructor-like for value types.
In general, any method that doesn't touch an objects state (and therefore is more class-specific than object-specific) can be made static. Performance differences shouldn't really arise. Not very measurable, in any case. Jan Gray's great article Writing faster managed code: Know what things cost has some hard data on this, albeit to be taken with care.
The usefulness of a static method primarily comes when you need to call the method without ever instantiating the object. For example, maybe the static method is there to actually look up an existing instance and return it (an example being a singleton instance).
As others have stated, you can make any method static if it doesn't access state, and you'll get a tiny performance improvement.
If you actually want to be able to call the method on a specific instance though, and get the benefits of polymorphism (i.e. a derived class can override the behaviour of the method), then you should make the it an instance method.
If your classes implement interfaces, then the methods belonging to those interfaces must also be declared as instance methods.
Instance methods are tight to an instance. So you could see one advantage of static methods is not being tight to an instance. Static methods can (if visible) used by other objects to solve their problems. Sometimes this good and needed. Then you have to think about keeping your static methods in the same class or if you start building utility classes for broader use.
I wouldn't see the use of static methods of being "less OO". Static methods is one way to circumvent the shortcomings of OO (especially in single inheritance languages). You can call it a more functional approach (I know it isn't really).
Taking all this is just a bunch of questions that you should ask your code and that should determine if it is better an instance method, a static method of the same class or a static method of another class.
I wouldn't even think about performance issues. It will weaken your design and the difference isn't really that big. Performance is important if you have performance problems.
Instance methods require passing an implicit parameter (the this reference) which make them slightly slower than static methods. But that really should not be the reason to prefer them.
For a related discussion, look at:
Should C# methods that *can* be static be static?
If your method uses non-static data members, don't make it static (you "can't").
If your method does not use any non-static data members, you can make it static, but that mostly depends on your design rather than on whether it uses or not uses non-static members (there's not much difference in performance anyway as Mehrdad said).
If you have NO non-static data members in your class, sometimes it's a best practice to make all the methods static (like in the case of grouping helper functions under one class for the sake of good order).
I'm partially guessing based on the heritage of C# but I suspect it's the same as the other OO languages.
Static methods do not require an object to work on. A good example is something like:
Double pi = Math.PI.
Instance methods do require an object. An example is along the lines of:
Integer x = 9;
Integer y = x.sqrt();
Not all information belonging to a class should need an object instantiated for that class to get access to it. All those constants which can be used for creation of objects (Math.PI, Window.OVERLAPPED, etc) are prime examples of this.
No one is better than the other. It really depends on your requirement. Class methods are called when you want to apply a change to class as a whole. Whereas Instance methods are called when you are not applying change to the class but to a unique instance (object) of that class.
So I dont see a reason why one should be better than the other.