Business logic class

I came across several ways to write business logic in asp.net, but I am interested in 2 examples below, what are the advantages of using a structure to store class variables:

namespace Shopping { public struct ShoppingCart { public string Color; public int ProductId; } public partial class MyShoppingCart { public decimal GetTotal(string cartID) { } // Some other methods ... } } 

 namespace Shopping { public partial class MyShoppingCart { public string Color{ get; set; } public int ProductId{ get; set; } public decimal GetTotal(string cartID) { } // Some other methods ... } } 
+7
source share
1 answer

As dsimcha states in their answer here :

Whenever you do not need polymorphism, you want semantics of meaning and want to avoid overhead allocation and garbage collection. However, the caveat is that structures (arbitrarily large) are more expensive than class references (usually a single machine word), so classes can be faster in practice.

As JoshBerke says in his answer here :

Use the construct if you need value semantics, not referential semantics.

From http://msdn.microsoft.com/en-us/library/ms228593.aspx

1.7 Structures

Like classes, structures are data structures that can contain data of members and members of functions, but unlike classes, structures are type values ​​and do not require heap allocation. A variable of type struct directly stores structure data, while a variable of type type stores a reference to a dynamically allocated object. Struct types do not support user-defined inheritance, and all types of structures are implicitly inherited from the type object.

Structures are especially useful for small data structures that have semantics of meaning. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are good examples of structures. using structures rather than classes for small data structures can make a big difference in the number of memory allocations an application performs. For example, the following program creates and initializes an array of 100 points. When Point is implemented as a class, 101 separate objects are created: one for the array and one for each 100 elements.

+5
source

All Articles