Foo() vs this.Foo() [closed] - 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.
I have a co-worker who uses a C# refactoring tool. The tool for some reason perfers:
this.Foo()
over
Foo()
Now we've asked him to turn it off simply because it's annoying to have all the code re-written automatically, but that's not the point.
Am I missing something, or is this just wrong? Why on earth would I want this.Foo()?

As other answers here point out, this is largely a matter of style.
Many times a call to Foo() would be unambiguous without the this., but there are times where it might add clarity. For example:
EventHandler foo = GetEventHandlerFoo();
EventHandler baz = GetEventHandlerBar();
foo();
this.Bar();
baz();
In this case, the this. prefix helps to make the method invocation stand out from the delegate invocations.
Is this necessary? No, and Lasse V. Karlsen correctly points out that the this. is just a surrogate for a naming convention that makes it unambiguous.
But I find that I will frequently use the this.Foo prefix on local properties for a similar reason, where again it is more a matter of style.

If you want to use it, use it.
If you don't want to use it, don't use it.
There's no right answer here.
If for some reason you have a naming convention where the name alone isn't enough to determine whether you're looking at a local variable, a method parameter, an instance field, a property, or a method, you should fix the naming convention, instead of prefixing local fields with this. to distinguish them from local variables.

I think this comes down to a question of syntax vs. semantics. The argument for this.Foo() is it very explicitly denotes exactly what Foo() is and where it came from. There's no wondering if it was an argument passed in to a method, or a static class declared who-knows-where. It's a method on the current object, period. Anything less and you're giving up clear semantics in favor of tighter syntax.
The obvious argument against it: Mouse-over and ctrl+click.

It's a style thing. Sometimes people think it makes the code more clear -- apparently some people find it helpful to be explicit about the target of a method invocation. Personally, I find the spurious use of this to be distracting.

This example demonstrates how the this keyword can be used to explicitly describe a variable's scope:
class Item
{
int id;
public Item (int id)
{
this.id = id;
}
}

I always use this. since it explicitly shows where the thing is. I don't even use a refactoring tool to do it. I type it by hand.

Related

C#, .net, general programming architecture. GetType or Enum : Which is better? [closed]

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 9 years ago.
Which do you think is better..
if (thing.GetType() == typeof(thisthing))
{
//do stuff for this type of thing.
}
Or give the objects an Enum property
if (thing.TypeName == NamesEnum.thisthing)
{
//do stuff for this type of thing.
}
Neither of these is a particularly extensible or maintainable approach.
It's typically better to design this directly into a virtual method in your type hierarchy, and just call the method. This allows other classes to override and provide custom functionality as appropriate.
In your case, the thisthing type (which should be named ThisThing if you want to follow .NET naming conventions) would just have a DoStuff method which could be virtual if needed, and call it.
It depends:
if (thing.TypeName == NamesEnum.thisthing)
will run more performant then GetType() as, this a simple comparison of 2 numeric values.
But:
if (thing.GetType() == typeof(thisthing))
is more more "flexible": when you do some refactoring, change type name or whatever, this condition will still work.
But will fail in condition, if 2 types belong to 2 different assemblies, instead in first case this still will be matched as equal,as you campare not types but just enum values.
In short, there is no best approach, just most suitable for your needs.
IF you are working with basic types that don't have sub types...
your first example can be shortened nicely to
if (thing is typeof(thisthing))
Depends on the situation really. If you get to a lot of different types you're going to want a switch statement at some point, so I would say option 2 if there are going to be a lot of types.

Would you make this method Static or not? [closed]

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 10 years ago.
During a code review I presented a method quickly to the team that I had made static and one person agreed that there was no reason for it to not be static and a person disagreed saying that he would not make it static because it wasn't necessary and just to be on the safe side for future modifications and testing.
So I did quite a bit of research and obviously it's a specialized case but I would like to know what you would do in this situation and why?
(Its basically a helper method I call from a few different methods, a very low traffic page. More for my knowledge and learning on Static.)
private IEnumerable<Category> GetCategoryByID(int id, Context context)
{
var categoryQuery = from selectAllProc in context.SelectAll_sp()
where selectAllProc.CategoryID == id
select selectAllProc;
return categoryQuery;
}
Making private methods static is a form of micro-optimization; the method call is slightly faster. But the difference is almost too small to be meaningful.
Generally speaking, you should mark a method static when it:
Doesn't interact in any way with instance members, and
You would like to have the ability to call it without instantiating the class, as in Class.Method()
Ordinarily, methods like your example would go into their own static helper class, if they are used in more than one place.
If I were you I would ask my self the following questions.
Is it something which is related to type or instance of type?
If the answer is yes, I would be slightly inclined to make it static else, make it non static.
If you can give us some more information, the community can come up with some good options.
The first remark that comes to my mind is that by declaring this method static and possibly using it in multiple places in your code you are introducing a Service-locator kind of dependency.
As far as I know the main problem with it is that implicit dependencies are introduced, i.e. they can't be inferred by looking at method signatures.
As a consequence it can be much harder to assess the impact of a modification of your static method on the rest of your system.

Extension methods and static methods mismatch prototype matching in c# [closed]

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.
Having encountered a more advanced collision problem of extension and static methods I exemplified and simplified some code to:
using System;
namespace Test
{
static class EM
{
public static string To(this object o)
{
return o.GetType().ToString();
}
}
class A
{
public static string To() { return "Test.A"; }
}
class B { }
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
object o = null;
o.To();
B b = null;
b.To();
A a = null;
a.To();
A.To();
}
}
}
I got myself suprised when the .NET compilers, ranging from 3.x to 4.y failed to resolve which method should be called in the line where "a.To();" appears. Of course, I paraphrased the compiler but that's what the error message can be brought to (literally "Member 'Test.A.To()' cannot be accessed with an instance reference; qualify it with a type name instead").
I am posting this for not going into details of why the compiler alerts a programmer (already know the rules) but more to boost a discussion in what would be a near or final resolve to the problem of this certain kind (take into account inheritance) ahead of Microsoft, where a human can tell the extension/static method call matches easily, whereas the compiler even does not supply the exact programmer's mistake description or a hint.
Looking forward to hearing from 'stackoverflowers'.
First off, your "question" is explicitly a call for discussion. It will therefore be closed, because a call for discussion is not a question. StackOverflow is not a discussion site; there are any number of forums you can use to have a discussion. This is a good place to ask a question.
To clarify the situation: what is happening here is:
overload resolution is determining that the call a.To() has an applicable candidate in the form of the static method.
the fact that the method is static but the receiver is an instance does not make the candidate inapplicable. Rather, it makes it an error for overload resolution to choose it as the best applicable candidate.
Extension methods are not checked at all unless there was no applicable candidate. There was an applicable candidate, albeit an illegal one, so extension methods are not checked.
I agree that this is a bit weird, but the analysis is both correct and desirable. The language designers must decide what is more likely: that the caller intended to call the static method but mis-typed "a" for "A", or that the caller intended to call some completely different method that might extend some type compatible with "a". The safer assumption is the former, and therefore we give an error.
I understand that some people might find this analysis somewhat weird. It is somewhat weird, but it does make sense. If you think these rules are arcane and confusing, you're right; this is what happens when you bolt on new rules to an existing algorithm over a period of more than a decade.
Overload resolution in C# was originally designed to handle a very simple language; "params" was the most complicated part of overload resolution. it now must handle generics, type inference, extension methods, dynamic, and named and optional arguments. All those changes have severely stressed the overload resolution algorithm because every time a new feature is added we must ensure that the old features continue to work just the same.
Regarding your specific situation: if it hurts when you do that then do not do that. It is a very bad idea to make static, instance and extension methods that have the same name. They are unlikely to do the same thing, so do not make them have the same name.
the compiler even does not supply the exact programmer's mistake description or a hint.
Nonsense. The compiler tells you exactly what is wrong: overload resolution chose a static method, and you called it with an instance as the receiver. That's the error in the program, and that's the error that is reported.

Why can't you call methods with c# object initializer syntax? [closed]

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.
Why can't you call methods with c# object initializer syntax?
It seems to me that the property setters are called in the order that they are set in the syntax, so why not allow calls to methods as well? If there is a good reason, I'm missing it.
EDIT
I realize the semantic differences between methods and properties and the technical similarities. The purpose of this question is to probe for a good technical reason that they did not include the feature.
this. __curious_geek, I hear what you are saying, but I'm sure there are some features they haven't included because it wasn't technically feasable.
That's all I'm after. The overwhelming unwelcoming tone is heard loud and clear. Stackoverflow is no longer a "Question and Answer site" but instead a "Defend your question site".
Edit 2
Sample usage:
var mySuperLongVariableNameThatIDontWantToTypeOverAndOverAgainAndIsntThatTheWholePointAnyway = new Thingy
{
Name = "Marty McFly",
AddChildren("Biff","Big Bird","Alf"),
// 1000 other properties and method calls.....
}
The answer is in the name -- object initializer syntax is syntactic sugar to visually group the object's initial state. Methods change the object state, so once it's changed, it's no longer the initial state.
For example: say you buy a car. It is a red coupe with 55,000 miles on it. Then, you decide to drive it. It ends up with 55,500 miles on it. It has changed from its initial state:
var c = new Car() {Color = "Red",
Style = Styles.Coupe,
Mileage = 55000};
// c.Mileage is 55,000
c.Drive();
// c.Mileage is 55,500
In this somewhat contrived example, the method has a side effect and thus changes the object from its initial 55,000mi state to a 55,500mi state. This is not the same thing as buying a car with 55,500 miles on it.
If you really want to do this, you could cheat I suppose...
class C {
int BadProperty {
set {
SomeMethod(value);
}
}
void SomeMethod(int value) {
// here is where you do really, really bad things
}
}
Then call it like this!
var fail = new C { BadProperty = 1 };
what if the method fails ? The basic idea is, it's just a syntactic sugar. Eric Lippert is many time asked about "Why does C# not support feature X?". His answer is always
"because no one designed, specified,
implemented, tested, documented and
shipped that feature." - Eric Lippert.
This is all about orders, the Class have to be initialized with all the fields and all declared methods, before it can be guaranteed to run a method safely.
You can call methods with named parameters, if that is what you are asking about:
someMethod(param1: "Hello World", param2: "Some Other Value");

Underscores for private local variables? [closed]

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 13 years ago.
It seems to be the case with the BCL to use underscores for private local variables. I never use them, but get away like this:
int count = 0;
this.Count++;
public int Count
...
public ClassName ( int count )
{
this.Count = count;
}
What are your thoughts on this? Are they are problems with my approach?
This is basically something you'll have to decide upon yourself, just find or make a style guide and follow it.
Personally, I use _ as a prefix for private fields of the class.
The simple rule we use here is: Private implementation details of a class, including variable names, are completely up to the developer who makes it. Public/protected method names, properties, class names, and so on, are subject to best practice guidelines. Internal types can even be considered to be part of this, since they are not publically visible.
When someone else needs to use your library, it will never have to work with internal or private types, will not see if you used underscores, etc. In other words, this is really up to you....
Just keep in mind that if someone else has to maintain your code later that it should not be too obfuscated...
It's not required to use the underscore to denote private variables. It's all personal preference. I use them only so I know I'm using the local variable rather than having Intellisense accidentally use my public Property instead.
IMO, you should never name a private member variable the same as the name of a property, method, or anything else, for that matter. It should be clear which named item you are working with. This will make your code easier to understand and maintain, and will reduce programming errors by yourself, or other developers who need to maintain your code.
Also, if you ever wanted to port the code to VB, that particular naming would not work. Not sure why you would want to switch to VB, but it happens.
I use underscores. It helps me keep variable scope in check and reduce the possibility naming collisions.
Underscores make more sense for languages that are not case sensitive (like VB.Net). In languages like C#, it comes down purely to personal preference.
If you have an aversion to putting this. in the front of some ambiguous assignments, then underscores are for you. Without them, you can occasionally accidentally do things like this:
private int that;
public void AssignThat(int that)
{
that = that; // assigns to method scope variable, not instance scope
}
FXCop or R# should catch this for you, and I believe you get a compiler warning, but it is possible.
There is a practical reason to use a prefix, IntelliSense. ATM it is braindamaged in the way that it does not really distinguish between current instance variables and inherited properties/variables. So using '_' for private variables makes it easier to locate variable within intellisense list and function/variable list in VS code editor. So in a way it is wider-scope hungarian notation.

Categories