Using consts in static classes - c#

I was plugging away on an open source project this past weekend when I ran into a bit of code that confused me to look up the usage in the C# specification.
The code in questions is as follows:
internal static class SomeStaticClass
{
private const int CommonlyUsedValue = 42;
internal static string UseCommonlyUsedValue(...)
{
// some code
value = CommonlyUsedValue + ...;
return value.ToString();
}
}
I was caught off guard because this appears to be a non static field being used by a static function which some how compiled just fine in a static class!
The specification states (§10.4):
A constant-declaration may include a
set of attributes (§17), a new
modifier (§10.3.4), and a valid
combination of the four access
modifiers (§10.3.5). The attributes
and modifiers apply to all of the
members declared by the
constant-declaration. Even though
constants are considered static
members, a constant-declaration
neither requires nor allows a static
modifier. It is an error for the same
modifier to appear multiple times in a
constant declaration.
So now it makes a little more sense because constants are considered static members, but the rest of the sentence is a bit surprising to me. Why is it that a constant-declaration neither requires nor allows a static modifier? Admittedly I did not know the spec well enough for this to immediately make sense in the first place, but why was the decision made to not force constants to use the static modifier if they are considered static?
Looking at the last sentence in that paragraph, I cannot figure out if it is regarding the previous statement directly and there is some implicit static modifier on constants to begin with, or if it stands on its own as another rule for constants. Can anyone help me clear this up?

UPDATE: This question was the subject of my blog on June 10th, 2010. Thanks for the great question!
why was the decision made to not force constants to use the static modifier if they are considered static?
Suppose constants are considered to be static. There are three possible choices:
Make static optional: "const int x..." or "static const int x..." are both legal.
Make static required: "const int x..." is illegal, "static const int x..." is legal
Make static illegal: "const int x..." is legal, "static const int x..." is illegal.
Your question is why did we choose (3)?
The design notes from 1999 do not say; I just checked. But we can deduce what was probably going through the language designer's heads.
The problem with (1) is that you could read code that uses both "const int x..." and "static const int y..." and then you would naturally ask yourself "what's the difference?" Since the default for non-constant fields and methods is "instance" unless "static", the natural conclusion would be that some constants are per-instance and some are per-type, and that conclusion would be wrong. This is bad because it is misleading.
The problem with (2) is that first off, it is redundant. It's just more typing without adding clarity or expressiveness to the language. And second, I don't know about you, but I personally hate it when the compiler gives me the error "You forgot to say the magic word right here. I know you forgot to say the magic word, I am one hundred percent capable of figuring out that the magic word needs to go there, but I'm not going to let you get any work done until you say the magic word".
The problem with (3) is that the developer is required to know that const logically implies static. However, once the developer learns this fact, they've learned it. It's not like this is a complex idea that is hard to figure out.
The solution which presents the fewest problems and costs to the end user is (3).
It is interesting to compare and contrast this with other places in the language where different decisions were made.
For example, overloaded operators are required to be both public and static. In this case, again we are faced with three options:
make public static optional,
make it required, or
make it illegal.
For overloaded operators we chose (2). Since the natural state of a method is private/instance it seems bizarre and misleading to make something that looks like a method public/static invisibly, as (1) and (3) both require.
For another example, a virtual method with the same signature as a virtual method in a base class is supposed to have either "new" or "override" on it. Again, three choices.
make it optional: you can say new, or override, or nothing at all, in which case we default to new.
make it required: you have to say new or override, or
make it illegal: you cannot say new at all, so if you don't say override then it is automatically new.
In this case we chose (1) because that works best for the brittle base class situation of someone adds a virtual method to a base class that you don't realize you are now overriding. This produces a warning, but not an error.
My point is that each of these situations has to be considered on a case-by-case basis. There's not much general guidance here.

Basically, const implies static already, since the value cannot be changed at runtime. There's no reason for you to ever declare static const, since it's already implied, and the language designers decided to make the language syntax reflect that.
The specification language is basically saying "Const is always static, so you can't explicitly say static and const since it's redundant."

It isn't required or allowed because it's redundant. If all const members are static, then only confusion can arise from allowing some of them to be specified as static and some of them not to be.

Another reason to disallow declare constants as static is that from CLR point of view the constants are not not stored in memory along with other static fields of the type.
The constants don't have memory address and you cannot get reference to the constant value (the only exception is string constants). At runtime the type holding constant definition won't be loaded if other static/nonstatic members are not referenced. If it is the only type in the assembly, you can even safely delete it's DLL from the disk after compilation.
So, the constants are 'static' only in terms of 'may be referenced from static methods'. Constants do not have any other 'static' properties as other static type members do.

Related

Difference ways of calling methods within the same class in C# [duplicate]

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.

confused about the keyword this C# [duplicate]

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.

Const methods in C#

In C++, you can define a constant method like so:
int func_that_does_not_modify_this(int arg) const {}
Placing const at the end of the function prevents you from accidentally modifying any of the internal properties, and lets the caller know that this function won't modify the object.
Is there a concept like this in C#?
No, there's nothing like that in C#. It's been talked about a lot, but it's quite difficult to make const work in such a way that it's verifiable at compile time, can't be cast away like it can in C++, and is still reasonably easy to actually use without everyone having to get it perfectly right when they design their own classes.
Of course, if you design your own types to be immutable (like string) then all instance methods on it are effectively const. This isn't always practical, but it's an important technique to use where appropriate.
Code Contract should provide such a feature in the future. Currently, you can mark a method as [Pure], which means it doesn't have any side-effects (i.e. doesn't modify any of the class members). Unfortunately, the current version of the tools does not enforce this rule, so using that attribute is for documentation purpose only. I'm pretty sure that in future version, it will be enforced via static-analysis (i.e. at compile-time), or at least that's what the documentation hints at.
Related SO questions: Pure functions in C#
No. There's nothing similar in C#.
No const & either.
As Jon points out you can obviously implement a const method, but there's no way beyond documentation to let the caller know that a method is const.
C# 8.0 adds support for C++ style const methods, but only to structs. You can add a readonly modifier to a method deceleration to make any modifications to state within it a compiler warning (which you can define as an error if you wish). A readonly struct method may still call a non-readonly method, but that method will be called on a copy of the struct to prevent any changes to the original data.
For more information:
📄 What's new in C# 8.0 | Readonly members
📄 Structure types (C# reference) | readonly instance members
▶️ What's new in C# 8 - Part 2 | Read Only Members

Why are const parameters not allowed in C#?

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.

Why does C# not allow const and static on the same line?

Why does C# not allow const and static on the same line? In Java, you must declare a field as 'static' and 'final' to act as a constant. Why does C# not let you declare const's as final?
I make the further distinction that in Java, every interface is public and abstract, whether this is explicitly declared or not. Aren't const's effectively static in nature? WHy does C# balk at this?
const and static really do mean different things, different storage mechanism, different initialisation. static is read/write, therefore must have memory allocated for storage and must be initialised at runtime. A static can be initialised with a literal value or an expression. In contrast, a const is immutable and must be initialised with a compile time constant (typically a literal value, or an expression that can be fully evaluated at compile time). The value is known at compile time so it can be embedded directly in the generated code, therefore requires no storage to be allocated at runtime.
Constants by their nature are static, so that would be redundant.
As said before, static final in Java is the same as static readonly in C#. In fact, you are saying that this member is static and its content can't be changed. Also you can specify in both cases the value from static constructor.
But const in C# is completely different thing. It's more along the lines of constants in C (DEFINE directives) but with OOP in mind. It's static because it's constant - every instance would have this constant with the same value, no constructor can set it. Also it's possible that someone would like to access the constant without having to create an instance. When you think about it non-static constant just doesn't make sense. You can almost say that constants are not part of an object - they just use it to provide context, a strong name.
Java doesn't have an equivalent to const. You can read somewhere that static final is equivalent to DEFINE but that's just so vague. Completely different mechanism, nothing in common but in the end result in the code is the same - better maintainability and readability of the code.
You just have to stop thinking about constants in C# as static members because they are not. Think of them as OOP version of DEFINE. When you consider encapsulation only reason for final and readonly fields is to prevent your own code from accidently changing its value. And that doesn't sound like constant to me.
Sumary:
final = readonly
static final = static readonly
N/A = const
It is true that a C# const implies static BUT, C# has an equivalent to Java's final keyword in the keyword readonly.
So, in fact, C# allows a const final, it is static readonly in C#.
Because allowing and not requiring modifiers that are inherent can cause confusion. If you see
static const int A = 3
const int B = 5
you may believe that they are 2 different kinds of constants.
Even VB 2008 (which can be very verbose if you wish) doesn't allow that.

Categories

Resources