+ 1

what is the difference between readonly, static, and const in c#?

all three work somewhat similar so what si the importance. Can't we use only one in place of all three using differently.

30th Apr 2018, 4:09 PM
Devashish Shukla
1 Respuesta
+ 4
Static isn't all that similar. Static makes the member bound to the class rather than an instance of the object. Or more simply put, the member is shared throughout all object instances. This is why you can call a static member with: MyClass.myMethod(); instead of: (new MyClass()).myMethod(); Static is a bit more difficult to understand but, hopefully that makes sense. const is well, a constant. It always remains unchanged. const float PI = 3.14; You cannot re-set the value of PI since it is marked as const. So, PI = 5.1; // ERROR readonly is similar to const, except a major difference is that const is implicitly static while readonly is not. This gives us the ability to initialize something that is readonly inside of a constructor. Lets think of an arrays length: class Array{ public readonly int length; Array(int length){ this.length = length; } } Now when we create an Array, the length is different for each array we create. However much like a const, the variable cannot be modified once given a value. new Array(4); // length = 4 new Array(5); // length = 5 (new Array(10)).length = 15; // Error // Length cannot be changed
30th Apr 2018, 4:48 PM
Rrestoring faith
Rrestoring faith - avatar