When do I use struct instead of having class in c#? [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When should I use a struct instead of a class?
By Venkat K in the C# .NET forum.
29-Apr-09 07:38 AM
The only difference between "class" and "struct" is that a struct defaults to having public members (both data members and function members) and a struct defaults to public inheritance, whereas a class defaults to private members and private inheritance. That is the only difference. This difference can be circumvented by explicitly specifying "public", private", or "protected" so a struct can be made to act like a class in ever way and vice versa.by convention, most programmer's use "struct" for data types that have no member functions and that do not use inheritance. They use "class" for data types with member functions and inheritance. However, this is not necessary or even universallly acepted.
*(Can this be true)

That statement is entirely false when it comes to C#. I believe it may well be true for C++, but in C# the difference is between a value type (structs) and a reference type (classes).

It's not the only difference. Structs are value types and classes are reference types. Look it up on Google to find out more about the differences, which are too many to list in the minute I have right now.
Unless, as #BrokenGlass points out it's C++.

The statement you quote would be correct for C++, but not for C#. Here's an excerpt of what the C# Language Specification has to say about structs:
Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly stores the data of the struct, whereas a variable of a class type stores a reference to a dynamically allocated object. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.
Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs.

Related

Is there a word that encompasses "classes" and "structs"?

Classes and structs in C# share several characteristics:
they can be instantiated (absent restrictions to the contrary, as with abstract and static classes)
they can contain method and property implementations
the type's author defines the type's instance fields
We often use "class" and "struct" to distinguish between "reference type" and "value type", but sometimes it's useful to consider both types of types. Furthermore, "reference type" also includes interfaces and delegates, which are not classes. So "class" doesn't mean any reference type, it means "a reference _(fill in the blank)_".
For example, if reference and value type declarations were like this:
public sealed class ref String { }
public class val Int32 { }
instead of like this:
public sealed class String { }
public struct Int32 { }
then the word "class" could be used to denote the concept.
The best answer I've come up with here is "concrete type", but that would be confusing, since it could also refer to the non-abstract subclass of an abstract class.
Any suggestions?
EDIT
To clarify, I'm not seeking a word that can collectively describe instances of classes and structs. I'm trying to describe class types and struct types.
In other words, if "class" denotes a set that includes System.String, System.FileInfo, etc., and "struct" denotes a set that includes System.Int32, System.Collections.Generic.List<T>.Enumerator, etc., then I'm looking for the word that denotes the union of those sets.
EDIT 2
(In reaction to Jordão's answer) Another way to answer this question would be to complete the following sentence: "All C# method implementations must be declared as members of a _(fill in the blank)_".
I normally use the term "type" to refer to any of those elements: class, struct and even interfaces and enums.
I never really felt the need to talk about classes and structs exclusively, I would probably just say "class", and then differentiate them as needed.
The term type in C# can refer to any of:
Reference Types
object, dynamic and string
Class types
Interface types
Delegate types
Constructed class/interface/delegate types (e.g. List<string>)
Array types
Value types
Struct types
Enumeration types
Simple types (integral types, floating point types, decimal, and bool)
Nullable types
Pointer types
All of these are terms from the C# specification.
class, interface, delegate, struct and enum types are also called type declarations (or: user-definable types).
Depending on your point of view, you might also consider type parameters and void to be types.
However, there isn't any special term for "classes or structs". In the language of the C# specification, one would say:
All C# method implementations must be declared as members of a class or struct declaration.
I realize this question has a selected answer, but I believe I can offer a fresh insight that will still be helpful:
I think the word you are looking for may be Model. This term is used to mean several different things in CS, but the wikipedia article for mathematical model describes my intension.
In this context, a model is a description of a system in some meta language. A system can be fully expressed in terms of its three parts: structure; behavior; and, interconnectivity. Both .NET classes and .NET structs are compatible with this definition. Interfaces are not, because the behavior is not defined. You can only indicate the structure of method calls and member declarations and the type contracts for operations (interconnectivity). Enums may or may not be compatible with this definition, but as most frequently used are not, because they typically do not express behavior. The exceptions are enums for which bitwise operations are sufficient representations of meaningful set operations. With this precondition, I think its fair to classify an enum along with classes and structs.
As a side note, both interfaces and standard enums could be considered as systems by themselves, if extension methods were interpreted as intrinsic to the types they extend. However, neither the compiler nor I would consider extension methods to be intrinsic to the type of the first operand. A more accurate interpretation would be to consider both the enum/interface and the extension method as necessary components of a system. The difference between these component types that are extended and a class/struct/special-case enum is that the class/struct/special-case enum is a system in-itself, and therefore a subsystem of its containing system, whereas the component type is a component but not a system in itself.
It is probably worthwhile to clarify that, under this interpretation, the term model is analogous to a type, whereas the term system is analogous to an instance. A system could also apply to a larger composite, such as an assembly, but that is not what the question was about.
The statement "All C# method implementations must be declared as members of a model" seems to work. It also does not logically entail that "all models can contain custom method implementations", so we are safe in the special-case of set-theoretic enums. It would also work in the case where the modeled system is the composition of static extension method implementations and interfaces.
 
I find this to be a pseudo discussion. Point #3 can be said about enums and interfaces too, and the point about subclasses of abstract classes not fitting into the mix, I simply don't get. I think your own suggestion of "concrete types" is ok, but maybe you just want to talk about them as classes and structs, oh wait, but with the exception of subclasses of abstract classes and classes that implement interfaces. The reason that there is no term for what you are looking for might be that it is not a very useful concept in its own right.
EDIT:
All C# method implementations must be declared as members of a class or struct.
It should be Microsoft term. The origin of these notions is C++, where structs are just classes with all members being public. So, Microsoft cooked some new judging here, mixing some of C, C++ and Java. So they should invent also a terms.
Microsoft denotes them all as "types" which can be "value", "reference" and "pointer": http://msdn.microsoft.com/en-us/library/3ewxz6et(v=vs.100).aspx
But these notions do not gather only structs and classes.
So, if invent some custom term, we may take one from Pascal language, for example, where it is "record". Or some other terms can be coined from here: http://en.wikipedia.org/wiki/Object_composition
Both classes and structs are types which define objects. They are building blocks within an object oriented programming language. You can model both of them using UML or some other high-level object oriented modelling language. The choice between one or the other is an implementation detail.

When to use Structs in C# [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to use struct in C#?
I'm reading a C# tutorial in the net http://www.csharp-station.com/Tutorials/Lesson12.aspx.
And I came to the topic about Structs.
I'm just confused about this thing.
When does struct is advantageous to use or what are the practical uses of this?
Struct is a value type. Class is an object type.
You use value types when you never have to pass it by reference into a function/method parameter -- i.e. you can't change it inside of a function/method.
Whenever you pass it into a function/method, it always gets copied (i.e. pass by value), never by refernce. Structs are automatically boxed when being accessed like an object.
In practice, structs are used to model whenever you have a chunk of data that form a coherent whole (e.g. Color with RGB, vectors with XYZ, complex numbers etc.) and the whole item forms a single unit.
They are also used a lot to interface with unmanaged libraries (e.g. C or C++ DLL functions that accept struct parameters).
citation from MSDN:
The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive.
You know how ints and floats don't need to be "initialised" (set to new int/float)?
A struct is a way of declared an arrangment of members like in a class, that behave like that.

Should I use a structure instead of a class to hold string only data in C#? [duplicate]

This question already has answers here:
When should I use a struct rather than a class in C#?
(31 answers)
Closed 7 years ago.
C# question.
Say I have a customers class that has a bunch of props for storing string only data such as name postal data and phone numbers.
I don't use this entity for ORM as I'm only adding it to some type of collection for use during app life cycle.
Additionally I don't need to add any entity specific methods to it or persist the data to xml or database, or even to a webservice.
Is it better to make this a struct rather than a class? or no benefit?
Also side question, should I make the collection Customers, a list structure?
Be harsh, please critique.. :)
struct customer
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
struct Customers<List>
{
private customer cust;
public customer Cust
{
get { return cust; }
set { cust = value; }
}
}
I can't see any value in making the customer a struct. The string fields will all be reference types, so you might as well make the whole thing a reference type (ie. class).
I'd be inclined to use one of the built-in collection types rather than create my on type for Customers. Something like:
List<Customer> Customers = new List<Customer>();
I suppose you could look at When to use struct in C#?
Unless you have identified specific reasons for using a struct, use a class.
Update: due to #Dmitry Lobanov: Eric Lippert's post: The Truth About Value Types
Structs vs. Classes
Structs may seem similar to classes,
but there are important differences
that you should be aware of. First of
all, classes are reference types and
structs are value types. By using
structs, you can create objects that
behave like the built-in types and
enjoy their benefits as well.
Heap or Stack?
When you call the New operator on a class, it will be
allocated on the heap. However, when
you instantiate a struct, it can be
created on the stack. This will yield
performance gains. Also, you will not
be dealing with references to an
instance of a struct as you would with
classes. You will be working directly
with the struct instance. Because of
this, when passing a struct to a
method, it's passed by value instead
of as a reference.
Ref.
For what it's worth, I would never use structs because I so very rarely have a need to provide a data only structure that doesn't have some sort of associated behaviour (validators, formatters, etc...).
The one thing that I do like about the basic concept of a "struct" is that it represents a storage system at it's most basic, and therefore should avoid the need to write all those pernickity custom getters and setters and all that sort of stuff... but then again, we now have those lovely auto-properties which effectively achieve the same result from purely a coding perspective, and while the YAGNI nazi in me might say to use the struct because it is meant to be simple, the realist in me knows that I will inevitably want to change the struct to a class anyway, so why not simply implement the class from the beginning and be done with the matter! ;-)
As for the argument of performance, and other benefits... ask yourself the question "does this really matter". If you're writing a serious real-time system... perhaps you want to be using another tool. If you're simply passing around some data, you've likely got oodles of processing croutons at your disposal, and your killer algorithm might not really need to worry about the nano-second difference it's going to make.
Personally I use structs everywhere I need to store information, as long as it will not cause obvious performance issues. In most projects this is never, since the data is either directly mappable to an existing type or is larger than a reference (affecting the invariable LINQ queries and other manipulation). I find that structs are only viable when I can stick the data in an array and leave it there (modifying the variables directly in the array), the struct is rarely used, or the amount of data in the struct is less than 64 bits (ignoring struct overhead).
As it was explained to me, structs should be used only to store data and translate it from one form to another (ToString or ToArray converters).
Also, structs are more restrictive than classes with the primary differences:
Structs are value types while classes are reference types. This means the whole struct instance is copied when it is assigned while only the memory address of a class instance is copied. Since most programs are 32bit or 64bit it is usually recommended to limit the size of the struct to prevent performance issues related to copying struct instances as compared to class instanceses. While this can be overcome by putting the structs in an array, this moves the structs to the heap (instead of stack). Also, using generics like List always returns a copy of the instance, since they use methods to access the values. See also the Struct Instances vs. Class Instances section in Objects (C# Programming Guide)
Structs can be instantiated on the stack, while classes are always instantiated on the heap. This is controlled by the compiler and does not affect coding, though it may have a small performance benefit (which is rarely ever detectable).
Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
A struct cannot declare a default constructor (a constructor without parameters) or a destructor.
Unlike classes, structs can be instantiated without using a new operator.
A struct cannot inherit from another struct or class, and it cannot be the base of a class.
All structs inherit directly from System.ValueType, which inherits from System.Object while classes inherit from System.Object.
A struct cannot be null (use the generic Nullable struct).

Should I use a Struct? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When to use struct in C#?
Hi, I am creating an application that has a class in C# that is purely for holding variables, it does nothing else but set and get these variables. I was wondering, for efficiency and good coding practice, if I should convert this class to a struct so that it is being used properly. I've never used structs before but have been looking into them however I am having some trouble getting it working. Any advice would be appreciated!
Thanks,
Stuart
If the collection of values model a value type (that is, something that doesn't have an identity of its own and two instances with the same values are considered the same) use a struct.
Otherwise, use a class.
Using structures in place of classes depends on the scenario on which you are working. Although you can use structures in place of classes but structures lacks the ability to implement access identifiers (such as Private, Public, Protected). If you are using classes just for holding variables, you can use structures as well, but if your class contains some private, protected or public methods or variables/properties, you can not use structures.
Hope this helps!
The decision for struct or class should be based on "do I want reference type semantics or values type semantics?"
When you use a struct as parameter, the complete contents are copied. For a class just the reference is copied. So a "big struct" could have a performance penalty!
In most cases, a class is preferred. Structs are passed by value, have no inheritance, etc. You mention efficiency, is this class likely to be a performance bottleneck ?
If you make a struct though, make sure to make it immutable
I'm not sure that using a struct or not relates to good coding practise, but there are some performance benefits to using structs under certain circumstances. For example, MSDN suggests that a type which is under 16 bytes in size might be more efficiently handled by a struct than a class.
It's important to understand why a struct might be a better choice and how their memory is managed by the runtime. Libraries which must perform quickly with the minimum of overhead would consider using structs (such as a lot of the Math types in the XNA framework). There are also design issues like the fact that your struct always has a default constructor; if you want to make sure that your type can only be constructed with specific values then a struct isn't the best choice.
The long and short of it is, unless you have a very specific reason to be using structs over classes, just stick with classes.
If you want to press ahead with structs, what issues are you having with them?
It really depends on what you're trying to achieve. The fact that you currently have only getters and setters doesn't mean anything. For example, a type might be modelling the application settings read from a file. At some point you might wish to add a IsValid() or Normalize() methods. So in this case, you'd rather go with a class then a struct.
A struct should be used, when the type's identity is decided by the value of the fields. A good example from the .NET framework is Point, which has X and Y.
The second thing is that structs should be cheap to pass to and from functions:
public bool IsInRange(Point point)
{
// ...
}
Remember that point will be copied field by field here, so that should be fairly cheap.
You use structs when:
Logically represents a single value
Has an instance size less than 16
bytes
Will not be changed after creation
Will not be cast to a reference type
Refere to MCTS 70-536

C# why need struct if class can cover it?

Just wondering why we need struct if class can do all struct can and more? put value types in class has no side effect, I think.
EDIT: cannot see any strong reasons to use struct
A struct is similar to a class, with the following key differences:
A struct is a value type, whereas a
class is a reference type.
A struct does not support inheritance
(other than implicitly deriving from
object).
A struct can have all the members a
class can, except the following:
A parameterless constructor
A finalizer
Virtual members
A struct is used instead of a class when value type semantics are desirable. Good examples of structs are numeric types, where it is more natural for assignment to copy a value rather than a reference. Because a struct is a value type, each instance does not require instantiation of an object on the heap. This can be important when creating many instances of a type.
Custom value types aren't absolutely necessary - Java does without them, for example. However, they can still be useful.
For example, in Noda Time we're using them pretty extensively, as an efficient way of representing things like instants without the overhead of an object being involved.
I wouldn't say that "class can do all struct can and more" - they behave differently, and should be thought of differently.
Why use a struct when a class works? Because sometimes a class doesn't work.
In addition to the performance reasons mentioned by Reed Copsey (short version: fewer objects that the GC needs to track, allowing the GC to do a better job), there is one place where structures must be used: P/Invoke to functions that require by-value structures or structure members.
For example, suppose you wanted to invoke the CreateProcess() function. Further suppose that you wanted to use a STARTUPINFOEX structure for the lpStartupInfo parameter to CreateProcess().
Well, what's STARTUPINFOEX? This:
typedef struct _STARTUPINFOEX {
STARTUPINFO StartupInfo;
PPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
} STARTUPINFOEX, *LPSTARTUPINFOEX;
Notice that STARTUPINFOEX contains STARTUPINFO as its first member. STARTUPINFO is a structure.
Since classes are reference types, if we declared the corresponding C# type thus:
[StructLayout(LayoutKind.Sequential)]
class STARTUPINFO { /* ... */ }
class STARTUPINFOEX { public STARTUPINFO StartupInfo; /* ... */ }
The corresponding in-memory layout would be wrong, as STARTUPINFOEX.StartupInfo would be a pointer (4 bytes on ILP32 platforms), NOT a structure (as is required, 68 bytes in size on ILP32 platforms).
So, to support invoking arbitrary functions which accept arbitrary structures (which is what P/Invoke is all about), one of two things are necessary:
Fully support value types. This allows C# to declare a value type for STARTUPINFO which will have the correct in-memory layout for marshaling (i.e. struct support, as C# has).
Some alternate syntax within P/Invokeable structures which would inform the runtime marshaler that this member should be laid out as a value type instead of as a pointer.
(2) is a workable solution (and may have been used in J/Direct in Visual J++; I don't remember), but given that proper value types are more flexible, enable a number of performance optimizations not otherwise achievable, and make sensible use within P/Invoke scenarios, it's no surprise that C# supports value types.
In general, use a class.
Only use a struct when you absolutely need value type semantics.
Structs are also often required for performance reasons. Arrays of structs take quite a bit less memory, and get much better cache coherency than an array of object references. This is very important if you're working with something like a rendering system, and need to generate 5 million vertices, for example.
For details, see Rico Mariani's Performance Quiz + Answers.
Structs are useful simply because they are passed by value, which can actually be useful in certain algorithms. This is actually something that classes CAN'T do.
struct ArrayPointer<T>
{
public T[] Array;
public int Offset;
}
You can pass this structure to a method and the method can alter the value of Offset for its own needs. Meanwhile, once you return from the method, it will behave as if Offset never changed.
Struct Vs Class in C#
C# Struct usage tips?
Why do we need struct? (C#)
For the average application developer, using classes is the norm. On the surface, classes make structs seem unnecessary, but when you dig deeper into the nitty-gritty details they are actually quite different.
See here for some differences between structs and classes.
The most well-known difference is that classes are reference-types and structs are value-types. This is important because it allows a library developer to control how instances of a data-type can be used.
1, performance. In some cases using structures we'll get much better performance.
2, data immutability. By changing some property of a struct you'll get a new struct. This is very useful in some cases
3, better control of in memory representation. We can exactly define how the struct is located in memory and this allows us to serialize and deserialize some binary data fast and efficiently.
It is almost a must to use for interop with underlying data structure used by win32 API. I suppose a very big reason to have it in .net could be due to that reason.

Categories