Whenever I have local variables in a method, ReSharper suggests to convert them to constants:
// instead of this:
var s = "some string";
var flags = BindingFlags.Public | BindingFlags.Instance;
// ReSharper suggest to use this:
const string s = "some string";
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
Given that these are really constant values (and not variables) I understand that ReSharper suggest to change them to const.
But apart from that, is there any other advantage when using const (e.g. better performance) which justifies using const BindingFlags instead of the handy and readable var keyword?
BTW: I just found a similar question here: Resharper always suggesting me to make const string instead of string, but I think it is more about fields of a class where my question is about local variable/consts.
The compiler will throw an error if you try to assign a value to a constant, thus possibly preventing you from accidentally changing it.
Also, usually there is a small performance benefit to using constants vs. variables. This has to do with the way they are compiled to the MSIL, per this MSDN magazine Q&A:
Now, wherever myInt is referenced in the code, instead of having to do a "ldloc.0" to get the value from the variable, the MSIL just loads the constant value which is hardcoded into the MSIL. As such, there's usually a small performance and memory advantage to using constants. However, in order to use them you must have the value of the variable at compile time, and any references to this constant at compile time, even if they're in a different assembly, will have this substitution made.
Constants are certainly a useful tool if you know the value at compile time. If you don't, but want to ensure that your variable is set only once, you can use the readonly keyword in C# (which maps to initonly in MSIL) to indicate that the value of the variable can only be set in the constructor; after that, it's an error to change it. This is often used when a field helps to determine the identity of a class, and is often set equal to a constructor parameter.
tl;dr for local variables with literal values, const makes no difference at all.
Your distinction of "inside methods" is very important. Let's look at it, then compare it with const fields.
Const local variables
The only benefit of a const local variable is that the value cannot be reassigned.
However const is limited to primitive types (int, double, ...) and string, which limits its applicability.
Digression: There are proposals for the C# compiler to allow a more general concept of 'readonly' locals (here) which would extend this benefit to other scenarios. They will probably not be thought of as const though, and would likely have a different keyword for such declarations (i.e. let or readonly var or something like that).
Consider these two methods:
private static string LocalVarString()
{
var s = "hello";
return s;
}
private static string LocalConstString()
{
const string s = "hello";
return s;
}
Built in Release mode we see the following (abridged) IL:
.method private hidebysig static string LocalVarString() cil managed
{
ldstr "hello"
ret
}
.method private hidebysig static string LocalConstString() cil managed
{
ldstr "hello"
ret
}
As you can see, they both produce the exact same IL. Whether the local s is const or not has no impact.
The same is true for primitive types. Here's an example using int:
private static int LocalVarInt()
{
var i = 1234;
return i;
}
private static int LocalConstInt()
{
const int i = 1234;
return i;
}
And again, the IL:
.method private hidebysig static int32 LocalVarInt() cil managed
{
ldc.i4 1234
ret
}
.method private hidebysig static int32 LocalConstInt() cil managed
{
ldc.i4 1234
ret
}
So again we see no difference. There cannot be a performance or memory difference here. The only difference is that the developer cannot re-assign the symbol.
Const fields
Comparing a const field with a variable field is different. A non-const field must be read at runtime. So you end up with IL like this:
// Load a const field
ldc.i4 1234
// Load a non-const field
ldsfld int32 MyProject.MyClass::_myInt
It's clear to see how this could result in a performance difference, assuming the JIT cannot inline a constant value itself.
Another important difference here is for public const fields that are shared across assemblies. If one assembly exposes a const field, and another uses it, then the actual value of that field is copied at compile time. This means that if the assembly containing the const field is updated but the using assembly is not re-compiled, then the old (and possibly incorrect) value will be used.
Const expressions
Consider these two declarations:
const int i = 1 + 2;
int i = 1 + 2;
For the const form, the addition must be computed at compile time, meaning the number 3 is kept in the IL.
For the non-const form, the compiler is free to emit the addition operation in the IL, though the JIT would almost certainly apply a basic constant folding optimisation so the generated machine code would be identical.
The C# 7.3 compiler emits the ldc.i4.3 opcode for both of the above expressions.
As per my understanding Const values do not exist at run time - i.e. in form of a variable stored in some memory location - they are embeded in MSIL code at compile time . And hence would have an impact on performance. More over run-time would not be required to perform any house keeping (conversion checks / garbage collection etc) on them as well, where as variables require these checks.
const is a compile time constant - that means all your code that is using the const variable is compiled to contain the constant expression the const variable contains - the emitted IL will contain that constant value itself.
This means the memory footprint is smaller for your method because the constant does not require any memory to be allocated at runtime.
Besides the small performance improvement, when you declare a constant you are explicitly enforcing two rules on yourself and other developers who will use your code
I have to initialize it with a value right now i can't to do it any place else.
I cannot change its value anywhere.
In code its all about readability and communication.
A const value is also 'shared' between all instances of an object. It could result in lower memory usage as well.
As an example:
public class NonStatic
{
int one = 1;
int two = 2;
int three = 3;
int four = 4;
int five = 5;
int six = 6;
int seven = 7;
int eight = 8;
int nine = 9;
int ten = 10;
}
public class Static
{
static int one = 1;
static int two = 2;
static int three = 3;
static int four = 4;
static int five = 5;
static int six = 6;
static int seven = 7;
static int eight = 8;
static int nine = 9;
static int ten = 10;
}
Memory consumption is tricky in .Net and I won't pretend to understand the finer details of it, but if you instantiate a list with a million 'Static' it is likely to use considerably less memory than if you do not.
static void Main(string[] args)
{
var maxSize = 1000000;
var items = new List<NonStatic>();
//var items = new List<Static>();
for (var i=0;i<maxSize;i++)
{
items.Add(new NonStatic());
//items.Add(new Static());
}
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().WorkingSet64);
Console.Read();
}
When using 'NonStatic' the working set is 69,398,528 compared to only 32,423,936 when using static.
The const keyword tells the compiler that it can be fully evaluated at compile time. There is a performance & memory advantage to this, but it is small.
Constants in C# provide a named location in memory to store a data value. It means that the value of the variable will be known in compile time and will be stored in a single place.
When you declare it, it is kind of 'hardcoded' in the Microsoft Intermediate Language (MSIL).
Although a little, it can improve the performance of your code. If I'm declaring a variable, and I can make it a const, I always do it. Not only because it can improve performance, but also because that's the idea of constants. Otherwise, why do they exist?
Reflector can be really useful in situations like this one. Try declaring a variable and then make it a constant, and see what code is generated in IL. Then all you need to do is see the difference in the instructions, and see what those instructions mean.
Related
Consider the following code:
private unsafe void Function()
{
int length;
// This line raises error CS1686, "Local 'length' or its members cannot have their address taken and be used inside an anonymous method or lambda expression".
glGetProgramiv(1, GL_PROGRAM_BINARY_LENGTH, &length);
FunctionWithLambda(() => Console.WriteLine(length));
}
private void FunctionWithLambda(Action callback)
{
callback();
}
Note that I'm taking the address of length (a local variable), then using the variable itself (not its address) in a lambda. I understand why a local variable address can't be used in a lambda directly (see Why cannot I pass the address of a variable to an anonymous function?, among other examples), but why can't I use the value of length once assigned (even if that assignment happens to use the & operator)? The official documentation for error CS1686 (https://learn.microsoft.com/bs-latn-ba/dotnet/csharp/misc/cs1686) hasn't clarified this confusion.
My assumption is that this is simply a language limitation, but I'm curious if there's an underlying technical reason I'm missing. Also note I'm not asking how to work around this problem (I know I can easily copy length to another local variable first).
The C# specification says the following (my bold):
23.4 Fixed and moveable variables
The address-of operator (§23.6.5) and the fixed statement (§23.7) divide variables into two categories:
Fixed variables and moveable variables.
...snip...
The & operator (§23.6.5) permits the address of a fixed variable to be obtained without restrictions. However, because a moveable variable is subject to relocation or disposal by the garbage collector, the address of a moveable variable can only be obtained using a fixed statement (§23.7), and that address remains valid only for the duration of that fixed statement.
In precise terms, a fixed variable is one of the following:
A variable resulting from a simple-name (§12.7.3) that refers to a local variable, value parameter, or parameter array, unless the variable is captured by an anonymous function (§12.16.6.2).
.....
So it's explicitly forbidden by the spec. As to why it's forbidden, for that you would have to ask the language designers, but considering how much complexity is involved in capturing variables, it is somewhat logical.
I guess the reason is simple: Too complex to compile.
There are 2 problems the compiler has to solve:
Generate a clourse for the anonymous method.
Synchronize the value of the variable.
Let's assume the following codes are valid.
unsafe void Function()
{
int length = 1;
void bar() => Console.WriteLine(length);
bar();
foo(&length);
bar();
}
unsafe void foo(int* i) { (*i)++; }
Expected result is:
1
2
To solve the first problem C# will generate an anonymous class to hold the upvalue.
Here is the pseudocode:
class _Anonymous
{
public int _length;
public void _bar() { Console.WriteLine(_length); }
}
unsafe void Function()
{
int length = 1;
var a = new _Anonymous { _length = length };
a._bar();
foo(&length);
a._bar();
}
To solve the second problem C# uses the generated field instead of the original local variable.
unsafe void Function()
{
//int length = 1;
var a = new _Anonymous { _length = 1 };
a._bar();
foo(&a._length);
a._bar();
}
These are all the works that a compiler can do. But till now the codes still won't work, we need an extra fixed block.
unsafe void Function()
{
var a = new _Anonymous { _length = 1 };
a._bar();
fixed (int* p = &a._length)
foo(p);
a._bar();
}
So the limitation can be removed with a smarter compiler, but things get more easy if we forbid such kind of codes.
Disclaimer: This question is out of curiosity only, obviously one should never try to do this.
I understand that constants are not variables. But the value of a constant has to be stored somewhere in memory right? And that memory location has an address. So there must be a way to get that address, right?
Something like this:
const int seven = 7;
void Test()
{
Console.Write(seven);//7
int* pointerToSeven = GetThePointerOfConstSeven();//here we get the pointer to the constant
Increment(pointerToSeven);
Console.Write(seven);//8
}
void Increment(int* value)
{
(*value)++;
}
Ignoring the fact that this is a stupid thing to do, is there any way to do this in C#?
The main answer is no, it isn't possible. That is because the 7 doesn't have to be stored in (data) memory anywhere - it is just referred to directly as a number in the IL and machine code.
Consider:
const int seven = 7;
Console.WriteLine(seven);
Which produces IL:
IL_0000 ldc.i4.7
IL_0001 call Console.WriteLine (Int32)
Which becomes machine code:
L0006 mov [rsp+0x20], rax
L000b mov ecx, 7
L0010 call System.Console.WriteLine(Int32)
As you can see, the const int seven becomes a literal 7 in the code.
However, one type of const does require storage - a const string. Then you can get a char* and modify the string
const string sv = "7";
Console.WriteLine(sv); // outputs 7
unsafe {
fixed (char* p = sv) {
*p = '8';
}
}
Console.WriteLine(sv); // outputs 8
As you noted, this is a very bad idea.
The compiler replaces constants with literals. At runtime, the only place in memory that holds the value of the constant is a variable whose value was assigned from the constant.
Incidentally, the compiler also does this with values that can be computed from constants at compile time. This means you don't gain any efficiency by defining constants for simple arithmetic operations on other constants. For example, there's no runtime difference between defining a constant HALF_PI and just writing Math.PI / 2 everywhere. The reason to define HALF_PI would be convenience or readability.
I started digging into new C#/.net core features called Span and Memory and so far they look very good.
However, when I encountered MemoryMarshal.AsMemory method I found out the following interesting use case:
const string source1 = "immutable string";
const string source2 = "immutable string";
var memory = MemoryMarshal.AsMemory(source1.AsMemory());
ref char first = ref memory.Span[0];
first = 'X';
Console.WriteLine(source1);
Console.WriteLine(source2);
Output in both cases is Xmmutable string (tested on Windows 10 x64, .net471 and .netcore2.1). And as far as I can see any string that is interned can now be modified in one place and then all references to that string will use updated value.
Is there any way to prevent such behavior? And is it possible to "unintern" string?
This is just the way it works
MemoryMarshal.AsMemory(ReadOnlyMemory) Method
Creates a Memory instance from a ReadOnlyMemory.
Returns
- Memory<T> A memory block that represetns the same memory as the ReadOnlyMemory .
Remarks
This method must be used with extreme caution. ReadOnlyMemory is used to represent immutable data and other memory that is not meant to
be written to. Memory instances created by this method should not
be written to. The purpose of this method is to allow variables typed
as Memory but only used for reading to store a ReadOnlyMemory.
More things you shouldn't do
private const string source1 = "immutable string1";
private const string source2 = "immutable string2";
public unsafe static void Main()
{
fixed(char* c = source1)
{
*c = 'f';
}
Console.WriteLine(source1);
Console.WriteLine(source2);
Console.ReadKey();
}
Output
fmmutable string1
immutable string2
I have a following function which accepts a enum value and based upon the enum value returns a constant value(which is in a different class). Now i get a "Constant initializer missing" Error.
public const int Testfunction(TESTENUM TestEnum)
{
switch(TestEnum)
{
case TestEnum.testval1:
return testclass.constvalue;
case TestEnum.testVal2:
return testclass.constvalue1;
case TestEnum.testVal3:
return testclass.constvalue2;
}
}
how exactly the function's return type would be? (I am using object return type and this does not throw any error)
Is there any other option to achieve the same?
What's happening here is the compiler thinks that you are trying to declare a public constant integer field named Testfunction, and is extremely surprised to discover that there is no = 123; following the identifier. It's telling you that it expected the initializer.
There are a number of places in the C# compiler where the development team anticipated that C and C++ users would use a common C/C++ syntax erroneously. For example, there's a special error message for int x[]; that points out that you probably meant int[] x;. This is an example of another place where the compiler could benefit from a special-purpose error message that detects the common mistake and describes how to fix it. You might consider requesting that feature if you think it's a good one.
More generally, "const" in C# means something different than it means in C or C++. C# does not have the notion of a "const function" that does not mutate state, or a "const reference" that provides a read-only view of potentially-mutable data. In C# "const" is only used to declare that a field (or local) is to be treated as a compile-time constant. (And "readonly" is used to declare that a field is to be written only in the constructor, which is also quite useful.)
Removing "const" keyword from your function return type should solve the problem
It should be like this
public int Testfunction(TESTENUM TestEnum)
{
...
Return type cannot be declared constant
.NET methods cannot return const any type..
The const keyword is invalid there: remove it.
The most likely working code:
public static class TestClass
{
public const int constValue1 = 1;
public const int constValue2 = 2;
public const int constValue3 = 3;
}
enum TestEnum
{
testVal1, testVal2, testVal3
}
public int TestFunction(TestEnum testEnum)
{
switch (testEnum)
{
case TestEnum.testVal1:
return TestClass.constValue1;
case TestEnum.testVal2:
return TestClass.constValue2;
case TestEnum.testVal3:
return TestClass.constValue3;
}
return 0; // all code paths have to return a value
}
First, according to const (C# Reference):
The const keyword is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable is constant, which means it cannot be modified.
In C#, const is only used as a modifier of a field (like TestClass.constValue1) or local variable, not suitable for a function return type.
So you are from the great C/C++ kingdom. Thinking with my very limited knowledge to C/C++, const return types in C/C++ is only meaningful with pointers...
// C++ code
const int m = 1;
// It returns a pointer to a read-only memory
const int* a(){
return &m;
}
But unless you are using unsafe code, there is no pointer in C#. There are only value types (like int/DateTime/TestEnum/structs) and reference types (like string/classes). There are a lot more to read about on the web.
So as int is a value type in C#, when you returns it, it gets copied. So even if you are returning a "constant int" the returned value is not a constant and modifying the return value will not "change the constant and cause a SegFault".
Well, I forgot to answer your questions...
How exactly the function's return type would be? (I am using object return type and this does not throw any error)
Like what I showed in the code above, int.
const int blah = 1 only declares a variable/field blah of type int which one must not modify it (by doing blah = 2). In C# const int is not a type.
Is there any other option to achieve the same?
Well... I think I don't actually need to answer this...
class app {
public int x = 3;
static void Main(string[] args)
{
}
}
it's possible get the memory address allocated by x variable?
the example can be in C, C++, C# or D.
I hope it is clear
Thanks in advance
The ampersand (&) is the "address-of" operator in most C-like languages:
int x;
printf("Address of x is %p\n", &x);
The return value of & is effectively a pointer to its operand.
In C and in C++ this is fairly straight-forward. I'll give the example in C++:
struct App
{
int x;
App() : x(3) { }
};
int main()
{
App a;
int * p = &a.x; // address goes here
}
There is of course no such thing as "the variable App::x", since App is only the type. Each instance of this type, such as a in the example, carries its own set of member variables, and a pointer to the member variable is readily obtained. (The same is true for plain data structs in C.)
Note that C++ has another, related feature: Member pointers. This allows us to form the opaque value int App::*pm = &App::x which by itself doesn't point to anything, but only carries information about the offset of App::x inside the class, if you will. This animal can be used together with an instance to obtain the actual value, e.g. a.*pm.
Skipping D and E. C# and F# (and other CLR languages) - there is no fixed addres for any partcular variable in general. One can use managed debugger (i.e. WinDbg + SOS) to find address of any particular variable, or use fixed along with interop classes.