C# redundancy, noise [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
EDIT 1: This question is about new features of C#, not about actual possibilities (where there is no such thing as new default()).
EDIT 2: There is actually a discussion about that reduction of redundancy # .DOTNET Foundation.
When declaring a member,
class MyClass {
AnyClass<WithLong<Generic,Declaration>> value =
new AnyClass<WithLong<Generic,Declaration>>();
}
is quite redundant.
We may find the following, more concise, less noisy:
AnyClass<WithLong<Generic,Declaration>> value = new default();
// or
AnyClass<WithLong<Generic,Declaration>> value = new();
// or
AnyClass<WithLong<Generic,Declaration>> value = new var();
Is there any benefit to the actual redundancy, or any risk on a more concise declaration that I haven't identified ?
Note 1:
var is actually a good way to reduce noise :
var value = new AnyClass<WithLong<Generic,Declaration>>();
My comment is about extending that concision to members.
Note 2:
A similar question has already been posted, but answers don't really care about redundancy & noise, which is unfortunate, because i think keywords like default, var are already intended to reduce code noise, and that is not a so futile question.

The C# team acknowledge this issue and they plan to remove extra noise when relevent.
In the specific case of Dictionary, you will have to wait until C#9.
Dictionary Literals introduces a simpler syntax to create initialized Dictionary objects without having to specify either the Dictionary type name or the type parameters. The type parameters for the dictionary are inferred using the existing rules used for array type inference.
// C# 1..8
var x = new Dictionary <string,int> () { { "foo", 4 }, { "bar", 5 }};
// C# 9
var x = ["foo":4, "bar": 5];
This proposal makes the work with dictionaries in C# simpler and removing the redundant code. In addition, it is worth to mention that a similar dictionary-syntax is used in other programming languages like F# and Swift.
source
Well no... I just read that the dictionary literals issue was rejected...
We think there are a number of interesting use cases around initializing data, particularly for things like immutable dictionaries. We don't find the existing syntax for initializing a dictionary that onerous, nor do we see it as a frequent pattern in code that would benefit much from a language feature. We thing that the general area of initializing data should be looked at again after we do records and withers. But this proposal doesn't feel compelling.

Related

C# Coding Best Practice [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm currently doing work which requires me to convert VB.Net code to C#.
I've been using the "Builder Pattern" primarily and this has me converting many functions that are one single call of a function ie. SomeFunction(var1,var2,var3) into:
Dim Director As New SomeDirector
With Director
.SomeProperty = SomeValue
.SomeProperty2 = SomeValue2
End With
My concern is that this creates 5-6 lines of code rather than one single line. Is there a way for me to do this in a more concise way or is it better to have the 5-6 lines of code?
Thanks!
As already mentioned, you can do something similar in C# with object initialisation:
var Director = new SomeDirector { SomeProperty = SomeValue, SomeProperty2 = SomeValue2 };
This does not require you to write an explicit constructor.
One neat way to write that is with a constructor in the SomeDirector class:
public SomeDirector(int value1, int value2)
{
this.SomeProperty = value1;
this.SomeProperty2 = value2;
}
then your code sample becomes:
var director = new SomeDirector(someValue, someValue2);
The idea here is that while the constructor looks a bit long-winded, it's tucked away in the class and the code that calls it is nice and concise (and you can't forget an important property).
In case you wondered, there's no C# equivalent of VB's with keyword.
More of a general answer to your question:
In theory it doesnt matter how many lines of code you have, only how much resources it costs to execute. But best practices are also about human readability so it really depends on the situation. Do you need to optimize for performance or further development. This is something that in most cases you as a developer will know better than anyone else who dont have the full insight.

When to create a new function? [closed]

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 6 years ago.
Improve this question
I had an argument with my teammate about the following.
We need to parse a symbol in a string to int(it is always a digit), this particular functionality is used in a number of places. So this can be done this way:
var a = int.Parse(str[i].ToString());
The argument was: do we need to create a function for this.
int ToInt(char c) {
return int.Parse(c.ToString());
}
that can be used:
var a = ToInt(str[i]);
My opinion is that creating such a function is bad: it gives no benefits except for typing couple characters less (no, as we have autocomplete), but such practice increase a codebase and makes code more complecated to read by introducing additional functions. My teammate's reason is that this is more convinient to call just one such function and there is nothing bad in such a practice.
Actually question relates to a general: when it is ok(if at all) to wrapp combination of 2-3-4 functions with a new function?
So I would like to hear your opinions on that.
I argee that this is mostly defined based on personal preferences. But also I would like to hear some objective factors to define a convention for such situations in our project.
There are many reasons to create a new sub-routine/method/function. Here is a list of just a few.
When the subroutine is called more than once.
If it makes your code easier to read/understand.
Personal preference.
Actually, the design can be done in many ways of course, and depends on the actual design of the whole software, readability, easy of refactoring, and encapsulation. These things are to be considered on each occasion by its own.
But on this specific case, I think its better to keep it without a function and use it as the first example for many reasons:
Its actually one line of code.
The overhead of calling a function in performance will be far more the benefit you get from making it.
The compiler itself probably will unwrap it again into the one line call if you make it a function, though its not always the case.
The benefit you get from doing so, will be mainly if you want to add error checking, TryParse, etc... in the function.

why indexer are known as smart array in c#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm totally new to programming and I am wondering; when would be a good time
to use an array or an indexer? I want to know what types of applications
would make good use of arrays or indexers. There seems to be other ways of
doing the jobs of the two and less confusing.
The books I read don't provide good examples of situations when I would need
an array or indexer. I don't really need a definition of them as I already
have that. I just need to know what which well known apps have uses for
arrays and indexer?
This is the first time I've ever heard the term "smart array" in C#
No one uses the phrase "smart array" not that I heard of.
http://social.msdn.microsoft.com/Forums/en-US/3b56248f-1ff6-41aa-a0cd-35735e802e13/what-is-indexer-for-in-c
no one calls indexers smart array except the guy in the linked forum post.
indexers used for stuff like Dictionaries and Hashtables
In general I think arrays are a pain to manage, and I don't use them very often. As a programmer, you have to be completely responsible for the length of an array.
string[] str1 = new string[10];
When you add and remove items from the array, you have to be aware of all times where in the array you are.
Personally I avoid arrays when possible and use strongly typed collection, like List
List<string> str1 = new List<string>();
Then I can use the built-in methods to manage the items without having to be as concerned with managing the fine details.
str1.Add("Hello!");
str1.Add("Hello again!");
str1.RemoveAt(0);
Console.WriteLine(str1[0]); //Hello again!
I think answer to why indexer are known as smart array in c#? question is they are not.
Post on MSDN forum does not prove anything. There is nothing about smart array on MSDN documentation. You should follow official feature naming, which is indexer or indexed property. That's the name you can find on
Specification: chapter 10.9 Indexers
An indexer is a member that enables an object to be indexed in the same way as an array. Indexers are declared using indexer-declarations:
Documentation: Indexers (C# Programming Guide)
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

Divide or multiply element by element - c# vs f# comparison [closed]

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 9 years ago.
Improve this question
I know there are lots of external packages on linear algebra but my question is really when do I use f# and when c#? I make a simple example and while I did this I realized maybe it is too simple. but lets say I want to do element by element division of two arrays:
Imperative c#:
static double[] elementdivideimp (double[] arr1, double[] arr2)
{
var res = new double[arr1.Length];
for (int i = 0; i < arr1.Length; i++)
{
res[i] = arr2[i]/arr1[i];
}
return res;
}
LINQ c#:
static double[] elementdivideL(double[] arr1, double[] arr2)
{
return arr1.Zip(arr2, (a, b) => b/a).ToArray();
}
f#:
let elementdividefunc a b = Array.map2 (fun i j -> (j / i)) a b
As said maybe this is too simple but I m really struggling to decide which language to go for when I face a programming challenge. SO when do I use which?
As already mentioned in the comments, use the right tool for the job.
Now, the question is, when is F# the right tool for the job. To get a useful answer, it is important to look at the problem from the business perspective - what business problems are you facing and can F# (or any other language) help you solve them?
I think the talk Succeeding with functional-first languages in the industry by Don Syme looks at this problem from the right perspective. It looks at the specific task of developing analytical components and explains what problems people usually face in this domain (correctness, complexity, efficiency and time-to-market) and how better languages can help you overcome those (and many of the points are based on the evidence collected by the F# foundation and numerous earlier SO questions #1 #2).
I think you will not get a clear answer just by comparing fairly simple snippets of code, but your example demonstrates that:
F# code is generally more concise which likely reduces time-to-market
Compared with imperative C#, you do not need to handle corner cases, which aids correctness
You can easily use data structures like arrays, so your code is more efficient (I have not tested this, but I think the C# code uses IEnumerable<T> and will actually be slower in this case).
If you look at other business areas, then you may find different problems and then you can base your evaluation on those. But for analytical components (computations), I think there is a good evidence for languages like F#.

what is the best way to declare string or any other data type in c# [closed]

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 9 years ago.
Improve this question
which is the best memory efficient/efficient way to declare string and other data type variables in c#!?
Option 1
string strAssociateId = context.Request.QueryString["xxxxxx"],
strAssociateName = context.Request.QueryString["xxxxx"],
strPhoto = context.Request.QueryString["xxxxx"],
strDescription = context.Request.QueryString["xxxxx"];
or
Option 2
string strAssociateId = context.Request.QueryString["xxxxx"];
string strAssociateName = context.Request.QueryString["xxxxx"];
string strPhoto = context.Request.QueryString["xxxxx"];
string strDescription = context.Request.QueryString["xxxxx"];
or
any other way!?
which is the best way to follow on a longer run?!
or both have the same efficiency!?
downvoters pls comment so that i can correct.
I am just trying to find the best way and this question is not there in stackoverflow before!!
this will not lead to any discussion, and the question is completely answerable and clear
The only difference between those options, is readability. There are no performance difference, and they will generate the exact same IL.
For readability, I would choose option 2.
They will be compiled to the same IL, your Option 1 is simply syntactic sugar.
I my opinion Option 2 is better because it has better readability.
which is the best way to follow on a longer run
Both are best as both will generate the same IL.
or both have the same efficiency
Yes as both have same efficiency.
Which one to follow
You need to follow the one that is followed through out your application to support consistency. However if you are starting a new project you can decide not which one you like the most. My preference is the second one as it is more common as well as more readable
Both are better. But you are gonna mess up with the code. If you prefer using second method you might require or consider using comments
// this code is this..
So that you can know what variable or string was written here. Either you might think that this is a parameter to something.
The first method is more lovey to everybody. However I don't use strings. I use simple vars.
To follow a long run, you can use any of them. They don't have any time consuming effect.
To check more about these You can use IE F12 Developer Tools. To Test which page is using more time to get loaded.

Categories