In a method that is so long that it scrolls off the screen. Just to make life easier as I program, if I want to refer to the variables of a class I can use the Me or this objects depending on which language I am using.
eg. Me.var1 = "Hello"
Is there an object (like Me) that would allow easy reference to the parameters of a function?
eg. params.par1 = "World"
There's no such feature in the language. Local variables and method arguments are treated specially by the .NET jitter, they are heavily optimized at runtime. Anything .NET would do, or you would do, to capture those variables would defeat such optimizations.
A very simple solution is to use Window + Split, it gives you two views on your code. Scroll the top one to the method header, write your code in the bottom one. You can adjust the splitter to give you more room in the bottom window.
Taking advantage of IntelliSense would be another way. Prefix the argument names with a little string, like "par". Then typing "par" in your code automatically gives you the list of argument names in the IntelliSense popup window.
These are however but band-aids for the real problem. As soon as you find yourself reaching like this, your first thought should be to split up the code in the function to make it smaller. There are some hard truths I discovered after thirty years of coding:
Long methods have more bugs. There's a metric for this, called "cyclomatic complexity". The higher the number, the more likely that the code is broken. Well supported by Visual Studio, this blog post is useful.
Code should never be indented more than 3 levels deep. By far the simplest way to discover that your cyclomatic complexity is getting out of hand without running a tool.
A method should never be larger than what fits on the screen. Any code that doesn't fit is a cognitive tax that produces compile errors and bugs. There's a corollary to this, programmers with big monitors create more bugs. The hard rule I use is one inspired by using DOS editors, a method should not have more than 25 lines of code.
Wide code produces a special kind of bug, the nasty kind that you can't see. Anything that's off the screen to the right is code that may have a bug that can take you a long time to discover. VB.NET is especially prone to this kind of bug since it uses end-of-line as a statement terminator. Much improved in VS2010 btw, the underscore is now optional in many cases. Always break your line to avoid this kind of bug.
Plan ahead and write maintainable code. Maintained code is never smaller than the original. If you already have trouble writing the original code then by definition you cannot maintain it. You have to start out small.
Always design first, code later. Long methods are a strong indicator of not thinking about code long enough before you start coding. In itself a strong bug inducer, in addition to writing correct code that just doesn't do the job.
The short answer is no. It seems like you are hoping to use this to distinguish between parameter scope and class scope for function parameters and fields with the same name, unfortunately you can't. Either use different naming schemes, or do the following:
public class MyClass {
private string myString;
private int myInt;
public MyClass(string myString) {
this.myString = myString;
}
public int DoStuff(int myInt) {
this.myInt += myInt;
return this.myInt;
}
}
to be really clear and avoid problems, you could change the names:
public class MyClass {
private string m_myString;
private int m_myInt;
public MyClass(string myString) {
m_myString = myString;
}
public int DoStuff(int myInt) {
m_myInt += myInt;
return m_myInt;
}
}
And you should really start by writing a test before the code, then you can check that you haven't accidentally mixed things up in your code.
Footnote
I include this as people coming to the title of this question may be looking for the following information.
While you say
Just for ease of programming - if I am a long way down in a function I would like to see what parameters there are without having to scroll up
In case you really want to look at your parameters from inside your code for other reasons then you need reflection. This is slow, and it's typical use would be to find a method, then reflect the parameters in that method. For a very comprehensive sample, see MSDN - ParameterInfo Class. The pertinent part of the code is:
foreach (MemberInfo mi in typeof(MyClass).GetMembers() )
{
// If the member is a method, display information about its parameters.
if (mi.MemberType==MemberTypes.Method)
{
foreach ( ParameterInfo pi in ((MethodInfo) mi).GetParameters() )
{
Console.WriteLine("Parameter: Type={0}, Name={1}", pi.ParameterType, pi.Name);
}
}
You should be able to use GetParameters() reflection method
MethodInfo barMI = bar.GetMethod("Foo");
ParameterInfo[] pars = barMI.GetParameters();
foreach (ParameterInfo p in pars)
{
Console.WriteLine(p.Name);
}
You can use this in run time. But for your aim, I would try to refactor the number of functions and their names. I try to keep code length under 80 symbols per line and the number of lines in a class under 100. Which is not always possible, but it's a good objective to decouple stuff and keep classes simple.
A simple way would be to encapsulate your parameters in an object so you can just refer to that, and intellitype (or whatever predictive feature) would show you what properties you have available without having to scroll back up. Like this
public class MyParamObject{
public string FirstParam {get;set;}
public string SecondParam {get;set;}
}
Then you could change your method from
public void MyReallyOvergrownMethod(string firstParam, string secondParam){...
to
public void MyReallyOvergrownMethod(MyParamObject params){...
then you can use the params parameter like this in the method
//Deep inside the method
if(params.FirstParam == "SomeValue"{//Do something
This is a numpty solution to a problem that would be best solved by refactoring your method. Look at loops, and conditionals and get them out into seperate private methods that are named after what they do. Loads of stuff on this, if you search for cleancoders.
In light of your comment "Just for ease of programming - if I am a long way down in a function I would like to see what parameters there are without having to scroll up": in Visual Studio, with code showing, just above the scrollbar there is a little bit you can grab and pull down to split the window. You can then have your function declaration visible in one pane and scroll as much as you like in the other. Or you can use Window menu->Split.
Related
I keep writing several utility, reusable functions in C#. Many functions return multiple values for which I use out or ref parameters. Many functions also have additional information, which may be of use to some callers (but not all callers).
Example, a function to read a CSV file may have additional information like no. of blank lines, no. of lines with duplicate values, and some other statistics.
The additional information could also include warnings, messages, etc.
Not every caller will be interested in this information, so I don't want to include all these as out, ref or Tuples, which will make it mandatory for the caller to declare all such expected variables.
I just wanted to figure out if there is a way to make the additional information available to the callers, so that the caller can choose or retrieve some of the optional additional information it is interested in.
For example, Func 1 can call Func B. After calling it, it gets all the standard return values. Additionally, can it call something like FuncB.GetAdditionalInfo(infoType) without Func B getting executed again?
It may be possible to design this using a class which serves as an intermediary to store all the optional values as well, and then return them to the caller on request; but I want it to be generic enough to be used across all my utility functions.
One possibility is Func B storing all these in some kind of global variables, which the caller can access if required. But if a utility class has several such resuable functions, I will need to have so many public variables, for the additional info of each function!
I am on .NET 4.5 as of now. Is there a design pattern for this? I am open to know if there is a good solution in F#.
Also, I want to avoid too many overloaded versions to achieve this!
Thanks.
I do not contend to present you with the ideal implementation, but here is one that makes sense to me. Design two different data structures: one would represent the options that your function accepts and the second one would be the one that your function returns. For example:
public class Helper
{
// General cover-it-all implementation that accepts an option object
// and analyzes based on the flags that are set in it
public static CSVStatistics AnalyzeCSV(string file, CSVAnalysisOptions options)
{
// define what we are analysing by reading it from the
// from the options object and do your magic here
}
// Specific implementation that counts only blank lines
public static long CountBlankLines(string file)
{
var analysisResult = AnalyseCSV(file, new CSVAnalysisOptions
{
IsCountingBlanks = true
});
//I'm not doing a null check here, because I'm settings the
//flag to True and therefore I expect there to be a value
return analysisResult.BlanksCount.Value;
}
}
// Analysis options structure
public struct CSVAnalysisOptions
{
public bool IsCountingBlanks { get; set; }
public bool IsCountingDuplicates { get; set; }
public bool IsCountingOther { get; set; }
}
// Analysis results structure
public struct CSVStatistics
{
public long TotalLineCount { get; set; }
public long? BlanksCount { get; set; }
public long? DuplicatesCount { get; set; }
}
In the above example CountBlankLines is a specific implementation that counts only blank lines and acts as "sugar" that simplifies the call, while AnalyzeCSV is the method that actually will do the counting. Also, notice how the CSStatistics structure has nullable longs. This will allow you to check if a value is null and therefore know that it was not actually analysed instead of outputting a zero (which is a possible value).
The CSVAnalysisOptions structure could also be replaced by bit flags, you can read about them here - https://www.dotnetperls.com/enum-flags.
I feel like what you're trying to do is to build a very chunky API that can do a whole lot of things in one shot. Generally speaking we don't like chunky API's because they can get complicated especially if there are side-effects or unusual quirks in the interactions between options in the API.
Honestly, the best way to do this is to create a chattier API wherein each call does one thing, does it right and does it well.
When you do this, the code ends up being easier to factor and unit test.
That's not to say that there isn't cause for a moderate amount of chunkiness, but it should be logical.
So for example, if you're cracking an image file to decode, say, a PNG or a JPG, you will need the image width, height, resolution, and color type up front. It would make total sense to grab all of those in one go. Would you need to dig out metadata information or the color profile right away? Probably not.
So it would make sense to have a single call that returns and aggregation of all the basic image information and then separate calls for getting the rest.
"But performance!" you say, "what about performance?!"
Simple. You measure it and see what falls out. A few years ago a wrote a PNG decoder and unlike libpng which reads chunks sequentially, I thought it would be easier to just build a database up front that maps where every chunk of the file is, then refer to that database to find any given chunk. Surprisingly enough, this impacted performance in no significant way and made the consuming code so much easier to read and maintain.
Let things get called multiple times and if there is a performance issue, figure out how to address it. Typically, you do this with a cache or session private to the objects that get the information.
What you're describing sounds like it would be neither easy to read nor to maintain, let alone to test.
Here's an F# pattern that might be suitable for your use case. It's pretty much the same pattern that the Argu library uses for command-line arguments: you declare a discriminated union that contains all the possible "flags" that your function might want to return (I put "flags" in quotation marks because some of them might be more than just booleans), and then your function can return a list of those values. If there are dozens, then a set might be worth it (because a list has to be searched linearly), but if you don't expect to return more than seven or eight such flags, then the extra complexity of a set isn't worth it and you might as well use a list.
Some F# code illustrating how you might use this pattern, with dummy functions where your business logic would go:
type Notifications
| InputWasEmpty
| OutputWasEmpty
| NumberOfBlankLinesInOutput of int
| NumberOfDuplicateLinesInOutput of int
| NumberOfIgnoredErrors of int
// Whatever else...
type ResultWithNotifications<'a> = 'a * Notifications list
// The syntax "TypeA * TypeB" is F# syntax for Tuple<TypeA,TypeB>
// And the 'a is F# syntax for a generic type
type outputRecord = // ... insert your own data type here
// Returns the filename of the output file, plus various notifications
// that the caller can take action on if they want to
let doSomeProcessing data : ResultWithNotifications<outputRecord list>
let mutable notifications = []
let outputFileName = getSafeOutputFilename()
if List.isEmpty data then
notifications <- InputWasEmpty :: notifications
let output = data |> List.choose (fun record ->
try
let result = record |> createOutputRecordFromInputRecord
Some result
except e
eprintfn "Got exception processing %A: %s" record (e.ToString())
None
)
if List.isEmpty output then
notifications <- OutputWasEmpty :: notifications
if List.length output < List.length data then
let skippedRecords = List.length data - List.length output
notifications <- (NumberOfIgnoredErrors skippedRecords) :: notifications
// And so on. Eventually...
output |> writeOutputToFilename outputFileName
outputFileName, notifications // Function result
Hopefully the F# code is comprehensible without explanation, but if there's anything that isn't clear in the above, let me know and I'll try to explain.
Can someone please break down what a delegate is into a simple, short and terse explanation that encompasses both the purpose and general benefits? I've tried to wrap my head around this and it's just not sinking in.
I have a function:
public long GiveMeTwoTimesTwo()
{
return 2 * 2;
}
This function sucks. What if I want 3 * 3?
public long GiveMeThreeTimesThree()
{
return 3 * 3;
}
Too much typing. I'm lazy!
public long SquareOf(int n)
{
return n * n;
}
My SquareOf function doesn't care what n is. It will operate properly for any n passed in. It doesn't know exactly what number n is, but it does know that n is an integer. You can't pass "Haha not an integer" into SquareOf.
Here's another function:
public void DoSomethingRad()
{
int x = 4;
long y = SquareOf(x);
Console.WriteLine(y);
}
Contrary to its name, DoSomethingRad doesn't actually do anything rad. However, it does write the SquareOf(4) which is 16. Can we change it to be less boring?
public void DoSomethingRad(int numberToSquare)
{
long y = SquareOf(numberToSquare);
Console.WriteLine(y);
}
DoSomethingRad is clearly still pretty fail. But at least now we can pass in a number to square, so it won't write 16 every time. (It'll write 1, or 4, or 9, or 16, or... zzzz still kinda boring).
It'd be nice if there was a way to change what happens to the number passed in. Maybe we don't want to square it; maybe we want to cube it, or subtract it from 69 (number chosen at random from my head).
On further inspection, it seems as though the only part of SquareOf that DoSomethingRad cares about is that we can give it an integer (numberToSquare) and that it gives us a long (because we put its return value in y and y is a long).
public long CubeOf(int n)
{
return n * n * n;
}
public void DoSomethingLeet(int numberToSquare)
{
long y = CubeOf(numberToSquare);
Console.WriteLine(y);
}
See how similar DoSomethingLeet is to DoSomethingRad? If only there was a way to pass in behavior (DoX()) instead of just data (int n)...
So now if we want to write a square of a number, we can DoSomethingRad and if we want to write the cube of a number, we can DoSomethingLeet. So if we want to write the number subtracted from 69, do we have to make another method, DoSomethingCool? No, because that takes too damn much typing (and more importantly, it hinders our ability to alter interesting behavior by changing only one aspect of our program).
So we arrive at:
public long Radlicious(int doSomethingToMe, Func<int, long> doSomething)
{
long y = doSomething(doSomethingToMe);
Console.WriteLine(y);
}
We can call this method by writing this:
Radlicious(77, SquareOf);
Func<int, long> is a special kind of delegate. It stores behavior that accepts integers and spits out longs. We're not sure what the method it points to is going to do with any given integer we pass; all we know is that, whatever happens, we are going to get a long back.
We don't have to give any parameters to SquareOf because Func<int, long> describes behavior, not data. Calling Radlicious(77, SquareOf) just gives Radlicious the general behavior of SquareOf ("I take a number and return its square"), not what SquareOf will do to any specific integer.
Now if you have understood what I am saying, then you have already one-upped me, for I myself don't really get this stuff.
* END ANSWER, BEGIN WANDERING IDIOCY *
I mean, it seems like ints could be perceived as just really boring behavior:
static int Nine()
{
return 9;
}
That said, the line between what is data and behavior appears to blur, with what is normally perceived as data is simply boring-ass behavior.
Of course, one could imagine super "interesting" behavior, that takes all sorts of abstract parameters, but requires a ton of information to be able to call it. What if it required us to provide the source code that it would compile and run for us?
Well, then our abstraction seems to have gotten us all the way back to square one. We have behavior so abstract it requires the entire source code of our program to determine what it's going to do. This is fully indeterminate behavior: the function can do anything, but it has to be provided with everything to determine what it does. On the other hand, fully determinate behavior, such as Nine(), doesn't need any additional information, but can't do anything other than return 9.
So what? I don't know.
In the simplest possible terms, it's essentially a pointer to a method.
You can have a variable that holds a delegate type (just like you would have an int variable that can hold an int type). You can execute the method that the delegate points to by simply calling your variable like a function.
This allows you to have variable functions just like you might have variable data. Your object can accept delegates from other objects and call them, without having to define all the possible functions itself.
This comes in very handy when you want an object to do things based on user specified criteria. For example, filtering a list based on a user-defined true/false expression. You can let the user specify the delegate function to use as a filter to evaluate each list item against.
A delegate is a pointer to a method. You can then use your delegate as a parameter of other methods.
here is a link to a simple tutorial.
The question I had was 'So, why would I want to do that?' You won't really 'get it' until you solve a programming problem with them.
It's interesting that no-one has mentioned one of key benefits of delegation - it's preferable to sub-classing when you realise that inheritance is not a magic bullet and usually creates more problems than it solves. It is the basis of many design patterns, most notably the strategy pattern.
A delegate instance is a reference to a method. The reason they are useful is that you can create a delegate that is tied to a particular method on a particular instance of a type. The delegate instance allows you to invoke that method on that particular instance even if the object on which you will invoke the method has left your lexical scope.
The most common use for delegate instances like this is to support the concept of callbacks at the language level.
It simply references a method. They come in great use with working with cross threading.
Here is an example right out of my code.
//Start our advertisiment thread
rotator = new Thread(initRotate);
rotator.Priority = ThreadPriority.Lowest;
rotator.Start();
#region Ad Rotation
private delegate void ad();
private void initRotate()
{
ad ad = new ad(adHelper);
while (true)
{
this.Invoke(ad);
Thread.Sleep(30000);
}
}
private void adHelper()
{
List<string> tmp = Lobby.AdRotator.RotateAd();
picBanner.ImageLocation = #tmp[0].ToString();
picBanner.Tag = tmp[1].ToString();
}
#endregion
If you didnt use a delegate you wouldn't be able to crossthread and call the Lobby.AdRotator function.
Like others have said, a delegate is a reference to a function. One of the more beneficial uses(IMO) is events. When you register an event you register a function for the event to invoke, and delegates are perfect for this task.
In the most basic terms, a delegate is just a variable that contains (a reference to) a function. Delegates are useful because they allow you to pass a function around as a variable without any concern for "where" the function actually came from.
It's important to note, of course, that the function isn't being copied when it's being bundled up in a variable; it's just being bound by reference. For example:
class Foo
{
public string Bar
{
get;
set;
}
public void Baz()
{
Console.WriteLine(Bar);
}
}
Foo foo = new Foo();
Action someDelegate = foo.Baz;
// Produces "Hello, world".
foo.Bar = "Hello, world";
someDelegate();
In most simplest terms, the responsibility to execute a method is delegated to another object. Say the president of some nation dies and the president of USA is supposed to be present for the funeral with condolences message. If the president of USA is not able to go, he will delegate this responsibility to someone either the vice-president or the secretary of the state.
Same goes in code. A delegate is a type, it is an object which is capable of executing the method.
eg.
Class Person
{
public string GetPersonName(Person person)
{
return person.FirstName + person.LastName;
}
//Calling the method without the use of delegate
public void PrintName()
{
Console.WriteLine(GetPersonName(this));
}
//using delegate
//Declare delegate which matches the methods signature
public delegate string personNameDelegate(Person person);
public void PrintNameUsingDelegate()
{
//instantiate
personNameDelegate = new personNameDelegate(GetPersonName);
//invoke
personNameDelegate(this);
}
}
The GetPersonName method is called using the delegate object personNameDelegate.
Alternatively we can have the PrintNameUsingDelegate method to take a delegate as a parameter.
public void PrintNameUsingDelegate(personNameDelegate pnd, Person person)
{
pnd(person);
}
The advantage is if someone want to print the name as lastname_firstname, s/he just has to wrap that method in personNameDelegate and pass to this function. No further code change is required.
Delegates are specifically important in
Events
Asynchronous calls
LINQ (as lambda expressions)
If you were going to delegate a task to someone, the delegate would be the person who receives the work.
In programming, it's a reference to the block of code which actually knows how to do something. Often this is a pointer to the function or method which will handle some item.
In the absolute most simplest terms I can come up with is this: A delegate will force the burdens of work into the hands of a class that pretty much knows what to do. Think of it as a kid that doesn't want to grow up to be like his big brother completely but still needs his guidance and orders. Instead of inheriting all the methods from his brother (ie subclassing), he just makes his brother do the work or The little brother does something that requires actions to be taken by the big brother. When you fall into the lines of Protocols, the big brother defines what is absolutely required, or he might give you flexibility to choose what you want to make him do in certain events (ie informal and formal protocols as outlined in Objective-C).
The absolute benefit of this concept is that you do not need to create a subclass. If you want something to fall in line, follow orders when an event happens, the delegate allows a developed class to hold it's hand and give orders if necessary.
My question is about whether what follows is an appropriate use of the dynamic keyword in C# 4.
I have some helper methods that provide a more useful representation of various objects than their standard ToString methods do, which I use for unit testing. Here is a simplified example:
public static string PrettyPrint<T>(IEnumerable<T> list)
{
return string.Join(", ", list);
}
// Needed because string is IEnumerable<char>, to prevent
// "Hello" -> "H, e, l, l, o"
public static string PrettyPrint(string s)
{
return s;
}
public static string PrettyPrint(object o)
{
return o.ToString();
}
I use them something like this:
public static void PrettyPrinting()
{
object[] things = { 1, "Hello", new int[] {1, 2, 3} };
foreach (dynamic item in things)
{
Console.WriteLine(PrettyPrint(item));
}
}
This produces the following output:
1
Hello
1, 2, 3
Notice that if I replace the dynamic keyword with object, I get the following (all the calls are routed through PrettyPrint(object)), which is what I am trying to avoid:
1
Hello
System.Int32[]
So my question is essentially is this a code smell or is it legitimate to cast an object to dynamic in this way?
So long as you don't abuse it, duck typing like this is part of the reason dynamic was added to the language.
As to your question, I'm not 100% sure as I don't know your teams style of coding. (I also see little comments ;) )
DuckTyping has it's uses - however a developer needs to know what they're doing before using it. Otherwise it's like running with scissors; it could be abused like other keywords in the C# system.
Personally, I'd rather see extension methods, but depending on the developer, his/her arguments and the documentation done I'd probably allow it.
The biggest reason for my hesitation (and this example is pretty tame to some of the ones I've seen online) is it stops you from finding issues at compile time. It requires more QA testing, a lot more boundary testing, and has a higher risk of failure.
Not an answer to the exact question, but I would say your code is not very OO, which is another smell.
Ideally you want to call item.PrettyPrint() and each item is supposed to return its representation, and override PrettyPrint.
Luckily, existing types can be extended with extension methods. They enable you to add the methods and that's what I would do instead.
If you still want to have the logic for the display of each type in one class, I would combine extension methods with the visitor pattern.
That said, I don't have C# environment so I can't test what I propose. Let me know if you try this, and if it works.
Ever since I found out about auto properties, I try to use them everywhere. Before there would always be a private member for every property I had that I would use inside the class. Now this is replaced by the auto property. I use the property inside my class in ways I normally would use a normal member field. The problem is that the property starts with a capitol, which makes it look a bit weird imho when using it in this manner. I didn't mind that properties start with a capitol before because they would always be behind a "dot". Now I have found myself prefixing all the properties I use internally with this., to sooth my feeling.
My dilemma is that before I was always a bit against prefixing all usage of internal members with this., unless "necessary" (like in a setter or constructor). So I am kind of looking for a second opinion on this. Is there a standard good way to do this? Should I just stop complaining (I have the tendency to be a "ant humper" (Dutch expression))?
Before:
class Foo
{
private Bar bar;
public Bar Bar { get { return bar; } }
public Foo(Bar bar)
{
this.bar = bar;
}
public void DoStuff()
{
if(bar != null)
{
bar.DoMethod();
}
}
}
After:
class Foo
{
public Bar Bar {get; private set;}
public Foo(Bar bar)
{
this.Bar = bar;
// or
Bar = bar;
}
public void DoStuff()
{
if(this.Bar != null)
{
this.Bar.DoMethod();
}
// or
if(Bar != null)
{
Bar.DoMethod();
}
}
}
Update
It seems that opinions vary, although more people are in favor of prefixing with this.. Before the auto properties I was always pretty much against prefixing with this. instead of in constructors and in setters (as I mentioned before). But now I just don't know anymore.
Additional note: The fact that it is also common to name the property the same as the class (public Bar Bar { get; private set; }) also makes me tend towards prefixing. Every time I type Bar.DoMethod(), I feel like it looks like a static method. Even though VS would color Bar if it was a static method and you cannot have a static and instance method with the same signature. When it is colored it is clear that it is a static method, but when it is not colored it is not 100% clear that it is not a static method. You could for example just be missing a using statement, but also just because I am not used to having to link the not being colored to whether it's a static call or not. Before I'd instantly see it by the capitalization of the first letter in case of a member or by the "dot" in case of a property (E.g. the "dot" after foo in (Foo)foo.Bar.DoMethod()).
(Difficult to choose an "Accepted answer" at the moment)
Yes, there is a "standard way to do this": the capital letter and the this-prefix are considered good coding practice. If you use some tool to test your code for coding guidelines like ReSharper or Microsoft's own StyleCop, it will warn you if not using the this-reference, or if you don't start your properties with a capital.
Your properties are publicly visible. Any public property, field or method should start with a capital.
Any property, field or method that you call inside your own class that is part of that class should be prefixed with the this-reference for ease-of-reading.
Update: of course, opinions vary. I like hitting this. and then, after the dot, seeing only the members, instead of seeing all keywords when just hitting ctrl-space without any prefix. This helps me. But, in the end (quote from here):
Whatever your opinion, the important
thing is that all people closely
collaborating on a project use the
same formatting standards,
irrespective of what those standards
are.
More references:
Microsoft on using a capital letter in almost any name and in properties specifically.
More guidelines here.
I strongly recommend to use 'this.' where possible. Framework Design Guidelines recommends this practice. It lets you know the scope from readability point of view and helps you avoid silly mistakes which compiler may report at compile time.
And I strongly recommend never using this as it only ever reduces clarity. If you actually find yourself in an instance where you need this to avoid collisions I would recommend renaming one of the fields/properties/variables.
The only place I find it acceptable is if it's part of a publicly exposed API where renaming would cause a breaking change.
In the first example, the bar parameter lexically shadows bar field from the instance. So you have to use this for disambiguation.
In the 2nd example you have no such ambiguity, and hence does not need a disambiguation (ie this). You can however still prefix it, if that is your cup of tea. :)
This is issue about LANGUAGE DESIGN.
Please do not answer to the question until you read entire post! Thank you.
With all helpers existing in C# (like lambdas, or automatic properties) it is very odd for me that I cannot pass property by a reference. Let's say I would like to do that:
foo(ref my_class.prop);
I get error so I write instead:
{
var tmp = my_class.prop;
foo(tmp);
my_class.prop = tmp;
}
And now it works. But please notice two things:
it is general template, I didn't put anywhere type, only "var", so it applies for all types and number of properties I have to pass
I have to do it over and over again, with no benefit -- it is mechanical work
The existing problem actually kills such useful functions as Swap. Swap is normally 3 lines long, but since it takes 2 references, calling it takes 5 lines. Of course it is nonsense and I simply write "swap" by hand each time I would like to call it. But this shows C# prevents reusable code, bad.
THE QUESTION
So -- what bad could happen if compiler automatically create temporary variables (as I do by hand), call the function, and assign the values back to properties? Is this any danger in it? I don't see it so I am curious what do you think why the design of this issue looks like it looks now.
Cheers,
EDIT As 280Z28 gave great examples for beating idea of automatically wrapping ref for properties I still think wrapping properties with temporary variables would be useful. Maybe something like this:
Swap(inout my_class.prop1,inout my_class.prop2);
Otherwise no real Swap for C# :-(
There are a lot of assumptions you can make about the meaning and behavior of a ref parameter. For example,
Case 1:
int x;
Interlocked.Increment(ref x);
If you could pass a property by ref to this method, the call would be the same but it would completely defeat the semantics of the method.
Case 2:
void WaitForCompletion(ref bool trigger)
{
while (!trigger)
Thread.Sleep(1000);
}
Summary: A by-ref parameter passes the address of a memory location to the function. An implementation creating a temporary variable in order to "pass a property by reference" would be semantically equivalent to passing by value, which is precisely the behavior that you're disallowing when you make the parameter a ref one.
Your proposal is called "copy in - copy out" reference semantics. Copy-in-copy-out semantics are subtly different from what we might call "ref to variable" semantics; different enough to be confusing and wrong in many situations. Others have already given you some examples; there are plenty more. For example:
void M() { F(ref this.p); }
void F(ref int x) { x = 123; B(); }
void B() { Console.WriteLine(this.p); }
If "this.p" is a property, with your proposal, this prints the old value of the property. If it is a field then it prints the new value.
Now imagine that you refactor a field to be a property. In the real language, that causes errors if you were passing a field by ref; the problem is brought to your attention. With your proposal, there is no error; instead, behaviour changes silently and subtly. That makes for bugs.
Consistency is important in C#, particularly in parts of the language that people find confusing, like reference semantics. I would want either references to always be copy-in-copy-out or never copy-in-copy-out. Doing it one way sometimes and another way other times seems like really bad design for C#, a language which values consistency over brevity.
Because a property is a method. It is a language construct responding to a pattern of encapsulating the setting and retrieval of a private field through a set of methods. It is functionally equivalent to this:
class Foo
{
private int _bar;
public int GetBar( ) { return _bar; }
public void SetBar( ) { _bar = value; }
}
With a ref argument, changes to the underlying variable will be observed by the method, this won't happen in your case. In other words, it is not exactly the same.
var t = obj.prop;
foo(ref t);
obj.prop = t;
Here, side effects of getter and setter are only visible once each, regardless of how many times the "by-ref" parameter got assigned to.
Imagine a dynamically computed property. Its value might change at any time. With this construct, foo is not kept up to date even though the code suggests this ("I'm passing the property to the method")
So -- what bad could happen if
compiler automatically create
temporary variables (as I do by hand),
call the function, and assign the
values back to properties? Is this any
danger in it?
The danger is that the compiler is doing something you don't know. Making the code confusing because properties are methods, not variables.
I'll provide just one simple example where it would cause confusion. Assume it was possible (as is in VB):
class Weird {
public int Prop { get; set; }
}
static void Test(ref int x) {
x = 42;
throw new Exception();
}
static void Main() {
int v = 10;
try {
Test(ref v);
} catch {}
Console.WriteLine(v); // prints 42
var c = new Weird();
c.Prop = 10;
try {
Test(ref c.Prop);
} catch {}
Console.WriteLine(c.Prop); // prints 10!!!
}
Nice. Isn't it?
Because, as Eric Lippert is fond of pointing out, every language feature must be understood, designed, specified, implemented, tested and documented. And it's obviously not a common scenario/pain point.