Aleksei Chepovoi
Aleksei Chepovoi

Reputation: 3955

Methods on value types in .NET

I'm reading a "CLR via C#" by Jeffrey Richter and he suggests never define methods in a value type that are intended to change it's behavior cause value types should be immutable (because of boxing/unboxing expenses and sometimes unpredictable behavior).

So, we can define methods in our custom value type only for displaying it's state?

Can You give any other examples where the ability to define methods within a Struct is needed?

Upvotes: 1

Views: 101

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149010

The best example I can think of is the DateTime struct.

All instance methods on the type are designed to create a new DateTime by manipulating the current one (e.g. AddMinutes) or get additional information from the current DateTime (e.g. IsDaylightSavingsTime). It also has a variety of static methods for creating a new instances from various inputs, (e.g. FromBinary) or generally manipulating DateTime values (e.g. Compare)

No method can actually modify the current instance.

Upvotes: 4

Related Questions