In C#, is "this" keyword required? [duplicate] - c#

This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
Closed 9 years ago.
In the following constructor, is the 'this' keyword required? I know I can remove it, it complies and everything is okay. If I omit 'this' will that cause problems for me down the road? Is ommission of 'this' considered bad practice?
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}

No, this is purely optional in almost all cases. The only reason it is required in your example is to disambiguate between local variables and parameters and member variables that happened to have the same identifier name.
You could avoid the use of this by renaming either the parameter or the field to something unique.

Yes, you need it in your code example. C# will always assume you mean local variable, so if a member variable and a local variable exist with the same name, you must use this, otherwise it will be assumed that you are referring to the local variable.
In your code example, if you neglect the this, you are effectively assigning name (or alias)'s value to itself (thus accomplishing nothing).

in the case below this is absolutely required. But you can get around it by choosing variable names carefully. In my humble opinion, there is nothing wrong with the example below and I do not mind having to use this. In fact, I often use this even when it is not required just to prompt intellisense and auto-complete in my IDE.
internal class Something
{
private string name;
public Something(string name)
{
this.name = name;
}
}

It's optional, unless you have a member variable named 'name', in that case, your line there will be assigning to itself.
I always like to access all member variables with "this", just to be explicit. Some people like to use "_" as a prefix, or even "m".

In C# it is most common to either name the private variable _Name or m_Name. This also makes it easy to visually match up Properties because if you have a property Name, which uses a local private variable _Name, it is easy to see quickly what it is for.
Without the this keyword in your example, all you are doing is assigning the local variable to the local variable (and not to the private variable). Which is why it compiles, but won't do what you think it is doing.

in your example, if you don't use "this" something worse will happen: "Variable Hiding"

Related

c# "this" not required? [duplicate]

This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
Closed 9 years ago.
In the following constructor, is the 'this' keyword required? I know I can remove it, it complies and everything is okay. If I omit 'this' will that cause problems for me down the road? Is ommission of 'this' considered bad practice?
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
No, this is purely optional in almost all cases. The only reason it is required in your example is to disambiguate between local variables and parameters and member variables that happened to have the same identifier name.
You could avoid the use of this by renaming either the parameter or the field to something unique.
Yes, you need it in your code example. C# will always assume you mean local variable, so if a member variable and a local variable exist with the same name, you must use this, otherwise it will be assumed that you are referring to the local variable.
In your code example, if you neglect the this, you are effectively assigning name (or alias)'s value to itself (thus accomplishing nothing).
in the case below this is absolutely required. But you can get around it by choosing variable names carefully. In my humble opinion, there is nothing wrong with the example below and I do not mind having to use this. In fact, I often use this even when it is not required just to prompt intellisense and auto-complete in my IDE.
internal class Something
{
private string name;
public Something(string name)
{
this.name = name;
}
}
It's optional, unless you have a member variable named 'name', in that case, your line there will be assigning to itself.
I always like to access all member variables with "this", just to be explicit. Some people like to use "_" as a prefix, or even "m".
In C# it is most common to either name the private variable _Name or m_Name. This also makes it easy to visually match up Properties because if you have a property Name, which uses a local private variable _Name, it is easy to see quickly what it is for.
Without the this keyword in your example, all you are doing is assigning the local variable to the local variable (and not to the private variable). Which is why it compiles, but won't do what you think it is doing.
in your example, if you don't use "this" something worse will happen: "Variable Hiding"

Get the name of the parameter that is passed to function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
get name of a variable or parameter
I have this function.
public void AddVariable( String str)
{
Response.Write(str); // will write the value of str
}
But I need to write the name of the string variable that is passed into the function.
For example:
String temp = "test Variable";
AddVariable(temp);
Here I need to get the name of the variable inside my function, Instead of value.
ie, I need to get 'temp' inside my function, Instead of 'test Variable'.
Is it possbile?
You could get the name of the variable inside the function ("str"), but you cannot get the name of the variable that was passed into the function unless you pass it in as a second parameter.
It doesn't make sense to get the name of the variable passed to the function because there may not have even been a variable if a literal was passed such as AddVariable("test variable").
You don't need parameter name (possible from reflection) but rather a variable name that has been passed as a parameter. AFAIK, for all practical purpose, this is not possible for the code within the function.
On the other hand, it's as such possible to do the code analysis of all assemblies loaded in the app-domain and find all invocations to your method and then do the stack-walk to determine possible invocation so that you may able to nail the variable name in the calling method (again if there can be many invocations in calling method, making it difficult to guess the variable name and you have to then rely on IL offset etc) but its just too convoluted.
Perhaps, you can state the reason for such requirements, there can be some alternative. For example, you can get and log stack trace within your method code that can be used for say trouble-shooting.

What is the difference b/w public variable and public auto property [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between Property and Field in C#
I know it is a very basic question but I cannot read any valid answer after searching
E.g
public string abc;
public string abc { get; set; }
Please describe this.
(About my terminology: "field" = public variable, "property" = get/set)
One thing to be mentioned additionally to the differences in usage: A property, unlike a field, gets compiled to a method (I think it's called something like get_abc internally). Declaring an auto property from beginning on has therefor two advantages:
1) No problems with reflection. If some reflection code is based on the value being a field, and later you think "well, now I'd like to add null testing" and change to a property, then the reflection code will eventally fail (unless you expected that in the reflection, but that would be extra effort for nothing imho)
2) "Warning" of possible side effects. Fields can only change their values, methods can do arbitrary things to a class. So, declaring a property from beginning on signalizes the possibility of other changes happening in the background. (Of course one shouldn't do weird stuff in a setter, but sometimes it isn't impractical to get additional initialization from one value provided; e.g. measuring the length of a list)
I also would say that it's good style to use properties wherever possible. Especially for the two reasons provided, but also for consistency.
Variables store direct value but property are a window to your class and its variables.
Even though they work the same(almost), one very good thing with field is that if you want to do some extra work with field (like validation or doing any calculations) you can do so.
This will explain you
public string _abc;
public string abc
{
get
{
return _abc;
};
set
{
if (value == null)
_abc = "";
else
_abc = value;
};
}
Here if null is passed to property abc then it will be checked it and an empty value will be assigned to _abc. otherwise value.
If we wanted this with a variable. every where we had to do this.
if(foo == null) // here foo is some string
_abc = ""
else
_abc = foo;
with property this can be done like
abc = foo;
Now it will check for in the set section of property.
Properties can contain some code on setting/getting the value. Public variables can't and will not contain any code when you access them. This is a huge difference.
Using a property you're saying to whomever uses you're code that there might be some code behind the value now or in the future.
Using a public variable you're saying its just a boring old field that will contain some value.
One reason for using an auto property instead of a Field is compatibility.
For example, when you assign a field, the CLR does just that. It sets the field.
When you have a property (auto or not), and you type
someObject.Whatever = "Value";
it looks like you are assigning a field, but in reality, the C# compiler inserts something like this for you:
someObject.set_Whatever("Value");
That's not the same as setting a field. And if you have a field and change it to a property later (e.g. if you want to implement change notifications or things like that), you will have to recompile all assemblies that used the original field, since assigning a Field requires different code than setting a property (no matter if auto or not).
There is almost never a reason to use a public field. Automatic properties can be inlined at runtime, so there would be no performance difference. And they leave the possibility open to add additional logic to your get / set methods without having to recompile dependent assemblies.
Same difference as a property over public variable such as property support binding but variable not.

C# Declaration Question

I am very new to c#, but I am learning more every day.
I am wondering what the following means:
private DataIdentifier dataIdentifier;
Why do they write like this? It is almost the same name but they use big D in the first word.
This declares a member variable (i.e. a "field") in a class.
private is the access modifier. It specifies that the variable can only be accessed from within the class. The access modifier is optional, and defaults to private (but it's considered best practice to be explicit anyway).
DataIdentifier is the type of the variable (i.e., only instances of the DataIdentifier class can be put into the variable).
dataIdentifier is the name of the variable. This is what you write in the code when you want to access the object that's being held in the variable.
Note: Technically, objects are not actually "in" a variable; the variable is typically a pointer to a location in memory where the object actually is (it "references" an object).
As you learn more C#, you'll see a common idiom where the name of the property is the same as the name of the type:
public SpaceShip SpaceShip;
This is allowed since the compiler is smart enough to know whether you're referring to the variable or the class itself when you type SpaceShip in your code, just from the context.
DataIndentifier is a type.
dataIdentifier is the name of a field of that type.
The similarity of the names is entirely coincidental.
private DataIdentifier dataIdentifier;
DataIdentifier is a Type whereas dataIdentifier is a variable declared of that type
Like
private int a;
where int is a type and a is a variable of type Int
This question has been answered several times over, but I would like to instead recommend what I believe to be the BEST introductory book for C#. Even if you don't like learning from books, you'll like this one:
Head First C#
Check out the free chapters and if you like it, buy it. I guarantee you won't be sorry. Hope it helps.
DISCLAMER: I am in no way affiliated to OReilly Media or any of its subsidiaries... ;)
It is just another type of notation. It's really a silly variable name. I wouldn't recommend you follow the same convention. DataIdentifier is the class/object type. private is the access modifier.
The DataIdentifier is the type (class or struct) and dataIdentifer is the name.
DataIdentifier is the type of the variable
dataIdentifier is the name of the variable (it is of the type DataIdentifier)
C# is case sensitive. DataIdentifier and dataIdentifier are two different things.
Here DataIdentifier is the type and dataIdentifier is the variable.
It may be useful for you to relate the example to the actual grammar of C#.
field-declaration:
attributesopt field-modifiersopt type variable-declarators ;
field-modifiers:
field-modifier
field-modifiers field-modifier
field-modifier:
new
public
protected
internal
private
static
readonly
volatile
variable-declarators:
variable-declarator
variable-declarators , variable-declarator
variable-declarator:
identifier
identifier = variable-initializer
variable-initializer:
expression
array-initializer

Why doesn't C# allow for global inferred types i.e. using var?

I know it can't be done since using var can only be done for local variables. I'm just wondering if anyone has a theory why the C# team thought this should be so. e.g. what would be wrong with this:
public class SomeClass
{
var someString = "hello"; //not cool
public SomeClass()
{
var someOtherString = "hello"; //cool
}
}
If someString is initialised then it is obviously a string just like someOtherString. Why is there one rule for local variables and another for globals?
Duplicate, hence CW.
See the posting by Eric Lippert:
Let me give you a quick oversimplification of how the C# compiler works. First we run through every source file and do a "top level only" parse. That is, we identify every namespace, class, struct, enum, interface, and delegate type declaration at all levels of nesting. We parse all field declarations, method declarations, and so on. In fact, we parse everything except method bodies; those, we skip and come back to them later.
[...]
if we have "var" fields then the type of the field cannot be determined until the expression is analyzed, and that happens after we already need to know the type of the field.
Its to do with the amount of searching the compiler would have to do resolve the type.

Categories

Resources