Static keyword proper usage? - c#

Regarding the static keyword.
Up to this point, via my own research, I have a general idea of what the static keyword is, but I feel that all these different descriptions and details have only confused me more. At the moment, I really don't feel that I know how to properly use "static"; it seems to be used differently between C# and VB.NET and applies differently within the language depending on what you are using it for…
While reading the MSDN article Static (Visual Basic) , many questions arose, specifically when I read this sentence:
Normally, a local variable in a procedure ceases to exist as soon as the procedure terminates. A static variable remains in existence and retains its most recent value.
Is the VB.NET version of static the same as C# or Java, is the concept the same for most languages?
If static retain a value within a class, and we are able to access that certain member, function without instantiating the class, is this safe to use loosely? In other words, should we keep a close eye when using static’s within classes? They remind me of global variables for some reason. Maybe I’m just being ignorant here and simply need more practice to understand their purpose.
What are good scenarios where using static benefits and promotes reusability of code?

In C# the static keyword is the same as the shared keyword in VB.NET. Namely, from Static Classes and Static Class Members (C# Programming Guide):
Static classes and class members are used to create data and functions
that can be accessed without creating an instance of the class.
In VB.NET static works very differently, as it applies to variables, not types.
I do not know if there is a C# equivalent for this behavior.
1) Is the VB.NET version of static the same as C# or Java, and is the concept
the same for most languages?
It's different. shared is the same, though.
2) If static retain value within a class, and we are able to access
that certain member, function without instantiating the class – Is
this safe to use loosely? In other words, should we keep a close eye
when using static’s within classes? They remind me of global
variables for some reason, maybe I’m just being ignorant here and
simply need more practice to understand their purpose.
Be very careful, they are global to the application domain.
3) What are good scenarios where using static benefits and promotes
reusability of code?
I use static lists to cache sets of data that are used to populate dropdown lists so that I don't have to keep hitting SQL Server as one example.

The other answers dealt with the C# usages of static, so I'll talk about Static in VB.NET since you referenced an MSDN article about it. When you make a Static local variable in VB.NET, the compiler will translate that to a class-level variable that can only be referenced by code in the function in which the variable is declared in code. Whether said variable is instance or shared depends on the containing function. For example, this code:
Public Class StaticTest
Public Function Process(value As Integer) As Integer
Static lastValue As Integer
Dim result As Integer
If value > 0 Then
result = value
lastValue = value
Else
result = lastValue
End If
Return result
End Function
End Class
Decompiles to something like this:
Public Class StaticTest
' Methods
<DebuggerNonUserCode> _
Public Sub New()
End Sub
Public Function Process(ByVal value As Integer) As Integer
If (value > 0) Then
Dim result As Integer = value
Me.$STATIC$Process$20188$lastValue = value
Return result
End If
Return Me.$STATIC$Process$20188$lastValue
End Function
' Fields
Private $STATIC$Process$20188$lastValue As Integer
End Class
I noticed that if I set lastValue to value on entrance into the function, the compiler also created some sort of initialization code and extra fields, so there are some cases where Static locals do generate some extra code.
I would recommend avoiding using Static locals because I find them more confusing then helpful when compared to the alternative, actually declaring a class-level instance variable. The tradeoffs of Statics are:
For:
Cannot be accessed in another function
Against:
Cannot be initialized in constructor (but can be initialized inline with their declaration, which gives the extra init field/code I mentioned above)
Cannot be located according to your typcial placement of class locals in code
Look like locals but are not

VB.NET's shared is the same as C#'s static. C#'s static is pretty much the same as static in Java and most other languages. The concepts carry over.
This is a yes and no kind of question. You don't want to just randomly throw statics around without knowing what you're doing. However, they can be useful for a lot of situations (more on that in #3). They are not really like global variables because they are still "namespaced" and organized by the class they belong to.
Static members are typically used for utility methods and classes. For example, C# implements most of the Math library as static methods, since they're just doing computations and have no other side effects. As a general rule, if your method has no side effects, and all of the data it needs to do its job comes in as parameters. You can also use static properties if you want to share some data between instances of a class (for example, to track how many times a given method has been called, or something similar). Static also has some memory usage benefits, since it allows you to create only one instance of a class or method to share throughout the application, rather than creating new copies for each usage. You also use static classes for extension methods, but that's a whole other discussion.
You didn't ask specifically, but it's worth mentioning the downsides. The biggest reason to avoid static is maintainability. You cannot inherit or extend static classes easily, which is a major thing to think about. So long as you stick to the composition over inheritance rule, this isn't necessarily a deal-breaker, but the lack of inheritance and polymorphism for static classes is a major drawback. That one issue by itself leads a lot of people to suggest avoiding static in all cases.

Related

Is there reason why you can't declare a static variable within a C# method?

I've been working in C for the past couple of years and I've managed to get use to putting single-purpose, static variables near where they are used within my code.
While writing a very basic method that was in need of a method-scope static value, I was a bit surprised to find that the compiler didn't like that I tried to define a static object from within my method.
Googling has verified that this isn't possible within C#. Still, I'm curious why code, like the following, is completely off limits.
public int incrementCounterAndReturn()
{
static int i = 0;
return ++i;
}
Granted, this is a simplistic example that could be redefined for the same affect but that's beside the point. Method-scope, static values have their place and purpose. What design decisions have prevented such an implementation of static objects within C#?
We're on C# version 5.0 and it's 2013. I can only assume this isn't possible because of a design choice and not just because "that's complex and hard stuff to implement." Does anyone have any insider information?
The language design team is not required to provide a reason to not implement a feature. Rather, the person who wants the feature is required to make the case that the feature is the best possible way the design, implementation, test, and education teams can be spending their budgets. No one has ever successfully done so for your proposed feature.
Were I still on the design team and had this feature pitched I would point out that it is completely unnecessary. The feature in C is a known cause of developer confusion, particularly for novices, and the benefit of local vs type scope is tiny.
The underlying runtime does not provide method level static variables. In the CLR, all "static" data is defined on the type level, not method level. C# decided to not add this at the language level in its language design.
This is purely a design choice. VB.Net, which compiles to the same IL, does allow this via the Shared keyword in a Function or Sub statement (though it's handled via the compiler "promoting" the variable to a class level static variable).
Because in the CLR, static variables are associated with the TYPE. Storage for them is tied to the Type (class or stuct) they are associated with.
static variables are scoped to the class, not to an object instance. To make this work, your method must be declared static, and I believe your class must also be static (since instantiation is not relevant).
But the variable itself must be declared at the class level. C# doesn't allow you to create method-local static variables.
Worth noting: these kinds of maneuvers make it very difficult to unit test the method properly. Normally in C# one would make an ordinary class to hold such state; in fact, that's exactly how yield return works behind the scenes.
The .NET framework and languages were designed around the concept that anyone who is going to be compiling an assembly should be considered trustworthy enough to have access to all the code therein. From a semantic point of view, declaring a static variable foo within method bar would be equivalent to declaring a private static variable outside the method and accessing it within the method, provided only that one chooses as a name something which isn't used anywhere else. If one by convention combines the method name and meaning (e.g. bar_foo) one can generally avoid naming collisions pretty easily. Since the semantics are equivalent to having the variable declared outside the method, there's no need to have it declared inside.

Performance of static methods vs instance methods

My question is relating to the performance characteristics of static methods vs instance methods and their scalability. Assume for this scenario that all class definitions are in a single assembly and that multiple discrete pointer types are required.
Consider:
public sealed class InstanceClass
{
public int DoOperation1(string input)
{
// Some operation.
}
public int DoOperation2(string input)
{
// Some operation.
}
// … more instance methods.
}
public static class StaticClass
{
public static int DoOperation1(string input)
{
// Some operation.
}
public static int DoOperation2(string input)
{
// Some operation.
}
// … more static methods.
}
The above classes represent a helper style pattern.
In an instance class, resolving the instance method take a moment to do as oppose to StaticClass.
My questions are:
When keeping state is not a concern (no fields or properties are required), is it always better to use a static class?
Where there is a considerable number of these static class definitions (say 100 for example, with a number of static methods each) will this affect execution performance or memory consumption negatively as compared with the same number of instance class definitions?
When another method within the same instance class is called, does the instance resolution still occur? For example using the [this] keyword like this.DoOperation2("abc") from within DoOperation1 of the same instance.
In theory, a static method should perform slightly better than an instance method, all other things being equal, because of the extra hidden this parameter.
In practice, this makes so little difference that it'll be hidden in the noise of various compiler decisions. (Hence two people could "prove" one better than the other with disagreeing results). Not least since the this is normally passed in a register and is often in that register to begin with.
This last point means that in theory, we should expect a static method that takes an object as a parameter and does something with it to be slightly less good than the equivalent as an instance on that same object. Again though, the difference is so slight that if you tried to measure it you'd probably end up measuring some other compiler decision. (Especially since the likelihood if that reference being in a register the whole time is quite high too).
The real performance differences will come down to whether you've artificially got objects in memory to do something that should naturally be static, or you're tangling up chains of object-passing in complicated ways to do what should naturally be instance.
Hence for number 1. When keeping state isn't a concern, it's always better to be static, because that's what static is for. It's not a performance concern, though there is an overall rule of playing nicely with compiler optimisations - it's more likely that someone went to the effort of optimising cases that come up with normal use than those which come up with strange use.
Number 2. Makes no difference. There's a certain amount of per-class cost for each member it terms of both how much metadata there is, how much code there is in the actual DLL or EXE file, and how much jitted code there'll be. This is the same whether it's instance or static.
With item 3, this is as this does. However note:
The this parameter is passed in a particular register. When calling an instance method within the same class, it'll likely be in that register already (unless it was stashed and the register used for some reason) and hence there is no action required to set the this to what it needs to be set to. This applies to a certain extent to e.g. the first two parameters to the method being the first two parameters of a call it makes.
Since it'll be clear that this isn't null, this may be used to optimise calls in some cases.
Since it'll be clear that this isn't null, this may make inlined method calls more efficient again, as the code produced to fake the method call can omit some null-checks it might need anyway.
That said, null checks are cheap!
It is worth noting that generic static methods acting on an object, rather than instance methods, can reduce some of the costs discussed at http://joeduffyblog.com/2011/10/23/on-generics-and-some-of-the-associated-overheads/ in the case where that given static isn't called for a given type. As he puts it "As an aside, it turns out that extension methods are a great way to make generic abstractions more pay-for-play."
However, note that this relates only to the instantiation of other types used by the method, that don't otherwise exist. As such, it really doesn't apply to a lot of cases (some other instance method used that type, some other code somewhere else used that type).
Summary:
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. Edit: And it mostly only has that cost with ngen, not with jitted code.
Edit: A note on just how cheap null-checks are (which I claimed above). Most null-checks in .NET don't check for null at all, rather they continue what they were going to do with the assumption that it'll work, and if a access exception happens it gets turned into a NullReferenceException. As such, mostly when conceptually the C# code involves a null-check because it's accessing an instance member, the cost if it succeeds is actually zero. An exception would be some inlined calls, (because they want to behave as if they called an instance member) and they just hit a field to trigger the same behaviour, so they are also very cheap, and they can still often be left out anyway (e.g. if the first step in the method involved accessing a field as it was).
When keeping state is not a concern (no fields or properties are
required), is it always better to use a static class?
I would say, yes. As declaring something static you declare an intent of stateless execution (it's not mandatory, but an intent of something one would expect)
Where there is a considerable number of these static classes (say 100
for instance, with a number of static methods each) will this affect
execution performance or memory consumption negatively as compared
with the same number of instance classes?
Don't think so, unless you're sure that static classes are really stateless, cause if not it's easy mess up memory allocations and get memory leaks.
When the [this] keyword is used to call another method within the same
instance class, does the instance resolution still occur?
Not sure, about this point (this is a purely implementation detail of CLR), but think yes.
Static methods are faster but less OOP. If you'll be using design patterns, static method is likely bad code. Business logic are better written as non-Static. Common functions like file reading, WebRequest etc are better as static. Your questions have no universal answer.

Usage of Instance Variable within the class for Java/C#

Assume that 2 different methods - one static and one non-static - need an instance variable.
The variable is used 3-5 different times within the methods for comparison purposes.
The variable is NOT changed in any manner.
Also would the type of variable - String, Colection, Collection, etc. make any difference on how it should be coded.
What is the best/right way of using Instance Variable within a private method (static and non-static)?
Pass as method argument
Store locally by using the method to get the value - this.getClaimPropertyVertices();
Store locally by getting the value - this.claimPropertyVertices;
Use the instance variable directly in the method
When creating a local variable to store the value will the "final" keyword provide any advantages, if the variable will not be changed.
Edit 1: Based on a comment, I am adding additional information
The value cannot be created locally in the method. It has to come from the class or some other method accessed by the class.
My Solution Based on the Answers:
Based on the answer by #EricJ. and #Jodrell. I went with option 1 and also created it as a private static method. I also found some details here to support this.
When creating a local variable to store the value will the "final" keyword provide any advantages, if the variable will not be changed
In Java, final provides an optimization opportunity to the compiler. It states that the contents of the variable will not be changed. The keyword readonly provides a similar role in C#.
Whether or not that additional opportunity for optimization is meaningful depends on the specific problem. In many cases, the cost of other portions of the algorithm will be vastly larger than optimizations that the compiler is able to make due to final or readonly.
Use of those keywords has another benefit. They create a contract that the value will not change, which helps future maintainers of the code understand that they should not change the value (indeed, the compiler will not let them).
What is the best/right way of using Instance Variable within a private method (static and non-static)?
Pass as method argument
The value is already stored in the instance. Why pass it? Best case is this is not better than using the instance property/field. Worst case the JITer not inline the call, and will create a larger stack frame costing a few CPU cycles. Note: if you are calling a static method, then you must pass the variable as the static method cannot access the object instance.
Store locally by using the method to get the value - this.getClaimPropertyVertices();
This is what I do in general. Getters/setters are there to provide a meaningful wrapper around fields. In some cases, the getter will initialize the backing field (common pattern in C# when using serializers that do not call the object constructor. Don't get me started on that topic...).
Store locally by getting the value - this.claimPropertyVertices;
No, see above.
Use the instance variable directly in the method
Exactly the same as above. Using this or not using this should generate the exact same code.
UPDATE (based on your edit)
If the value is external to the object instance, and should not meaningfully be stored along with the instance, pass it in as a value to the method call.
If you write your functions with the static keyword whenever you can, there are several obvious benefits.
Its obvious what inputs effect the function from the signature.
You know that the function will have no side effects (unless you are passing by reference). This overlooks non-functional side effects, like changes to the GUI.
The function is not programtically tied to the class, if you decide that logically its behaviour has a better association with another entity, you can just move it. Then adjust any namespace references.
These benefits make the function easy to understand and simpler to reuse. They will also make it simpler to use the function in a Multi Threaded context, you don't have to worry about contention on ever spreading side effects.
I will cavet this answer. You should write potentially resuable functions with the static keyword. Simple or obviously non-resulable functionality should just access the private member or getter, if implemented.

more advantages or disadvantages to delegate members over classic functions?

class my_class
{
public int add_1(int a, int b) {return a + b;}
public func<int, int, int> add_2 = (a, b) => {return a + b;}
}
add_1 is a function whereas add_2 is a delegate. However in this context delegates can forfill a similar role.
Due to precedent and the design of the language the default choice for C# methods should be functions.
However both approaches have pros and cons so I've produced a list. Are there any more advanteges or disadvantages to either approach?
Advantages to conventional methods.
more conventional
outside users of the function see named parameters - for the add_2 syntax arg_n and a type is generally not enough information.
works better with intellisense - ty Minitech
works with reflection - ty Minitech
works with inheritance - ty Eric Lippert
has a "this" - ty CodeInChaos
lower overheads, speed and memory - ty Minitech and CodeInChaos
don't need to think about public\private in respect to both changing and using the function. - ty CodeInChaos
less dynamic, less is permitted that is not known at compile time - ty CodeInChaos
Advantages to "field of delegate type" methods.
more consistant, not member functions and data members, it's just all just data members.
can outwardly look and behave like a variable.
storing it in a container works well.
multiple classes could use the same function as if it were each ones member function, this would be very generic, concise and have good code reuse.
straightforward to use anywhere, for example as a local function.
presumably works well when passed around with garbage collection.
more dynamic, less must be known at compile time, for example there could be functions that configure the behaviour of objects at run time.
as if encapsulating it's code, can be combined and reworked, msdn.microsoft.com/en-us/library/ms173175%28v=vs.80%29.aspx
outside users of the function see unnamed parameters - sometimes this is helpfull although it would be nice to be able to name them.
can be more compact, in this simple example for example the return could be removed, if there were one parameter the brackets could also be removed.
roll you'r own behaviours like inheritance - ty Eric Lippert
other considerations such as functional, modular, distributed, (code writing, testing or reasoning about code) etc...
Please don't vote to close, thats happened already and it got reopened. It's a valid question even if either you don't think the delegates approach has much practical use given how it conflicts with established coding style or you don't like the advanteges of delegates.
First off, the "high order bit" for me with regards to this design decision would be that I would never do this sort of thing with a public field/method. At the very least I would use a property, and probably not even that.
For private fields, I use this pattern fairly frequently, usually like this:
class C
{
private Func<int, int> ActualFunction = (int y)=>{ ... };
private Func<int, int> Function = ActualFunction.Memoize();
and now I can very easily test the performance characteristics of different memoization strategies without having to change the text of ActualFunction at all.
Another advantage of the "methods are fields of delegate type" strategy is that you can implement code sharing techniques that are different than the ones we've "baked in" to the language. A protected field of delegate type is essentially a virtual method, but more flexible. Derived classes can replace it with whatever they want, and you have emulated a regular virtual method. But you could build custom inheritence mechanisms; if you really like prototype inheritance, for example, you could have a convention that if the field is null, then a method on some prototypical instance is called instead, and so on.
A major disadvantage of the methods-are-fields-of-delegate-type approach is that of course, overloading no longer works. Fields must be unique in name; methods merely must be unique in signature. Also, you don't get generic fields the way that we get generic methods, so method type inference stops working.
The second one, in my opinion, offers absolutely no advantage over the first one. It's much less readable, is probably less efficient (given that Invoke has to be implied) and isn't more concise at all. What's more, if you ever use reflection it won't show up as being a method so if you do that to replace your methods in every class, you might break something that seems like it should work. In Visual Studio, the IntelliSense won't include a description of the method since you can't put XML comments on delegates (at least, not in the same way you would put them on normal methods) and you don't know what they point to anyway, unless it's readonly (but what if the constructor changed it?) and it will show up as a field, not a method, which is confusing.
The only time you should really use lambdas is in methods where closures are required, or when it's offers a significant convenience advantage. Otherwise, you're just decreasing readability (basically the readability of my first paragraph versus the current one) and breaking compatibility with previous versions of C#.
Why you should avoid delegates as methods by default, and what are alternatives:
Learning curve
Using delegates this way will surprise a lot of people. Not everyone can wrap their head around delegates, or why you'd want to swap out functions. There seems to be a learning curve. Once you get past it, delegates seem simple.
Perf and reliability
There's a performance loss to invoking delegates in this manner. This is another reason I would default to traditional method declaration unless it enabled something special in my pattern.
There's also an execution safety issue. Public fields are nullable. If you're passed an instance of a class with a public field you'll have to check that it isn't null before using it. This hurts perf and is kind of lame.
You can work around this by changing all public fields to properties (which is a rule in all .Net coding standards anyhow). Then in the setter throw an ArgumentNullException if someone tries to assign null.
Program design
Even if you can deal with all of this, allowing methods to be mutable at all goes against a lot of the design for static OO and functional programming languages.
In static OO types are always static, and dynamic behavior is enabled through polymorphism. You can know the exact behavior of a type based on its run time type. This is very helpful in debugging an existing program. Allowing your types to be modified at run time harms this.
In both static OO and function programming paradigms, limiting and isolating side-effects is quite helpful, and using fully immutable structures is one of the primary ways to do this. The only point of exposing methods as delegates is to create mutable structures, which has the exact opposite effect.
Alternatives
If you really wanted to go so far as to always use delegates to replace methods, you should be using a language like IronPython or something else built on top of the DLR. Those languages will be tooled and tuned for the paradigm you're trying to implement. Users and maintainers of your code won't be surprised.
That being said, there are uses that justify using delegates as a substitute for methods. You shouldn't consider this option unless you have a compelling reason to do so that overrides these performance, confusion, reliability, and design issues. You should only do so if you're getting something in return.
Uses
For private members, Eric Lippert's answer describes a good use: (Memoization).
You can use it to implement a Strategy Pattern in a function-based manner rather than requiring a class hierarchy. Again, I'd use private members for this...
...Example code:
public class Context
{
private Func<int, int, int> executeStrategy;
public Context(Func<int, int, int> executeStrategy) {
this.executeStrategy = executeStrategy;
}
public int ExecuteStrategy(int a, int b) {
return executeStrategy(a, b);
}
}
I have found a particular case where I think public delegate properties are warrented: To implement a Template Method Pattern with instances instead of derived classes...
...This is particularly useful in automated integration tests where you have a lot of setup/tear down. In such cases it often makes sense to keep state in a class designed to encapsulate the pattern rather than rely on the unit test fixture. This way you can easily support sharing the skeleton of the test suite between fixtures, without relying on (sometimes shoddy) test fixture inheritance. It also might be more amenable to parallelization, depending on the implementation of your tests.
var test = new MyFancyUITest
{
// I usually name these things in a more test specific manner...
Setup = () => { /* ... */ },
TearDown = () => { /* ... */ },
};
test.Execute();
Intellisense Support
outside users of the function see unnamed parameters - sometimes this is helpfull although it would be nice to be able to name them.
Use a named delegate - I believe this will get you at least some Intellisense for the parameters (probably just the names, less likely XML docs - please correct me if I'm wrong):
public class MyClass
{
public delegate int DoSomethingImpl(int foo, int bizBar);
public DoSomethingImpl DoSomething = (x, y) => { return x + y; }
}
I'd avoid delegate properties/fields as method replacements for public methods. For private methods it's a tool, but not one I use very often.
instance delegate fields have a per instance memory cost. Probably a premature optimization for most classes, but still something to keep in mind.
Your code uses a public mutable field, which can be changed at any time. That hurts encapsulation.
If you use the field initializer syntax, you can't access this. So field initializer syntax is mainly useful for static methods.
Makes static analysis much harder, since the implementation of that method isn't known at compile-time.
There are some cases where delegate properties/fields might be useful:
Handlers of some sort. Especially if multi-casting (and thus the event subscription pattern) doesn't make much sense
Assigning something that can't be easily described by a simple method body. Such as a memoized function.
The delegate is runtime generated or at least its value is only decided at runtime
Using a closure over local variables is an alternative to using a method and private fields. I strongly dislike classes with lots of fields, especially if some of these fields are only used by two methods or less. In these situations, using a delegate in a field can be preferable to conventional methods
class MyClassConventional {
int? someValue; // When Mark() is called, remember the value so that we can do something with it in Process(). Not used in any other method.
int X;
void Mark() {
someValue = X;
}
void Process() {
// Do something with someValue.Value
}
}
class MyClassClosure {
int X;
Action Process = null;
void Mark() {
int someValue = X;
Process = () => { // Do something with someValue };
}
}
This question presents a false dichotomy - between functions, and a delegate with an equivalent signature. The main difference is that one of the two you should only use if there are no other choices. Use this in your day to day work, and it will be thrown out of any code review.
The benefits that have been mentioned are far outweighed by the fact that there is almost never a reason to write code that is so obscure; especially when this code makes it look like you don't know how to program C#.
I urge anyone reading this to ignore any of the benefits which have been stated, since they are all overwhelmed by the fact that this is the kind of code that demonstrates that you do not know how to program in C#.
The only exception to that rule is if you have a need for one of the benefits, and that need can't be satisfied in any other way. In that case, you'll need to write more comment than code to explain why you have a good reason to do it. Be prepared to answer as clearly as Eric Lippert did. You'd better be able to explain as well as Eric does that you can't accomplish your requirements and write understandable code at the same time.

when is it ok to use a structure rather than a class

In a recent project I was working I created a structure in my class to solve a problem I was having, as a colleague was looking over my shoulder he looked derisively at the structure and said "move it into a class".
I didn't have any argument for not moving it into a class other than I only need it in this class but this kind of falls down because couldn't I make it a nested class?
When is it ok to use a structure?
You should check out the value type usage guidelines: http://msdn.microsoft.com/en-us/library/y23b5415(vs.71).aspx
The article lists several important points but the few that I feel are the most valuable are the following
Is the value immutable?
Do you want the type to have value semantics?
If the answer to both questions is yes then you almost certainly want to use a Structure. Otherwise I would advise going with a class.
There are issues with using structures with a large amount of members. But I find that if I consider the two points above, rarely do I have more than the recommended number of members / size in my value types.
MSDN has a good guidelines document to cover structure usage. To summarize:
Act like primitive types.
Have an instance size under 16 bytes.
Are immutable.
Value semantics are desirable.
Otherwise, use a class.
You should always use a Class as your first choice, changing to Structure only for very specific reasons (as others have already outlined).
Depending on how much you "only need it in this class", you might be able to avoid the nested type completely by using an anonymous type; this will only work within a single method:
Public Class Foo
Public Sub Bar
Dim baz = New With { .Str = "String", .I = 314 }
End Sub
End Class
you can't (readily--there are a few things you can do with generics) move the instance baz outside of the Sub in a typesafe manner. Of course an Object can hold anything, even an instance of an anonymous type.
I think structures are great if you need copy the object or do not want it to be modified by the passed function. Since passed functions can not modify the originally passed structure instead got a new copy of it, this can be a life saver. (unless they passed as ByRef obviously) and can save you trouble of deep copy craziness in .NET or implementing pain of an ICloneSomething implementation.
But the general idea is defining a custom data structure in a more semantic way.
About moving to a class, if you are moving into a class where it'll be part of a class, generally this is good practice since your structure is 99% of the time related with one of you classes not related with a namespace.
If you are converting it to a class then you need to consider "is it defining a data strcuture" and "is it expensive?" since it's gonna be copied all over the place, "do you want to get affected by modifications done by the passers?"
The usage guidelines referenced by Marc and Rex are excellent and nicely cover cases where you aren't sure which one you would want. I will list some use cases where use of a struct is a requirement.
When you need to set the layout of the fields in memory
Interop with unmanaged code.
When you want to make Unions.
You need a fixed size buffer inlined.
You want to be able to do the equivalent of a reinterpret_cast with relative safety (so long as the struct does not contain any fields which are themselves reference types.
These are normally edge cases and (with the exception of interop) not recommended practices unless their use is necessary for the success of the project/program.

Categories

Resources