Is it ever advisable to escape keywords e.g. #class - c#

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.

Related

How to use a 'hard-coded' dictionary/enum

I am wanting to create a 'dictionary' of strings, however I have only ever learned how to use strings to reference what I want in a dictionary. I want something with more auto-correct (as typos can happen in a large table of strings), which is why I want to know how to hard-code. (The value of the strings will be retrieved from a text file, like JSON).
I notice that Microsoft uses some type of hard-coding in their String Resource File.
So instead of doing:
string result = strings["Hello"];
I wish to do this:
string result = strings.Hello;
The only thing I can think of is to use some external tool that creates an enum/struct script with the values from the text file. Is there a better option, perhaps one built into .NET?
Edit: I think 'strongly-typed' would be a better description over 'hard-coded'.
Edit 2: Thanks for all the comments and answers. By the looks of it, some code-gen is required to fufil this result. I wonder if there's already any tools out there that do this for you (I tried looking but my terminology may be lacking). It doesn't seem too difficult to create this tool.
There are compiletime constants and runtime constants.
Your wish for Autocrrection/Intellisense support requires a compile time constants. Those are the only ones Intellisence, Syntax Highlighting and the Compiler double check for you.
But your requriement of having the values generated from a 3rd party textfile, indicates either a runtime constant or some automatic code generation. Runtime constants would take away the Editor support. While Code generation would run into issue with the Editor only having a old copy of the file. And a high risk of breaking tons of code if a string in that one file changes.
So your two requirements are inherently at odds. You need to have your cake and eat it too.
Perhaps my primitve solution to the Enum/ToString() problem might help you?
Enumeration are for most parts groups of constants, and integer ones by default. With added type checks on assignments. That makes them a good way around Primitive Obsession. You reference a value from the group like you would any constant, readonly static field or readonly property. (There is other advantages like Flags, but I doubt they mater here).
While Enums have a string you could use for display and input parsing - the one you use in sourcecode - that one is absolutely not suited for display. By default they are all-caps and you would need to support Localisation down the line. My primitive Solution was a translation layer. I add a Dictionary<someEnum, String> SomeEnumStringRepresentation. This dictionary can be generated and even changed at runtime:
I need to display any specific value, it is SomeEnumLocalisation[someEnum]. I could add a default behavior to just ToString() the compiler representation of the Enum.
I need to parse a user input? Itterate over the values until you find a match, if not throw a ParseException.
I get to use compile time checks. Without having to deal with the very inmutable compile side strings anywhere else. Or with my code side strings changing all the time.
i am not quit understand what out put you want , bu I am just throwing an idea to here - how about to extend the class string and add your own methods to it ? so when you use strings.Hello it will return what you wanted?
example :
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

Long (readable) names in Generics/Templates

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.

.Net Coding Standards Using a prefix "Is" or "Has" on Method Names

Is it advisable to prefix an "Is" or a "Has" when creating a method that returns a Boolean. My feeling is that this practice is more suited to defining property names.
Say, we have a method like the following has some logic:
bool IsActivePage()
{
// Some logic to determine if the page is active...
}
Would it be more preferable to rename the method to GetActivePageStatus and then create a boolean property IsActivePage that returns the result of that method.
What is the .NET standard? All opinions will be appreciated?
The Framework Design Guidelines state that you should "give methods names that are verbs or verb phrases" since "typically methods act on data". Properties, on the other hand, should be named "using a noun, noun phrase, or an adjective" and "you can also prefix Boolean properties with Is, Can, or Has, but only where it adds value".
In this case, you are using a method rather than a property, probably since it is either expensive or has some side effects. I suggest you choose the name that provides the most clarity of what the returned value represents. The important part is that you're being consistent and that you're not confusing other developers with your convention.
I would be using
bool IsActivePage
{
get
{
// some logic
}
}
if the method has no side effects and is inexpensive.
I see no need to have both a method and a property for the same thing.
I vote for your solution: so YES, for methods , I personally think, it's better to have Get..Bla(), cause method intuitively, at least for me, is, not only something that returns a value to me, but also performs some calculations or calls other methods inside it, properties instead, just return value.
"Get" word, to me personally, seems DO SOMETHIGN+RETURN,
instead "Is" : check if this exists.
I think both are defensible. The key is really to think about how standardized a convention like this should be. In general, you should either decide at your team or company level about how to handle cases like this, and then be consistent after that. As long as code you and your company produce is clear to everyone involved, that's what matters.
I would say yes. All methods should start with an action verb to indicate that they do something. Is and Has are more suited for properties.
First, coding conventions are vitally important in any shared development project, or any project you expect to live beyond the first time you ship the code or set it down for a week.
That said, there are a number of .Net coding standards available on the Internet (Google is still your friend) and you should adhere to those documents as best you can. One exception is in a mixed language environment where different languages have different style conventions and you want to create a more common style that covers all of those languages. In that case, you should create a style document and publish it.
Would it be more preferable to rename
the method to GetActivePageStatus and
then create a boolean property
IsActivePage that returns the result
of that method.
I would probably not go this route. IMO either
a) the logic is very simple, and you can just put it in the property getter
b) the logic is not very simple, you want to put it in a method BUT NOT hide it inside a property where an unexpecting caller may incur unneeded overhead by using it inappropriately (ie not caching the value if there is significant overhead in calculating it)

C# syntax sugar - new way to set object attributes?

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)

Programming language where you can refer to a array element by . (dot)

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.

Categories