This question already has answers here:
Lambda variable names - to short name, or not to short name? [closed]
(11 answers)
Closed 9 years ago.
We normally follow coding / naming standard for all C# syntax. For Example, if we declare string inside the method, we use Scope-datatype-FieldName format. (lstrPersonName)
List<Person> icolPerson;
private LoadPersonName()
{
string lstrPersonaName;
}
i am kind of thinking how do we follow the naming standard in Lambda Expression. Especially when we defined the arguments for func delegate, we use shorted names like x. For Example
var lobjPerson = icolPerson.Where(x => x.person_id = 100)
if you look at the above line, X does not follow any standard. i also read that one purpose of lambda expression is to reduce the lenghthy code.
i am here to seek help to get the right approach for naming standard.
var lobjPerson = icolPerson.Where(x => x.person_id = 100)
OR
var lobjPerson = icolPerson.Where(lobjPerson => lobjPerson .person_id = 100)
My lambdas use one letter arguments, usually the first letter of what the parameter name would be:
buttons.Select(b => b.Text);
services.Select(s => s.Type);
But sometimes I add a few more letters to make things clearer, or to disambiguate between two parameters.
And when there isn't much meaning attached to the things I use xs and ys:
values.Aggregate((x, y) => x + y);
All said, the standard I use for lambdas is shortness first, expressiveness later, because the context tends to help understand things (in the first example it's obvious that the b stands for a button).
I've done a lot of programming in VBScript (ASP), and there the use of hungarian notation to keep track of the data type was crucial to keep sane. In a type safe language like C# I find no use at all to use hungarian notation that way.
Descriptive variable names does very much for the readability of the code, but it doesn't always have to describe every aspect of a variable. A name like persons indicates that it's a collection of person objects, whether it's a List<Person> or IEnumerable<Person> is usually not that important to understand what the code is doing, and the compiler tells you immediately if you are trying to do something completely wrong.
I frequently use single letter variable names, where the scope of the variable is very limited. For example the i index variable in a small loop, or in lambda expressions.
I usually just use the first letter of the type I am querying so in your case since it is of type Person I would do:
var lobjPerson = icolPerson.Where(p => p.person_id = 100);
Another example if it was say type Car I would do:
var lobjCar = icolCar.Where(c => c.car_id = 100);
I do this for quickness, however, I don't think there is anything wrong using full names in the query i.e. car => car.car_id
I think the naming standard you use (hungarian notation) was the need of the hour when high profile tools like Visual Studio were not present. Today you have technologies like Intellisense which tell you most of the things you are doing wrong with a variable as you type, like assigning an int to a string. So, as of today, it is not an exclusive part of good coding conventions or standards as it used to be. Most people follow pascal casing or camel casing these days. If anybody uses it, I think it is more because of a personal preference.
Having said that, according to the way you code and name your variables, you should follow the second approach instead. Again, this boils down to you personal preference.
PS: This comment does not mean that I am looking down on your usage of hungarian notation. :)
There is no the right approach at all. Naming standard like any other coding standards (like spaces and new lines after/before expressions) is a convention inside group. So just write your code as you like and as you should do it at your company. But do it consistently!
i prefer use underscore prefix in names of private fields. but your style(visibility + type + name) looks for me like an old WInAPI code citation(Hungarian notation) =).
As long as your lambda expression is only a single statement, I'd keep the variable name as short as possible. The overall purpose of naming is to make the code readable, and in these cases, the method name and general context should be enough.
You don't have to use x all the time. For a Person object, I'd tend to use p instead.
If you need to write a more complex expression involving braces and semicolons, I'd say that all the normal naming rules apply.
If your collection is called something-persons, then it's obvious that when you're doing persons.Where(p => p.Whatever) that p is a person. If your lambdas are so complicated it's not immediately obvious whatever the parameters you're using are, then you shouldn't use lambdas at all, or make them drastically simpler.
As for your other conventions, what is the point of using Hungarian for calling out that personName is a string? It's obvious that a name would be a string. And why do you need a prefix to remind you that a variable is a local? Its declaration is necessarily in the same method, so that can't be so long ago that you've already forgotten it. If you have, then your methods are too long or complex.
Just have your identifiers appropriately describe what the meaning of the variable is, then the rest will be obvious.
LINQ is not just for the developers who used to write queries for databases but also for the Functional Programmers.
So do not worry if you are not very comfortable with SQL kind of queries, we have a very nice option called “Lambda Expression”.
Here I am going to demonstrate the scenario for both the options with a small example. This example has an array of integers and I am only retrieving the even numbers using the power of LINQ.
Here we go
using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;
namespace LINQConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] arrInt = {1,2,3,4,5,6,7,8,9,10};
#region Place to change
//Language Integrated Query
var aa = from s in arrInt
where s % 2 == 0
select s;
#endregion
foreach (var item in aa)
{
Console.WriteLine("{0}", item);
}
Console.ReadKey();
}
}
}
If you do not want to use the different approach of query for Language then you are free to use Lambda Expression.
So just replace the #region area with the following code block results will be identical.
#region Place to change
//Lambda Expression
var aa = arrInt.Where(s => s % 2 == 0);
#endregion
Related
I'm using an in-house file parsing library, which I'm using to parse a gnarly reporting file generated by a legacy system. The library iterates allows you to define Linq queries which are applied successively to return an enumerable set of structures in the file.
A typical example would be something like the below.
var OrderReportParser =
from blanks in Rep(BlankLine) // One or more blank lines
from header1 in TextLine // A header text line with no useful information
from hyphenLine in WhiteSpace.And(Rep(Char('-'))).And(BlankLine)
// A line containing only hyphens
/* ... Snip ... lots of other from clauses */
from orderId in WhiteSpace.And(AlphaNumeric) // The id of this record
from price in WhiteSpace.And(Decimal) // Order price
from quantity in WhiteSpace.And(Integer) // Order quantity
select new OrderLine (orderId, price, quantity)
Because much of my file is simply text, many of the intermediate results generated by a statement such as the above are not required in the output (such as the variables blanks, header1, hyphenLine in the example above).
Is there any such mechanism in C# creating variables for the intermediate results, or do I always to create variable for each?
I am thinking of examples such as F#'s _ variable, which can be used in this fashion. See F#'s underscore: why not just create a variable name? for an example in the context of Tuples.
If you're asking if it's possible to do something like this:
var OrderReportParser =
from Rep(BlankLine)
from TextLine
from WhiteSpace.And(Rep(Char('-'))).And(BlankLine)
...
...then the answer is no. The designers of Linq probably never imagined that people would want to select something and then immediately throw it away without looking at it, since with most other Linq providers this parser syntax would create a huge Cartesian product. (Or if they did think about it they didn't consider it to be a useful enough feature.)
Why do you want to get rid of the variable names anyway? Personally I think including the variable names is likely to make the intent of the code clearer. If the unused variables bother you so much I guess you can name them something like _1, _2 or dummy1, dummy2, etc. That should make it pretty clear that they aren't used for anything. But they have to be there.
Edit: I had an inkling that the "anonymous variable" _ from languages like F# might've been what you were driving at. The answer is still no, I'm afraid. You could name the first variable _, but you wouldn't be allowed to redefine it on the second line, so that would be it. Also, the _ variable wouldn't have the special semantics that it has in F#, so you would essentially be pretending that C# has a feature that it doesn't. Keep in mind that C# is fundamentally an imperative language. It has a lot of functional-style features, such as Linq, but it's still very much a language in the C/Java tradition, where these sorts of pattern matching features have not yet made much inroads. I like those features too, but you have to think a little differently when writing C#.
I often find myself using lambdas as some sort of "local functions" to make my life easier with repetetive operations like those:
Func<string, string> GetText = (resource) => this.resourceManager.GetString(resource);
Func<float, object, string> FormatF1 = (f, o) => String.Format("{0:F1} {1}", f, o);
Func<float, object, string> FormatF2 = (f, o) => String.Format("{0:F2} {1}", f, o);
Instead of writing the String.Format-thing over and over, I can happily blow away with FormatF2 e.g. and save myself time and when I need to change something about the formatting, only one place to make edits.
Especially when I need the functionality in the given function exclusively, I'm very reluctant to turn them into a real function. While the lambdas above were relatively small... sometimes I have larger ones like (the following is supposed to add data to a table for print output):
Action<string, string, string> AddSurfaceData = (resource, col, unit) => {
renderTable.Cells[tableRowIndex, 0].Text = "\t" + this.GetText(resource);
renderTable.Cells[tableRowIndex, 1].Text = FormatF2(paraHydReader.GetFloat(paraHydReader.GetOrdinal(col)), "");
renderTable.Cells[tableRowIndex, 1].Style.TextAlignHorz = C1.C1Preview.AlignHorzEnum.Right;
renderTable.Cells[tableRowIndex, 2].Text = " " + this.GetText(unit);
renderTable.Cells[tableRowIndex, 2].Style.TextAlignHorz = C1.C1Preview.AlignHorzEnum.Left;
++tableRowIndex;
};
Again, I need this often and all the benefits of above apply, too. However, as you can see, this one is quite long for a lambda expression.. the question is: When do you draw the line? Is my last lambda too much? What other ways (other than using real functions or trying to stuff the data in containers and loop over them) exist to avoid writing the same code over and over again?
Thanks in advance
Christian
It is something you use potentially many times within a method, and only that inside that method. I like this idea. Do it if it doesn't make your code hard to read. I would say that you should reconsider if you find it difficult to see what is the content of the lambda function vs. what is the real content of the method. In that case it might be cleaner to pull it out in a separate private method.
At the end, this is really a matter of taste...
I agree with awe: for small scale reuse inside a method (or even a class) this is perfect. Like the string.Format examples. I use this quite often. It's basically the same thing as using a local variable for an intermediate value that you use more than once, but then for code.
Your second example seems to be pushing it a bit. Somehow this gives me the feeling a private method AddSurfaceData (possibly static, depending on its use?) would be a better fit. That is of course outside of the context that you have, so use your own good judgement.
A Lambda method is an anonymous method.
This means that you should not give it a name.
If you are doing that, (in your case, you are assigning a name with your reference), it's just another way to declare a function.
C# has already got a way to declare functions, and it's not the lambda way, which was added
uniquely to pass functions via parameters and returns them as return values.
Think, as an example, in javascript:
function f(var1,var2,...,varX)
{
some code
}
or
var f = function() {
some code
}
Different syntax (almost) same thing.
For more information on why it's not the same thing: Javascript: var functionName = function() {} vs function functionName() {}
Another example: in Haskell You can define two functions:
function1 :: Int -> Int
function1 x = x + 2
or
function2 :: Int -> Int
function2 = \x -> x + 2
Same thing (this time I think it's the very same), different syntax. I prefer the first one, it's more clear.
C# 3.5, as Javascript, has got a lot of functional influences. Some of them should it be used wisely, IMHO.
Someone said local lambda functions with assignment in a reference is a good substitute for a method defined within another method, similar to a "let", or a "where" clause in Haskell.
I say "similar" because the twos have very different semantics, for instance, in Haskell I can use function name which is not declared yet and define it later with "where", while in C#, with function/reference assignment I can't do this.
By the way I think it's a good idea, I'm not banning this use of lambda function, I just want to make people think about it.
Every language has got his abstraction mechanism, use it wisely.
I like the idea. I don't see a better way to maintain code locality without violating the DRY principle. And I think it's only harder to read if you're not accustomed to lambdas.
+1 on nikie re DRY being good in general.
I wouldnt use PascalCase naming for them though.
Be careful though - in most cases the stuff you have in there is just an Extract Method in a dress or a potential helper or extension function. e.g., GetText is a Method and FormatF* is probably a helper method...
I have no problem with the long example. I see that you are repackaging compound data very elegantly.
It's the short ones that will drive your colleagues to investigate the advantages of voluntary institutionalization. Please declare some kind of constant to hold your format string and use "that String.Format-thing over and over". As a C# programmer, I know what that does without looking elsewhere for home-spun functions. That way, when I need to know what the formatted string will look like, I can just examine the constant.
I agree with volothamp in general, but in addition ...
Think of the other people that have to maintain your code. I think this is easier to understand than your first example and still offers the maintenance benefits you mention:
String.Format(this.resourceManager.GetString("BasicFormat"), f, o);
String.Format(this.resourceManager.GetString("AdvancedFormat"), f, o);
And your second example appears to be just a different way to declare a function. I don't see any useful benefit over declaring a helper method. And declaring a helper method will be more understandable to the majority of coders.
I personally think its not in good taste to use lambda functions when there is no need for it. I personally wont use a lambda function to replace a simple few lines of procedural code. Lambda functions offer many enhancements, but make the code slightly more complicated to read.
I wouldnt use it to replace string.format.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I notice, in C# i use very short variable names EVERYWHERE. My code is polluted with
foreach(var (v|f|i) in SOMETHING)
for(int (i|n|z)=0
var (ret|r) = blah();
...
return ret;
var sw = new StringWriter();
using(var r = cmd.ExecuteNonQuery()) {
while(r.Read()) {
r.GetSomething(3)
I dont know if this is bad or ok. I can certainly read it. I havent looked at code 5months ago or older so i cant say if i understand old code. All my functions are short and do one thing so by reading the function you can get a good idea what the variable is, especially since theres <=5vars in a function.
People use to yell at me about not using good variable names. Am i not using good variable names or is this ok?
Write code for humans to read. A good rule of thumb is the bigger the scope in which a variable is used, the more descriptive its name should be. Function parameters especially should have very descriptive names, with the exception of functions where it is obvious what the parameter does, as in
double sqrt(double n)
However, if it's something commonly given a short name and used in a small scope, then use a short name. Examples:
//these are okay
var sb = new StringBuilder();
var sw = new StringWriter();
var cmd = new SqlCommand();
for(var i = 0; i< count; i++) {}
Unless your code is minified, you shouldn't see vars like this all over the place. Your code should be effortlessly intelligible.
I recall hearing that we ought all code as if the next person to manage our project is a psychopathic killer who knows where you live.
Using short variable names for local variables is okay as long as the scope is limited.
Personally, I find that for simple usage short concise variable names tend to be easier to read than longer ones.
using (StreamReader sr = new StreamReader(inputStream))
{
sr.ReadByte();
}
As opposed to:
using (StreamReader streamReader = new StreamReader(inputStream))
{
streamReader.ReadByte();
}
It's really all about readability. Every situation is different, and developer teams are different. Follow the coding standard for the project, if that exists. If not, follow the style of existing codebase, if that exists.
I agree with some of the answers here say that variables names should have good names. But I believe that presupposes that an object has semantic value. Sometimes, it doesn't. In some cases, you just need an instance of a specific object to perform some small task, after which it becomes irrelevant. In cases like this, I believe that abbreviated identifiers are acceptable.
Note: Just because the usage of a variable is limited in its scope does not necessarily mean that an meaningless name is okay. If there is a good name that represents what the object does, then it should be used. If you can come up with a variable name that answers 'Why?', then that name is far preferable.
Also, using 'i' and 'j' for for indexes is well understood by developers. By convention, loop counter variables have been named this way since the days of FORTRAN.
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
PerformOperation(i,j);
}
}
Some years ago I discovered what happens if I made my functions short:
I could understand them. My brain is small, and long functions don't fit.
Classes get complicated (lots of functions). But Extract Class produced small, cohesive, single-purpose classes. Again, small brain, so small classes required.
The number of variables in a function (or class) is small. Remembering which is which from declaration time to use time is easy, because the distance is short.
The number of scopes in my functions is small, so I don't have to figure out which variables go where.
With all of that in place, how I name my variables doesn't matter much. The names don't have to make up for code that is otherwise hard to understand.
Since the number of variables in a scope is small, and the purpose obvious, I rarely need to put any effort in to choosing a descriptive name. Since I don't want to strain my small brain any more than I have to, I never abbreviate. My default name for a variable is the name of the type. E.g. class Foo goes in variable foo. In my code, if it's ever something different, you know something special is happening, and you should pay attention.
In the old days, my no-abbreviation habit would have produce unwieldy code, but since my methods and classes are small, the code doesn't suffer.
It's not just a matter of good variable names (which is a good idea) but rather if someone else could make sense of what you've written relying on the comments as well as the variable names.
Sure, for things like counters or simple actions short and concise names make sense. For more complex algorithms or something that is a little harder to read, you'll want to elaborate to the extent that the code is clear.
Every shop and every developer is different. At the end of the day, try to write your code with consideration for the next guy that might have to maintain it.
Using one letter variable names as indexes in loops or in short well defined blocks is normally considered ok. However, there is nothing wrong with using descriptive camel case names that convey meaning to others reading your code, for things like function arguments and local variables.
With limited exceptions, no - this is not OK. There's just no excuse any longer for single letter or overly abbreviated variable names. Even if you're a hunt-and-peck typist, intellisense means you almost never have to spell anything out. If you continue to name variables this way you are punishing both yourself any anyone unfortunate enough to be tasked with maintaining your code.
Would I consider it a bad coding style? Well, yes.
If you were working with me on same code I'd repeatedly remind you to name your variables better. In short, good code should be readable by other developers without much trouble and good variable names help a lot. Maybe you don't have problems reading your code even after a while, but the question is whether someone who has never worked on that good would be equally fine with it.
There are a few exceptions where I think that short variable names are okay:
Indexes (mostly in for loops) such as:
for (int i = 0; i < 10; i++)
{
}
Variables used in a very limited scope, such as Linq queries, lambda expressions or some of the examples already mentioned like Streamwriters and -readers and such are another example where I think that short variable names are fine.
Furthermore it's always a question of how readable your code eventually is. The reason why I would be constantly nagging at people who use short variable names is that for me that it is an indicator that they generally don't care about how readable their code is (especially for others).
I have no idea how you can keep track of things when you have variable names like that.
Generally, its much better to have longer names that actually describe the variables. The thing to strive for is for anyone to be able to read the code and understand whats going on, to be able to understand what they are for etc =)
It seems like the average length of my variable names increases by one every year I spend writing (and more importantly reading) code.
It should be immediately clear what any variable is for just by looking at a few lines of code. This can either be due to a nice variable name or the context.
About the only time I use short variable names is either if a short name is entirely descriptive (ie, x & y in a situation dealing with coordinates) or it's a utility function that operates on a data type (ie, capitalize the first letter of this string. It's a string, what else can you say about it? I named it S.)
I might not know what 'r' is later on in the code. Also, variable names are one thing, but you should be commenting code for the verbose explanation.
NB: This should probably be a community wiki as there's no definite answer.
This is bad. This is unmaintainable.
Short variables have their place. There is really no reason to write
for(int iterator; iterator
The rule of thumb is: One letter per screen of reach. With standarized 24 lines screen.
The exception is picking one-two extremely frequently used globals or semi-globals like pointer to the data storage or THE input data pointer, and make them 1-3 letters long. But anything else - use reason. Short loops - one letter. Locals of a function - 3-5 letters. Class variables - full word. Library class/function names - two words.
I don't see any reason to use short variable names that say nothing. We live in 21st century, we've got IDEs with IntelliSense (or other autocompletion)! Just press Ctrl+Space and it will advice you normal name for your variable depending on variable type, e.g.
StringBuilder <Ctrl+Space> stringBuilder;
List<Person> <Ctrl+Space> persons;
It is even easier than to type something like sb or another short name. No reason to use short names anymore.
P.S.: The only exception for me are counters like i, j, k in for loop.
I tend to prefer short "cryptic" variables (Symbols, in Mathematica) combined with descriptive comments.
Mathematica already has VeryLongFunctionNames for built in commands, and adding my own often spreads out code more than I care for.
I find it easier to read a shorter block of code where I can see everything at once, alongside a series of symbol descriptions.
This question already has answers here:
With block equivalent in C#?
(19 answers)
Closed 9 years ago.
I was looking at the online help for the Infragistics control library today and saw some VB code that used the With keyword to set multiple properties on a tab control. It's been nearly 10 years since I've done any VB programming, and I had all but forgotten that this keyword even existed. Since I'm still relatively new to C#, I quickly went to see if it had a similar construct. Sadly, I haven't been able to find anything.
Does C# have a keyword or similar construct to mimic the functionality provided by the With keyword in VB? If not, is there a technical reason why C# does not have this?
EDIT: I searched for an existing entry on this before asking my question, but didn't find the one Ray referred to (here). To refine the question, then, is there a technical reason why C# does not have this? And Gulzar nailed it - no, there are not a technical reason why C# does not have a With keyword. It was a design decision by the language designers.
This is what C# program manager has to say:
Why doesn't C# have a 'with' statement?
Small or non-existent readability benefits. We thought the readability benefits were small or non-existent. I won't go as far as to say that the with statement makes code less readable, but some people probably would.
Increased language complexity. Adding a with statement would make the language more complex. For example, VB had to add new language syntax to address the potential ambiguity between a local variable (Text) and a property on the "with" target (.Text). Other ways of solving this problem also introduce language complexity. Another approach is to push a scope and make the property hide the local variable, but then there's no way to refer to the local without adding some escape syntax.
C++ heritage. C++ has never had a with statement, and the lack of such a statement is not generally thought to be a problem by C++ developers. Also, we didn't feel that other changes -- changes in the kind of code people are writing, changes in the platform, other changes in the language, etc. -- made with statements more necessary.
In C# 3.0, you can use object initializers to achieve a similar effect when creating objects.
var control = new MyControl
{
Title = "title",
SomeEvent += handler,
SomeProperty = foo,
Another = bar
};
Rather than:
var control = new MyControl();
control.Title = "title";
control.SomeEvent += handler;
control.SomeProperty = foo;
control.Another = bar;
Note that, although this syntax was introduced in C# 3.0, you can still use it with the 2.0 framework, it's just syntactic sugar introduced by the compiler.
It is not idiomatic c#, but if you really want a with equivalent, you could do this:
Person MyPersonWithALongName = new Person();
MyUtils.With(MyPersonWithALongName, p => {
p.Name = "George";
p.Address = "123 Main St";
...
});
class MyUtils {
public static void With<T>(T x, Action<T> do) {
do(x);
}
}
Update:
It occurred to me that you could trivially make this more concise by turning it into an extension method, perhaps renaming it "Alias" or "As" for reabability:
MyPersonWithALongName.Alias(p => {
p.Name = "George";
p.Address = "123 Main St";
...
});
No, the "with" keyword was intentionally left out of the language.
If you have a lengthy name of reference, you can easily make a shorter reference to it using a variable, and even give it a limited scope:
{
SomeClass r = Some.Lengthy.Path.To.Get.To.A.Referece;
r.Some = 42;
r.Properites = "none";
r.To = 1;
r.Set = null;
}
For these solutions:
// ....
// (class Common)
public static void With<T>(T property, Action<T> action) {
action(property);
}
// ...
// usage somewhere ...
Person person = GetPerson();
Common.With(person, p => { p.Name = "test", p.Age = "123" });
It just seems we are aliasing the variable with "p". As solutions go, I found it easy enough to keep the variable name short, this sort of solution with a "With" generic doesn't buy any elegance.
Ideally, we'd all like to see some reworking of the syntax so the usage is similar to how initialization of multiple properties works today:
Person person = new Person() { Name = "test", Age = "123" };
No, it was a conscious decision made by the C# dev team. People have mixed feelings about the 'with' keyword because it can degrade code readability if abused (nesting with's).
I don't imagine that there's a technical reason it doesn't exist. What I would say though, is that the reason that it doesn't exist is that it's a programming construct that exists solely for the purpose of cutting down on typing. With things like intellisense, and copy and paste, the world doesn't really have much demand for features like this anymore. I use VB.Net, and can't recall if it's even still supported. Never really felt the need to use it.
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)
Class ReportClass
{
public string ReportName {get; set;}
}
Then it was used as follows in code:
displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())
That is about the simplest form example I can give you.
Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?
EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
I tend to avoid in-place assignment - or indeed any side effects like this - except for one common idiom:
string line;
while ((line = reader.ReadLine()) != null)
{
// Do something with line
}
(And variants for reading streams etc.)
I'm also okay with using object initializers in parameter calls, e.g.
Foo(new Bar { X=1, Y=2 });
but assigning to a property in an existing object... well, it's all subjective but it's not my cup of tea.
I think this is harder to maintain/harder to debug/harder to understand code. I would do the assignment on a line prior to calling that method.
ReportClass.ReportName = cmbReportName.SelectedValue.ToString();
displayReport(ReportClass.ReportName);
I've never really been a fan of compound statements.
It is totally fine. Both of them.
Automatic properties (the {get; set;} thing): Introduced in C#. Very useful feature.
Assignment in the parameters: Rarely used in C# but totally legal. Basically it assigns the value of the expression to the right of the assignment operator (=) to the property to the porperty on the left, and then passes this value on to the method.
This is more common in C, but I see no reason why shouldn't it be allowed in C# as well. Sometimes it might help readability, sometimes it makes it much worse. Use common sense to decide which applies when.
Did you mean the automatic properties or the in-place assignment?
Depends on your team IMO. If your team were comprised of C-style devs. Then I think it is ok.
But if this code is gonna be maintained further by, say, VB developers, then you'd need
to make this more readable.
Examples? The assignment operator (=) in C langauges also return the values it's assigned.
var a = 0;
var b = 0;
// This makes a *and* b equals to 1
a = b = 1;
// This line prints 3 and a is now equals to 3
Console.WriteLine(a = 3);
// This line prints 7 and a and b is now equals to 7
Console.WriteLine(a = b = 7);
I think it is rather natural for this kind of assignment to happen. Because the C-languages seem to encourage shorthand notations IMO.
If you need more readability and less trouble, then I'd say a newline is a nice add.
displayReport(
ReportClass.ReportName = cmbReportName.SelectedValue.ToString());
Make your intentions clearer when each compounded statements are on different lines. (but still a compound statement)
Or, extract the right part out into its own variable first, e.g.
var reportName = cmbReportName.SelectedValue.ToString();
displayReport(ReportClass.ReportName = reportName);
I use it all the time, and I havn't seen anyone confused upon reading it yet.
Personally I find the assignment as parameter not very readable. The overall flow of execution is just skewed by having an operation actually happening inside the parameter list.
I like to think that my code should express intent, not save whitespace. And my intent in this example would be exactly what EvilSyn suggests, first assign value, then pass it to the method.
The Microsoft Framework Design Guidelines discourage the placement of multiple statements on one line, except where there is direct language support, such as in the for statement. Since there is explicit language support for multiple assignment,
int a, b, c;
a = b = c = 0;
is permitted. On the other hand, code of the form used in your example is discouraged.
How about this one, people?
while ((packetPos = Packet.FindStart(buffer, nextUnconsideredPos)) > -1)
To avoid the inline assignment, you would have to factor redundantly, like this:
packetPosition = Packet.FindStart(buffer, nextUnconsideredPosition);
while (packetPosition > -1)
{
...
packetPosition = Packet.FindStart(buffer, nextUnconsideredPosition);
}
As far as naming the property goes you have a ReportClass, I would change that to Report and the property on it changed from ReportName to just Name. Saves you on typing (although yes intellisense is available). Looks better when coding up as Report.Name.
I know its a little off topic but hey ho
Seems fine to me. It is probably compiled with C# 3.0 and that allows C# automatic properties.
Is that really valid code? Seems like a static class to me.
I would have guessed you used it like this:
displayReport(new ReportClass { ReportName = cmbReportName.SelectedValue.ToString() } )