Can anyone tell what is the point of a constant in C#?
For example, what is the advantage of doing
const int months = 12;
as opposed to
int months = 12;
I get that constants can't be changed, but then why not just... not change it's value after you initialize it?
If the compiler knows that a value is constant and will never change, it can compile the value directly into your program.
If you declare pi to be a constant, then every time it sees pi / 2 the compiler can do the computation and insert 1.57... directly into the compiled code. If you declare pi as a variable, then every time your program uses pi / 2 the computer will have to reference the pi variable and multiply it by 0.5, which is obviously slower.
I should also add that C# has readonly which is for values that the compiler cannot compute, but which cannot change for the duration of your program's execution. For example, if you wanted a constant ProgramStartTime, you would have to declare it readonly DateTime ProgramStartTime = DateTime.Now because it has to be evaluated when the program starts.
Finally, you can create a read-only property by giving it a getter but no setter, like this:
int Months { get { return 12; } } but being a property it doesn't have to have the same value every time you read it, like this:
int DaysInFebruary { get { return IsLeapYear ? 29 : 28 } }
The difference between "can't change" and "won't change" only really becomes apparent when one of the following situations obtains:
other developers begin working on your code,
third-parties begin using your code, or
a year passes and you return to that code.
Very similar questions arise when talking about data accessibility. The idea is that you want your code to provide only as much flexibility as you intend, because otherwise someone (possibly you) will come along and do something you did not intend, which leads to bugs!
If you never make mistakes, nobody on any team you work with ever makes mistakes, you never forget the exact purpose of a variable you've defined even after coming back to code you haven't looked at in months or years, and you and everyone you work with 100% reliably recognizes, understands and follows your intention of never changing a const value when you haven't bothered to use a built-in language construct that both clearly indicates and enforces constness, then no, there's no point.
If any one of those things ever turns out not to be the case, that's the point.
As for me, I find that even when I'm at my most lucid, remembering more than seven things at once is pretty close to impossible, so I'll take all the help I can get to prevent mistakes, especially when the cost is a single keyword. If you're smarter than me, and you never have to work on a team with someone less smart than you, then do whatever you want.
In some cases, there may be some compiler optimizations that can be done based on constness (constant folding, for one, which collapses expressions consisting of constants at compile-time). But usually, that's not the point.
Keep in mind you may not be the only person using the value. Not only can't you change it, but nobody using your code (as a library, for example) can change it.
And marking it as constant also makes your intent clear.
That's it. The you tell the compiler it can never change, and the compiler can optimise much better knowing that it is immutable.
Using constants programmers have the advantage of Readability over actual Value like
const double PI = 3.14159;
It also speeds up computation compared to variables by inserting values at compile time and not being inferred from a register/memory location.
For several reasons:
You want to differentiate certain values that have certain meaning from other variables.
You may later forget you are not meant to change a value, and cause unforeseen behavior.
Your code may be used by other people an they may change it (especially if you're developing a library or an API).
Because every thing that can go wrong usually will - so prevent it by making such errors discoverable at compile time rather than runtime.
Declaring a value 'const' brings the compiler into play to help you enforce personal discipline, by not allowing any changes to that value.
Also, it will catch unexpected errors due to side-effects of passing a value (that you intend to treat as a constant) into a method that takes a 'ref' parameter and could conceivably alter the value unexpectedly.
Strictly speaking, "const" isn't necessary. Python, for example, has neither "const" nor "private"; you specify your intent with the naming convention of THIS_IS_A_CONSTANT and _this_is_private.
C#, however, has a design philosophy of catching errors at compile time rather than runtime.
All about readability, different semantics for programmer is true and you should know all of it.
But constants in C# (rather in .net) has very different semantics (in terms of implementation) as compared with ordinary variables.
Because a constant value never changes, constants are always considered to be part of the
defining type. In other words, constants are always considered to be static members, not
instance members. Defining a constant causes the creation of metadata. When code refers to a constant symbol, compilers embed the value in the emitted Intermediate Language (IL) code.
These constraints mean that constants don’t have a good cross-assembly versioning story, so you should use them only when you know that the value of a symbol will never change.
The "point" is so that you can use a single program-wide variable and have only one spot to change it.
Imagine if you were making a video game that relied on knowing the FPS (frames per second) in 100 different code files. So pretend the FPS was 50... and you had the number "50" in all those files and functions... then you realize that you wanted to make it 60 FPS... instead of changing those 100 files, you would just change this:
const int FRAMES_PER_SECOND = 60;
and in those files / functions, you would use the FRAMES_PER_SECOND variable.
By the way, this has nothing to do with C#... constants are in tons of languages.
It is a case of being explicit of your intention.
If you intend to change value, then do not use 'const'.
If you do not intend to change value, then use 'const'.
That way both compiler and third party (or yourself if you read your code after long time) can know what you intended. If you or somebody makes a mistake of changing value, then compiler can detect it.
And anyways, to use 'const' is not mandatory. If you think, you can handle 'constancy' yourself (without wanting compiler to detect mistake), then do not use 'const' ;-).
You should define a variable as "const" when you know the value of this will remain constant through out your application. So once you define a const, it value must be determinable at compile time and this value will be saved into the assembly's metadata. Some more important points abt Const:
A const can be defined only for types your compiler treats as primary types.
Constants are always considered to be the part of defining type.
They are always considered to be Static members.
Constants value are always embedded directly into the code, so constants dont require any memory to be allocated to them at run time.
Because of this embedding of the value into metadata, when somebody change the value of the const (in the assembly where the const is defined) due to versioning or some other requirement
then the user of the dll has to recompile his own assembly. And this issue can be avoided using "readonly" keyword.
One of the rule that many programmers follow is: Never hard-code any variables / except 0.
that means, instead of doing
for(int i=0; i<100; i++) {}
should do
const loopCount = 100;
....
for (int i=0; i<loopCount; i++) {}
I think using const is a good reason to replace this. And indeed, there's much more reason to this:
Optimize for compiler - memory, performance.
Tell the programmer that follow your work, this is CONSTANT
If you need to refactor, change your mind in the number, you know where to go. And make sure no other places in the code would change this.
Related
I wish to encode hard coded value of a const Point struct.
Why does the compiler not allow neither internal, nor arbitrary structs to be replaced during compilation? Since the internal bitwise representation can be established at compile time (in both cases), there is no apparent reason for the restriction.
My question is: Is there a way to hard-code a predefined set of bytes in c# that can be interpreted at compile time as the appropriate type, since all structs have a predetermined memory outline.
EDIT:
To clarify: Compile time means C# -> IL byte-code as stored in the output assembly.
The use case example:
public void Draw(Bitmap bmp, Point Location = new Point(0,0)) // invalid
This is an error because the new Point(0,0) cannot be evaluated at compile time. I can pass in int X = 0, int Y = 0 or the nullable Point? Location = null and generate the struct inside of the method, or Overload the method without the optional parameters and call the main method passing in the default values, but that technique incurs a performance penalty in terms of the extra method calls required.
This may not be appropriate for all structs, since the constructor could rely on, or change, external state or randomness.
FINAL EDIT:
This is now possible. Making the question moot. Yay.
The issue was the incorrect belief that the new keyword always implied heap allocation or dynamic stack allocation, with constant arguments neither case was true.
Why does the compiler not allow neither internal, nor arbitrary structs to be replaced during compilation? Since the internal bitwise representation can be established at compile time (in both cases), there is no apparent reason for the restriction.
All not-implemented features are not implemented for the same reason. To be implemented, a feature must be thought of, judged to be appropriate, designed, specified, implemented, tested, documented and shipped. All those things must happen. For your proposed feature, none of them happened. Therefore, no feature.
Programming language designers are not required to provide a justification for why a feature was not implemented. Rather, the people who want the feature are required to provide a reason why programming language designers should spend their valuable time implementing a feature that you want.
The C# design process is open, and the compiler source code is available. Why have you not designed and implemented the feature? If it is fair for you to ask the designers that question, it's fair for them to ask it of you! You're a computer programmer; get busy programming computers and build the feature if you think it is worthwhile, and then convince the language team to accept your pull request. If you don't think it is worth your time to do that, well, probably the language designers feel the same way.
My question is: Is there a way to hard-code a predefined set of bytes in c# that can be interpreted at compile time as the appropriate type, since all structs have a predetermined memory outline.
I'm not sure what you mean by "at compile time"; can you clarify?
There are ways to store byte arrays in an assembly, sure. Make a C# program with a byte array initialized to all constant values and ildasm the assembly; you'll see the code that the C# compiler generates to get the byte array image out of the metadata and into the array.
You could implement similar shenanigans to get a byte array, fix the array in place, and then use unsafe pointer magic to reinterpret the array bytes as struct bytes. That sounds extraordinarily dangerous, and might mess up the performance of the garbage collector. I would not wish to do so myself, but you seem pretty keen on this feature, so go for it and report back what you find out!
Alternatively, C++/CLI probably implements the feature you want; I've never used it but that seems like the sort of thing it would do. You could write a little program in C++/CLI that does what you want, and then either (1) use that program's assembly as a dependency of your assembly, (2) compile it as a netmodule link it in to your assembly via the usual netmodule linking gear (yuck) or (3) deduce how they implemented the feature and then do the same.
You can convert a struct into byte array and encode a byte array. It may work like this: (please compile and fix any errors (typing through mobile))
Suppose your struct is:
public struct TestStruct
{
public int x;
public string y;
}
public byte[] GetTestByte(TestStruct c)
{
var intGuy = BitConverter.GetBytes(c.x);
var stringGuy = Encoding.UTF8.GetBytes(c.y);
var both = stringGuy.Concat(intGuy).Concat(new byte[1]).ToArray();
return both;
}
Now you can encode a byte array like:
Convert.ToBase64String(byteArray);
There is no direct way to encode a struct. Its a value type at best and probably there as legacy for C and C++
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:
In a constructor:
public Light(Vector v)
{
this.dir = new Vector(v);
}
Elsewhere
public void SomeMethod()
{
Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}
I don't mean this to sound snarky, but it doesn't matter.
Seriously.
Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office.
It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something.
I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.
There are several usages of this keyword in C#.
To qualify members hidden by similar name
To have an object pass itself as a parameter to other methods
To have an object return itself from a method
To declare indexers
To declare extension methods
To pass parameters between constructors
To internally reassign value type (struct) value.
To invoke an extension method on the current instance
To cast itself to another type
To chain constructors defined in the same class
You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.
I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:
class Vector3
{
float x;
float y;
float z;
public Vector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)
Personally, I try to always use this when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see this used consistently, they will know if they are looking at a member variable or not.
I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.
I can't believe all of the people that say using it always is a "best practice" and such.
Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.
EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers
EDIT: #Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually need it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.
I use it whenever StyleCop tells me to. StyleCop must be obeyed. Oh yes.
Any time you need a reference to the current object.
One particularly handy scenario is when your object is calling a function and wants to pass itself into it.
Example:
void onChange()
{
screen.draw(this);
}
I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.
I use it anywhere there might be ambiguity (obviously). Not just compiler ambiguity (it would be required in that case), but also ambiguity for someone looking at the code.
Another somewhat rare use for the this keyword is when you need to invoke an explicit interface implementation from within the implementing class. Here's a contrived example:
class Example : ICloneable
{
private void CallClone()
{
object clone = ((ICloneable)this).Clone();
}
object ICloneable.Clone()
{
throw new NotImplementedException();
}
}
Here's when I use it:
Accessing Private Methods from within the class (to differentiate)
Passing the current object to another method (or as a sender object, in case of an event)
When creating extension methods :D
I don't use this for Private fields because I prefix private field variable names with an underscore (_).
[C++]
I agree with the "use it when you have to" brigade. Decorating code unnecessarily with this isn't a great idea because the compiler won't warn you when you forget to do it. This introduces potential confusion for people expecting this to always be there, i.e. they'll have to think about it.
So, when would you use it? I've just had a look around some random code and found these examples (I'm not passing judgement on whether these are good things to do or otherwise):
Passing "yourself" to a function.
Assigning "yourself" to a pointer or something like that.
Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.
Compiler enforced disambiguation.
You should always use it, I use it to diferantiate private fields and parameters (because our naming conventions state that we don't use prefixes for member and parameter names (and they are based on information found on the internet, so I consider that a best practice))
I use it when, in a function that accepts a reference to an object of the same type, I want to make it perfectly clear which object I'm referring to, where.
For example
class AABB
{
// ... members
bool intersects( AABB other )
{
return other.left() < this->right() &&
this->left() < other.right() &&
// +y increases going down
other.top() < this->bottom() &&
this->top() < other.bottom() ;
}
} ;
(vs)
class AABB
{
bool intersects( AABB other )
{
return other.left() < right() &&
left() < other.right() &&
// +y increases going down
other.top() < bottom() &&
top() < other.bottom() ;
}
} ;
At a glance which AABB does right() refer to? The this adds a bit of a clarifier.
In Jakub Šturc's answer his #5 about passing data between contructors probably could use a little explanation. This is in overloading constructors and is the one case where use of this is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.
class MyClass {
private int _x
public MyClass() : this(5) {}
public MyClass(int v) { _x = v;}
}
I've found this to be a particularly useful feature on occasion.
I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)
But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.
I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:
boolean sameValue (SomeNum other) {
return this.importantValue == other.importantValue;
}
[C++]
this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:
A a;
a = a;
Your assignment operator will be written:
A& A::operator=(const A& a) {
if (this == &a) return *this;
// we know both sides of the = operator are different, do something...
return *this;
}
this on a C++ compiler
The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
using the mother class' method if you did not overloaded it in the child class.
promoting a value of a type into another type
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf instead of print. this->printf would not have compiled.
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
These are the reasons I use this.
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).
Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.
I usually delete it once I have what I was after: but this is just my style breaking through.
In terms of style, if you are a lone-ranger -- you decide; if you work for a company stick to the company policy (look at the stuff in source control and see what other people are doing). In terms of using it to qualify members, neither is right or wrong. The only wrong thing is inconsistency -- that is the golden rule of style. Leave the nit-picking others. Spend your time pondering real coding problems -- and obviously coding -- instead.
I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.
When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.
To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.
It depends on the coding standard I'm working under. If we are using _ to denote an instance variable then "this" becomes redundant. If we are not using _ then I tend to use this to denote instance variable.
I use it to invoke Intellisense just like JohnMcG, but I'll go back and erase "this->" when I'm done. I follow the Microsoft convention of prefixing member variables with "m_", so leaving it as documentation would just be redundant.
1 - Common Java setter idiom:
public void setFoo(int foo) {
this.foo = foo;
}
2 - When calling a function with this object as a parameter
notifier.addListener(this);
There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.
You can use this to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.
template <typename T>
struct base {
void f() {}
};
template <typename T>
struct derived : public base<T>
{
void test() {
//f(); // [1] error
base<T>::f(); // quite verbose if there is more than one argument, but valid
this->f(); // f is now an argument dependent symbol
}
}
Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.
At that step, without actually substituting the type, the compiler has almost no information of what base<T> could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f that seems just natural to the programmer is a symbol that the compiler must find as a member of derived or in enclosing namespaces --which does not happen in the example-- and it will complain.
The solution is turning the non-dependent name f into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f --adding the base<T> makes the symbol dependent on T and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.
The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this-> before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>) this-> is argument dependent, and we get the same result: this->f is checked in the second round, after template parameter substitution.
You should not use "this" unless you absolutely must.
There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:
In a constructor:
public Light(Vector v)
{
this.dir = new Vector(v);
}
Elsewhere
public void SomeMethod()
{
Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}
I don't mean this to sound snarky, but it doesn't matter.
Seriously.
Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office.
It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something.
I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.
There are several usages of this keyword in C#.
To qualify members hidden by similar name
To have an object pass itself as a parameter to other methods
To have an object return itself from a method
To declare indexers
To declare extension methods
To pass parameters between constructors
To internally reassign value type (struct) value.
To invoke an extension method on the current instance
To cast itself to another type
To chain constructors defined in the same class
You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.
I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:
class Vector3
{
float x;
float y;
float z;
public Vector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)
Personally, I try to always use this when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see this used consistently, they will know if they are looking at a member variable or not.
I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.
I can't believe all of the people that say using it always is a "best practice" and such.
Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.
EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers
EDIT: #Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually need it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.
I use it whenever StyleCop tells me to. StyleCop must be obeyed. Oh yes.
Any time you need a reference to the current object.
One particularly handy scenario is when your object is calling a function and wants to pass itself into it.
Example:
void onChange()
{
screen.draw(this);
}
I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.
I use it anywhere there might be ambiguity (obviously). Not just compiler ambiguity (it would be required in that case), but also ambiguity for someone looking at the code.
Another somewhat rare use for the this keyword is when you need to invoke an explicit interface implementation from within the implementing class. Here's a contrived example:
class Example : ICloneable
{
private void CallClone()
{
object clone = ((ICloneable)this).Clone();
}
object ICloneable.Clone()
{
throw new NotImplementedException();
}
}
Here's when I use it:
Accessing Private Methods from within the class (to differentiate)
Passing the current object to another method (or as a sender object, in case of an event)
When creating extension methods :D
I don't use this for Private fields because I prefix private field variable names with an underscore (_).
[C++]
I agree with the "use it when you have to" brigade. Decorating code unnecessarily with this isn't a great idea because the compiler won't warn you when you forget to do it. This introduces potential confusion for people expecting this to always be there, i.e. they'll have to think about it.
So, when would you use it? I've just had a look around some random code and found these examples (I'm not passing judgement on whether these are good things to do or otherwise):
Passing "yourself" to a function.
Assigning "yourself" to a pointer or something like that.
Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.
Compiler enforced disambiguation.
You should always use it, I use it to diferantiate private fields and parameters (because our naming conventions state that we don't use prefixes for member and parameter names (and they are based on information found on the internet, so I consider that a best practice))
I use it when, in a function that accepts a reference to an object of the same type, I want to make it perfectly clear which object I'm referring to, where.
For example
class AABB
{
// ... members
bool intersects( AABB other )
{
return other.left() < this->right() &&
this->left() < other.right() &&
// +y increases going down
other.top() < this->bottom() &&
this->top() < other.bottom() ;
}
} ;
(vs)
class AABB
{
bool intersects( AABB other )
{
return other.left() < right() &&
left() < other.right() &&
// +y increases going down
other.top() < bottom() &&
top() < other.bottom() ;
}
} ;
At a glance which AABB does right() refer to? The this adds a bit of a clarifier.
In Jakub Šturc's answer his #5 about passing data between contructors probably could use a little explanation. This is in overloading constructors and is the one case where use of this is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.
class MyClass {
private int _x
public MyClass() : this(5) {}
public MyClass(int v) { _x = v;}
}
I've found this to be a particularly useful feature on occasion.
I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)
But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.
I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:
boolean sameValue (SomeNum other) {
return this.importantValue == other.importantValue;
}
[C++]
this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:
A a;
a = a;
Your assignment operator will be written:
A& A::operator=(const A& a) {
if (this == &a) return *this;
// we know both sides of the = operator are different, do something...
return *this;
}
this on a C++ compiler
The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
using the mother class' method if you did not overloaded it in the child class.
promoting a value of a type into another type
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf instead of print. this->printf would not have compiled.
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
These are the reasons I use this.
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).
Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.
I usually delete it once I have what I was after: but this is just my style breaking through.
In terms of style, if you are a lone-ranger -- you decide; if you work for a company stick to the company policy (look at the stuff in source control and see what other people are doing). In terms of using it to qualify members, neither is right or wrong. The only wrong thing is inconsistency -- that is the golden rule of style. Leave the nit-picking others. Spend your time pondering real coding problems -- and obviously coding -- instead.
I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.
When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.
To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.
It depends on the coding standard I'm working under. If we are using _ to denote an instance variable then "this" becomes redundant. If we are not using _ then I tend to use this to denote instance variable.
I use it to invoke Intellisense just like JohnMcG, but I'll go back and erase "this->" when I'm done. I follow the Microsoft convention of prefixing member variables with "m_", so leaving it as documentation would just be redundant.
1 - Common Java setter idiom:
public void setFoo(int foo) {
this.foo = foo;
}
2 - When calling a function with this object as a parameter
notifier.addListener(this);
There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.
You can use this to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.
template <typename T>
struct base {
void f() {}
};
template <typename T>
struct derived : public base<T>
{
void test() {
//f(); // [1] error
base<T>::f(); // quite verbose if there is more than one argument, but valid
this->f(); // f is now an argument dependent symbol
}
}
Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.
At that step, without actually substituting the type, the compiler has almost no information of what base<T> could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f that seems just natural to the programmer is a symbol that the compiler must find as a member of derived or in enclosing namespaces --which does not happen in the example-- and it will complain.
The solution is turning the non-dependent name f into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f --adding the base<T> makes the symbol dependent on T and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.
The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this-> before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>) this-> is argument dependent, and we get the same result: this->f is checked in the second round, after template parameter substitution.
You should not use "this" unless you absolutely must.
There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.
It looks strange especially for C++ developers. In C++ we used to mark a parameter as const in order to be sure that its state will not be changed in the method. There are also other C++ specific reasons, like passing const ref in order to pass by ref and be sure that state will not be changed. But why can't we mark as method parameters const in C#?
Why can't I declare my method like the following?
....
static void TestMethod1(const MyClass val)
{}
....
static void TestMethod2(const int val)
{}
....
In addition to the other good answers, I'll add yet another reason why to not put C-style constness into C#. You said:
we mark parameter as const in order to be sure that its state will not be changed in method.
If const actually did that, that would be great. Const doesn't do that. The const is a lie!
Const doesn't provide any guarantee that I can actually use. Suppose you have a method that takes a const thing. There are two code authors: the person writing the caller and the person writing the callee. The author of the callee has made the method take a const. What can the two authors assume is invariant about the object?
Nothing. The callee is free to cast away the const and mutate the object, so the caller has no guarantee that calling a method that takes a const actually will not mutate it. Similarly, the callee cannot assume that the contents of the object will not change throughout the action of the callee; the callee could call some mutating method on a non const alias of the const object, and now the so-called const object has changed.
C-style const provides no guarantee that the object will not change, and is therefore broken. Now, C already has a weak type system in which you can do a reinterpret cast of a double into an int if you really want to, so it should not be a surprise that it has a weak type system with respect to const as well. But C# was designed to have a good type system, a type system where when you say "this variable contains a string" that the variable actually contains a reference to a string (or null). We absolutely do not want to put a C-style "const" modifier into the type system because we don't want the type system to be a lie. We want the type system to be strong so that you can reason correctly about your code.
Const in C is a guideline; it basically means "you can trust me to not try to mutate this thing". That shouldn't be in the type system; the stuff in the type system should be a fact about the object that you can reason about, not a guideline to its usage.
Now, don't get me wrong; just because const in C is deeply broken doesn't mean that the whole concept is useless. What I would love to see is some actually correct and useful form of "const" annotation in C#, an annotation that both humans and compilers could use to help them understand the code, and that the runtime could use to do things like automatic paralellization and other advanced optimizations.
For example, imagine if you could "draw a box" around a hunk of code and say "I guarantee that this hunk of code performs no mutations to any field of this class" in a way that could be checked by the compiler. Or draw a box that says "this pure method mutates the internal state of the object but not in any way that is observable outside the box". Such an object could not be safely multi-threaded automatically but it could be automatically memoized. There are all kinds of interesting annotations we could put on code that would enable rich optimizations and deeper understanding. We can do way better than the weak C-style const annotation.
However, I emphasize that this is just speculation. We have no firm plans to put this sort of feature into any hypothetical future version of C#, if there even is one, which we have not announced one way or the other. It is something I would love to see, and something which the coming emphasis on multi-core computing might require, but none of this should be in any way construed to be a prediction or a guarantee of any particular feature or future direction for C#.
Now, if what you want is merely an annotation on the local variable that is a parameter that says "the value of this parameter doesn't change throughout the method", then, sure, that would be easily done. We could support "readonly" locals and parameters that would be initialized once, and a compile-time error to change in the method. The variable declared by the "using" statement is already such a local; we could add an optional annotation to all locals and parameters to make them act like "using" variables. It's never been a very high priority feature so it has never been implemented.
One of the reasons why there's no const correctness in C# is because it doesn't exist at the runtime level. Remember that C# 1.0 did not have any feature unless it was part of the runtime.
And several reasons why the CLR does not have a notion of const correctness are for example:
It complicates the runtime; besides, the JVM didn't have it either, and the CLR basically started as a project to create a JVM-like runtime, not a C++-like runtime.
If there is const correctness at the runtime level, there should be const correctness in the BCL, otherwise the feature is pretty much pointless as far as the .NET Framework is concerned.
But if the BCL requires const correctness, every language on top of the CLR should support const correctness (VB, JavaScript, Python, Ruby, F#, etc.) That's not going to happen.
Const correctness is pretty much a language feature only present in C++. So it pretty much boils down to the same argumentation as to why the CLR does not require checked exceptions (which is a Java language-only feature).
Also, I don't think you can introduce such a fundamental type system feature in a managed environment without breaking backward compatibility. So don't count on const correctness ever entering the C# world.
I believe there are two reasons C# is not const-correct.
The first is understandibility. Few C++ programmers understand const-correctness. The simple example of const int arg is cute, but I've also seen char * const * const arg - a constant pointer to constant pointers to non-constant characters. Const-correctness on pointers to functions is a whole new level of obfuscation.
The second is because class arguments are references passed by value. This means there's already two levels of constness to deal with, without an obviously clear syntax. A similar stumbling point is collections (and collections of collections, etc).
Const-correctness is an important part of the C++ type system. It could - in theory - be added to C# as something that is only checked at compile-time (it doesn't need to be added to the CLR, and wouldn't affect the BCL unless the notion of const member methods were included).
However, I believe this is unlikely: the second reason (syntax) would be quite difficult to solve, which would make the first reason (understandibility) even more of a problem.
This is possible since C# 7.2 (December 2017 with Visual Studio 2017 15.5).
For Structs and basic types only!, not for members of classes.
You must use in to send the argument as an input by reference. See:
See:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/in-parameter-modifier
For your example:
....
static void TestMethod1(in MyStruct val)
{
val = new MyStruct; // Error CS8331 Cannot assign to variable 'in MyStruct' because it is a readonly variable
val.member = 0; // Error CS8332 Cannot assign to a member of variable 'MyStruct' because it is a readonly variable
}
....
static void TestMethod2(in int val)
{
val = 0; // Error CS8331 Cannot assign to variable 'in int' because it is a readonly variable
}
....
const means "compile-time constant" in C#, not "readonly but possibly mutable by other code" as in C++. A rough analog of C++ const in C# is readonly, but that one is only applicable to fields. Aside from that, there is no C++-like notion of const correctness in C# at all.
The rationale is hard to tell for sure, because there are a lot of potential reasons, but my guess would be desire to keep the language simple first and foremost, and uncertain advantages of implementing this second.
Ada, Pascal and many other languages support ranges, a way to subtype integers.
A range is a signed integer value which ranges from a value (first) to another (last).
It's easy to implement a class that does the same in OOP but I think that supporting the feature natively could let the compiler to do additional static checks.
I know that it's impossible to verify statically that a variabile defined in a range is not going to "overflow" runtime, i.e. due to bad input, but I think that something could be done.
I think about the Design by Contract approach (Eiffel) and the Spec# ( C# Contracts ), that give a more general solution.
Is there a simpler solution that checks, at least, static out-of-bound assignment at compile time in C++, C# and Java? Some kind of static-assert?
edit: I understand that "ranges" can be used for different purpose:
iterators
enumerators
integer subtype
I would focus on the latter, because the formers are easily mappable on C* language .
I think about a closed set of values, something like the music volume, i.e. a range that goes from 1 up to 100. I would like to increment or decrement it by a value. I would like to have a compile error in case of static overflow, something like:
volume=rangeInt(0,100);
volume=101; // compile error!
volume=getIntFromInput(); // possible runtime exception
Thanks.
Subrange types are not actually very useful in practice. We do not often allocate fixed length arrays, and there is also no reason for fixed sized integers. Usually where we do see fixed sized arrays they are acting as an enumeration, and we have a better (although "heavier") solution to that.
Subrange types also complicate the type system. It would be much more useful to bring in constraints between variables than to fixed constants.
(Obligatory mention that integers should be arbitrary size in any sensible language.)
Ranges are most useful when you can do something over that range, concisely. That means closures. For Java and C++ at least, a range type would be annoying compared to an iterator because you'd need to define an inner class to define what you're going to do over that range.
Java has had an assert keyword since version 1.4. If you're doing programming by contract, you're free to use those to check proper assignment. And any mutable attribute inside an object that should fall within a certain range should be checked prior to being set. You can also throw an IllegalArgumentException.
Why no range type? My guess is that the original designers didn't see one in C++ and didn't consider it as important as the other features they were trying to get right.
For C++, a lib for constrained values variables is currently being implemented and will be proposed in the boost libraries : http://student.agh.edu.pl/~kawulak/constrained_value/index.html
Pascal (and also Delphi) uses a subrange type but it is limited to ordinal types (integer, char and even boolean).
It is primarilly an integer with extra type checking. You can fake that in an other language using a class. This gives the advantage that you can apply more complex ranges.
I would add to Tom Hawtin response (to which I agree) that, for C++, the existence of ranges would not imply they would be checked - if you want to be consistent to the general language behavior - as array accesses, for instance, are also not range-checked anyway.
For C# and Java, I believe the decision was based on performance - to check ranges would impose a burden and complicate the compiler.
Notice that ranges are mainly useful during the debugging phase - a range violation should never occur in production code (theoretically). So range checks are better to be implemented not inside the language itself, but in pre- and post- conditions, which can (should) be stripped out when producing the release build.
This is an old question, but just wanted to update it. Java doesn't have ranges per-se, but if you really want the function you can use Commons Lang which has a number of range classes including IntRange:
IntRange ir = new IntRange(1, 10);
Bizarrely, this doesn't exist in Commons Math. I kind of agree with the accepted answer in part, but I don't believe ranges are useless, particularly in test cases.
C++ allows you to implement such types through templates, and I think there are a few libraries available doing this already. However, I think in most cases, the benefit is too small to justify the added complexity and compilation speed penalty.
As for static assert, it already exists.
Boost has a BOOST_STATIC_ASSERT, and on Windows, I think Microsoft's ATL library defines a similar one.
boost::type_traits and boost::mpl are probably your best friends in implementing something like this.
The flexibility to roll your own is better than having it built into the language. What if you want saturating arithmetic for example, instead of throwing an exception for out of range values? I.e.
MyRange<0,100> volume = 99;
volume += 10; // results in volume==100
In C# you can do this:
foreach(int i in System.Linq.Enumerable.Range(0, 10))
{
// Do something
}
JSR-305 provides some support for ranges but I don't know when if ever this will be part of Java.