In C# language when you refer to an array element you can write:
myclass.my_array['element_name'] = new Point(1,1);
I think about refering to a element with name element_name by using dot in place of backets:
myclass.my_array.element_name = new Point(1,1);
Do you know any language where exists similar syntax to the example above?
What do you think about this example of refering to a array element? Is this good or is it as bad as my writing in english skills?
Kind regards
JavaScript does exactly what you describe. In JavaScript, every object is just a map of property names to values. The bracket operator just returns a property by name (or by value in the case of an integer index). You can refer to named properties by just using a dot, though you can't do that with integer indicies. This page describes the bracket operator and dot notation in detail.
You could almost certainly do this in any dynamic language, by handling property/variable access as an indexer if the specified property/variable didn't actually exist. I suspect that many dynamic languages already provide this functionality in some areas.
It's possible that in C# 4 you'll be able to make your objects behave like this if you really want to.
However, I would agree with the implicit judgement in Mohit's question - I see no reason to consider this more generally readable than using the more common indexer syntax, and it will confuse people who are used to indexers looking like indexers.
One area where I would quite possibly do something like this would be for an XML API, where a property would indicate "take the first element of the given name":
XElement author = doc.Root.Posts.Author;
That's quite neat - for the specific cases where it's what you want. Just don't try to apply it too generally...
REXX has the concept of stems, where you can say x.1, x.2 x.bob and these refer to array elements x[1], x[2] and x['bob'] respectively.
In addition LotusScript (in Notes) allows you to process the Notes databases in this fashion, where db.get("fieldname") is the same as db.fieldname.
I've used the REXX one a bit (as there's no choice) but when I've coded for Notes databases, I've preferred the get/put way of doing things.
Lua tables have a.x as syntactic sugar for a["x"]. Lua tables are associative arrays that could be used to represent arrays, hashes, and records of other languages. The sugar helps making code more readable by illustrating the intention (Record? Array? Hashtable?), though it makes no difference to the language.
What would be the advantage of such a syntax for you?
If you have fix names why not create a class with properties?
Maybe you are looking for a class or struct if you you want to use the element name as a field/property.
Related
CA1023: Indexers should not be multidimensional
Indexers, that is, indexed properties, should use a single index.
Multi-dimensional indexers can significantly reduce the usability of
the library. If the design requires multiple indexes, reconsider
whether the type represents a logical data store. If not, use a
method.
To fix a violation of this rule, change the design to use a lone integer or string index, or use a method instead of the indexer.
This seems very strange to me, why does this significantly affect anything? other than making a multidimensional index much less intuitive?
Change the design to use a string? And do what with it? Parse the numbers out at the other end and lose strong typing?
Can someone give me some reasons why there is something wrong with Multidimensional indexers?
If the design requires multiple indexes, reconsider whether the type
represents a logical data store. If not, use a method.
The problem is that indexers cannot be specifically named (except, as #volpav comments, for interfacing with languages that don't natively support them - by default, they are called Item) whereas methods must be. This means that a client may have problems guessing at the meaning of an indexer if it is not immediately obvious ("represents a logical data store"). This can be particularly vexing if an indexer has multiple parameters and/or multiple overloads of the indexer exist. Of course, naming indexer parameters can help matters (although the indexer itself cannot be specifically named in C#), but consider that methods can hint at the meanings of the return value and the parameters in the name of the method itself (consider GetCustomersByCountryAndAge vs this[string, int] ). This greatly helps readability when browsing source code.
Well-written XML documentation for your indexer would also help.
To fix a violation of this rule, change the design to use a lone
integer or string index
This somewhat poorly phrased sentence appears to be advice combined with the observation that int and string are the most common parameter types for indexers. It should likely just read "change the design to use a lone index."
I find myself sometimes writing code that looks like this with Java Generics:
/**Class description
*#param <K> Key to '.....'
public class Mappy<K>{
///class methods, fields, etc....
}
Sometimes using single-character names has caused slowdowns when months later I return to code and have to keep scrolling up to remember what "T" & "E" are. But last I checked, Oracle's official guideline was single-character names and I've never seen a java programmer not do it.
In C#, using TDescription is part of the official style guidelines, similar to how Google & others use Ixxxx for interfaces. But I still see one-letter names in production code & APIs for C#. I've heard it is similar in C++. In Haskell & Ocaml, especially Haskell, you use 'a' or 'b' as a generic parameter in your function signature (forget if the compiler/interpreter forces this or if they can be multi-letter).
I'm just asking this 'question' to see how y'all do it: do you stick with single-letter names in your generics/templates/etc..., do you have a convention like Txxx, do you give them full-fledged names (and does that confuse co-workers), or do you do something else?
This is very similar to Breaking java generics naming convention? (which I found via google). Instead of poking that question, I just wanted to gather some modern opinions (see if there's been a style coup in the pass two and a half years).
Edit 1:
Probably the reason this question came up is that a few days ago I made a pledge to dump the variable 'i'. Too many times using the quick & dirty loop variable 'i' has caused issues in nested loops & refactoring so I decided to go with only full-fledged names.
Naming conventions exist as a tool to help you maintain readable code.
They are there to help you. They are not a rule.
There's a higher value to have easy to read - maintainable code than to blindly follow a naming convention.
I use single-letter uppercase types in my generics when the type can be (almost) any type. Like with Map<K,V> etc.
However, when the type has more meaning than just ANY type, such as:
public class Table<Column extends Enum<Column> & Table.Columns> {
...
public interface Columns {
...
I use a more appropriate name Column but retain the convention of the initial uppercase. I feel it is important to maintain brevity for types as you are likely to use it many times in the code. A single uppercase character is - you must admit - perfect brevity.
In c# you can create variables named identically to a keyword by using #languagekeyword.
My question is, when would this be useful? When would the benefits out-weigh the drawbacks?
The CLR can be targeted by many different programming languages. One language's identifier is another language's keyword. It would be bad if a class library written in one language couldn't be used from another language because a declared method or property has a name that is a keyword in that language.
A simple example for a use of these syntax would be in a web application where you may be required to set some attributes to an HTML tag by giving an object like
new { #class = "cssClass" }
This would not be possible without that syntax.
It is most useful if you are writing a code generation framework and your underlying model (e.g. a DB) may contain domain objects that use keywords e.g. a db table or field named "event". In this case you can escape all names and there will be no clashes. This makes a code generator forward compatible if new keywords are added.
In general:
When you pick your own names, try to avoid it.
However, sometimes you don't entirely get to pick your own names. For example when you port code, or when you write a wrapper around code that's written in another language. In such cases I think it's better to stick to the original names, so that API descriptions still match with your code, instead of thinking of new names just to avoid a clash with reserved keywords.
It is not advisable to use variable names that conflict with reserved keyword but sometimes you may want to not follow that rule for readability.
For example:
var duplicates = from item in Items
group item by item.Name into #group
where #group.Count() > 1
select #group;
It kinda highlights the important part of code.
Other cases come to mind when you need to use third party code that you cannot change.
For the hardcore C# coders here, this might seem like a completely stupid question - however, I just came across a snippet of sample code in the AWS SDK forum and was completely sideswiped by it:
RunInstancesRequest runInstance = new RunInstancesRequest()
.WithMinCount(1)
.WithMaxCount(1)
.WithImageId(GetXMLElement("ami"))
.WithInstanceType("t1.micro");
This is very reminiscent of the old VB6 With ... End With syntax, which I have long lamented the absence of in C# - I've compiled it in my VS2008 project and it works a treat, saving numerous separate lines referencing these attributes individually.
I'm sure I've read articles in the past explaining why the VB6-style With-block wasn't in C#, so my question is: has this syntax always existed in the language, or is it a recent .NET change that has enabled it? Can we coat all object instantiations followed by attribute changes in the same sugar?
Isn't this better anyway?
RunInstancesRequest runInstance = new RunInstancesRequest
{
MinCount = 1,
MaxCount = 1,
ImageId = GetXMLEleemnt("ami"),
InstanceType = "t1.micro"
};
They implemented all those methods, each of which will also be returning the RunInstancesRequest object (aka, this). It's called a Fluent Interface
It is not syntactic sugar. Those methods just set a property and return the this object.
RunInstancesRequest runInstance = new RunInstancesRequest()
.WithMinCount(1)
.WithMaxCount(1)
.WithImageId(GetXMLElement("ami"))
.WithInstanceType("t1.micro");
==
RunInstancesRequest runInstance = new RunInstancesRequest().WithMinCount(1).WithMaxCount(1).WithImageId(GetXMLElement("ami")).WithInstanceType("t1.micro");
I don't know if that's considered syntactic sugar, or just pure formatting.
I think this technique is different than the With... syntax in VB. I think this is an example of chaining. Each method returns an instance of itself so you can chain the method calls.
See Method-Chaining in C#
The reason this syntax works for RunInstancesRequest is that each of the method calls that you are making return the original instance. The same concept can be applied to StringBuilder for the same reason, but not all classes have methods implemented in this way.
I would prefer having a constructor that takes all of those property values as arguments and sets them within the class.
It's always existed in C# and indeed in any C-style oo language (eh, most popular C-style language except C itself!)
It's unfair to compare it the the VB6 With...End With syntax, as it's much clearer what is going on in this case (about the only good thing I have to say about VB6's With...End With is at least it isn't as bad as Javascripts since it requires prior dots).
It is as people have said, a combination of the "fluent interface" and the fact that the . operator allows for whitespace before and after it, so we can put each item on newlines.
StringBuilder is the most commonly seen case in C#, as in:
new StringBuilder("This")
.Append(' ')
.Append("will")
.Append(' ')
.Append("work")
.Append('.');
A related, but not entirely the same, pattern is where you chain the methods of an immutable object that returns a different object of the same type as in:
DateTime yearAndADay = DateTime.UtcNow.AddYears(1).AddDays(1);
Yet another is returning modified IEnumerable<T> and IQueryable<T> objects from the LINQ related methods.
These though differ in returning different objects, rather than modifying a mutable object and returning that same object.
One of the main reasons that it is more common in C++ and Java than in C# is that C# has properties. This makes the most idiomatic means of assigning different properties a call to the related setter that is syntactically the same as setting a field. It does however block much of the most common use of the fluent interface idiom.
Personally, since the fluent interface idiom is not guaranteed (there's nothing to say MyClass.setProp(32) should return this or indeed, that it shouldn't return 32 which would also be useful in some cases), and since it is not as idiomatic in C#, I prefer to avoid it apart from with StringBuilder, which is such a well-know example that it almost exists as a separate StringBuilder idiom within C#
This syntax has always existed
Please refer to Extension Methods (C# Programming Guide)
This question already has answers here:
Closed 14 years ago.
Okay, this may be a dumb question, but I've not been able to find any information on it.
Are String.Empty and string.Empty the same? I always find myself gravitating towards using the upper case version (String.Empty) because I prefer the color and look of it in my IDE than the lower case version (string.Empty)...
Is there a "correct" way to use these that differ or is it entirely down to personal preference? It was my assumption that they're both the same, but to be honest, I never gave it any thought until for whatever reason today I wondered "If they both exist, they must both exist for a reason".
Is there a reason that anyone knows of? If so, what is it? Can anyone enlighten me?
P.S. The "exact duplicates" only answer half of the question - "which is right?", not the "why do they both exist?"
Exact Duplicate: What is the difference between String and string in C#?
Exact Duplicate: String vs string in C#
In C#, lower-case type names are aliases for the System.xxx type names, e.g. string equals System.String and int equals System.Int32.
It's best practice to use these language aliases for the type names instead of their framework equivalent, for the sake of consistency. So you're doing it wrong. ;-)
As for a reason why they both exist, the .NET types exist because they are defined in a language-independent standard for the .NET libraries called CTS (common type system). Why C# defines these aliases is beyond me (VB does something quite similar). I guess the two reasons are
Habit. Get all these C and Java programmers to use C# by providing the same type names for some fundamental types.
Laziness: You don't have to import the System namespace to use them.
EDIT Since many people seem to prefer the other notation let me point out that this is by no means unreasonable. A good case can actually be made for the usage of the CTS type names rather than C#'s keywords and some superficially good arguments are offered in the other answers. From a purity/style point of view I would probably concur.
However, consider if this is worth breaking a well-established convention that helps to unify code across projects.
It is conceptually similar to something like this:
using int=System.Int32
string is mapped to the String class AFAIK, so they're the same.
The same is true for, for example int and Int32.
Personally, I prefer to use String as both String and Object are references whereas all the other base types are value types. In my mind, that's the clearest separation.
They are both the same.
Personally I prefer using the lowercase string, the "blue one", using the C# keyword instead of the .NET class name for the same reason I'm using int instead of Int32.
Also, the lowercased one doesn't require inclusion of the System namespace...