Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"const correctness" in C#

The point of const-correctness is to be able to provide a view of an instance that can't be altered or deleted by the user. The compiler supports this by pointing out when you break constness from within a const function, or try to use a non-const function of a const object. So without copying the const approach, is there a methodology I can use in C# that has the same ends?

I'm aware of immutability, but that doesn't really carry over to container objects to name but one example.

like image 256
tenpn Avatar asked Sep 22 '08 10:09

tenpn


People also ask

What is const correctness in C?

In C, C++, and D, all data types, including those defined by the user, can be declared const , and const-correctness dictates that all variables or objects should be declared as such unless they need to be modified.

What is a const function in C?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

Is const valid in C?

Yes. const is there in C, from C89.

What is const * const in C?

const int* const is a constant pointer to constant integer This means that the variable being declared is a constant pointer pointing to a constant integer. Effectively, this implies that a constant pointer is pointing to a constant value.


2 Answers

I've come across this issue a lot of times too and ended up using interfaces.

I think it's important to drop the idea that C# is any form, or even an evolution of C++. They're two different languages that share almost the same syntax.

I usually express 'const correctness' in C# by defining a read-only view of a class:

public interface IReadOnlyCustomer {     String Name { get; }     int Age { get; } }  public class Customer : IReadOnlyCustomer {     private string m_name;     private int m_age;      public string Name     {         get { return m_name; }         set { m_name = value; }     }      public int Age     {         get { return m_age; }         set { m_age = value; }     } } 
like image 181
Trap Avatar answered Oct 13 '22 00:10

Trap


To get the benefit of const-craziness (or pureness in functional programming terms), you will need to design your classes in a way so they are immutable, just like the String class of c# is.

This approach is way better than just marking an object as readonly, since with immutable classes you can pass data around easily in multi-tasking environments.

like image 21
Sam Avatar answered Oct 13 '22 00:10

Sam