In C# if i declare a constant variable is any memory allocated to it as it acts as a compile time replacement? How long is the variable's life?
C# – In C# what is lifetime or lifespan of constant variable
cconst
Related Solutions
I would take it a step further, and bring it to 3 cases. Although there are variations on each, this is the rules I use the majority of the time when C# programming.
In case 2&3, always go to the Property Accessor (not the field variable). And in case 1, you are saved from even having to make this choice.
1.) Immutable property (passed in to constructor, or created at construction time). In this case, I use a field variable, with a read-only property. I choose this over a private setter, since a private setter does not guarantee immutability.
public class Abc
{
private readonly int foo;
public Abc(int fooToUse){
foo = fooToUse;
}
public int Foo { get{ return foo; } }
}
2.) POCO variable. A simple variable that can get/set at any public/private scope. In this case I would just use an automatic property.
public class Abc
{
public int Foo {get; set;}
}
3.) ViewModel binding properties. For classes that support INotifyPropertyChanged, I think you need a private, backing field variable.
public class Abc : INotifyPropertyChanged
{
private int foo;
public int Foo
{
get { return foo; }
set { foo = value; OnPropertyChanged("foo"); }
}
}
Is there appropriate way to declare variables name to avoid memory or space issues.
Variable names are mostly for humans. The C# compiler does not care about your name as long as it obeys language rules. So, to answer your question, there are no memory or space issues that could result just from the name. However, there are problems that could result from using the same name with different scoping but this is not what you are asking about.
bool noExp = true; bool willNotExpireEver = true;
two variable should occupy same space in memory that is size of bool rite?
No. In general each variable occupies different memory location for a period of time in the program's execution life time. This duration depends on where it is declared and when it was disposed of.
now where do variable names go? I mean they are somehow characters after all, where do they get space?
The role of the compiler is to take your friendly English like names and convert them to addresses to be used by the binary code. That is why the English name does not really matter to the compiler.
so is it better to name variables short or it does not matter?
As suggested by other answers, there are some common conversions on how to name variables. This is a matter of taste, and due to some lessons learned by others. In general, don't include the variable type as part of the name.
Best Answer
Literal
const
s are compile time replacements. Section 14.16 in the spec I have handy: