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.
Related
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.
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
So, I'm writing some code for practice and I've come to a point where I want to make a function where I can check a class for objects made from it and then, be able to use the methods and/or data fields I've written on the objects
Like, let me use a kind of blunt example
Dog.CheckForObjectsOfSameClass();
I've tried using a static number to refer to to then refer to the parent of such data, but I can't find a command for that either.
I would post the code I've tried to use before, but it would just make this the more confusing.
Thanks in advance for any answer that can help me solve this doubt
It sounds like you're asking for something like built-in reference counting. Other than the garbage collector there isn't anything like this in the language, and trying to hook into the garbage collector just to write normal application code would in my opinion be an utterly weird, crazy and plain dreadful thing to do.
As one of the comments suggests, this sounds like an XY problem, where the real solution is to understand why holding a reference to the object you want to access is difficult, and change your coding approach to do this in a more straightforward way. Depending on exactly what you are trying to do, adding a newly created object to a dictionary:
var dogs = new Dictionary<string, Dog>();
var rover = new Dog();
dogs.Add("rover", rover);
using a meaningful key to distinguish which object is which, might be a way of solving the problem.
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.
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.
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 best?
private long sumVals()
{
return (dbReturn("NUns") / dbReturn("TSpd")) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
or
private long sumVals()
{
long numUnits = dbReturn("NUns");
long targetSpeed = dbReturn("TSpd");
return (numUnits / targetSpeed) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
Is it better to try and put it all onto one line, so there is less code overall, or to spread it out like in the second one?
Is one or the other quicker? Is there a benefit, eg, while compiling?
Your case is simple, so the first one is OK. But in general, I would go for the second one.
It is important that you (and others) can read the code, but you don't need to save memory (fewer lines of code as well as fewer variables).
Your code will be easier to understand and debug if you choose to write it the second way. You also don't have to have a lot of comments if your variable names explain the code well enough, which makes your code easier to read in general. (I am not telling you to stop commenting, but to write code which does not need trivial comments!)
See this question for more answers.
My rule of thumb is to include enough content to fully describe what the intent of the code is, and no more. In my opinion, assigning values to variables only to use those variables immediately is actually less readable. It communicates the flow of the program well enough, but doesn't communicate the actual intent.
If you renamed the function from dbReturn to GetDatabaseValue then I don't think I can come up with a more expressive way to write this function than:
return (GetDatabaseValue("NUns") / GetDatabaseValue("TSpd")) * 60);
This communicates the intent perfectly (notwithstanding the fact that I don't know what "NUns" and "TSpd" mean). Fewer symbols means fewer things to understand when reading the code.
Full disclosure: Including extra symbols does improve debuggability. I write this way when I am first building a function so that I can track down where things go wrong. But, when I am satisfied with the implementation, I compress it down as much as possible for my and my co-workers' sanity.
As far as I can tell, there would be no run-time performance gain achieved by either approach. Compilers are awesome - they do this inlining without your knowledge. The only difference is in the code's readability.
To me, longer is always better. Modern compilers will shrink most code to be very fast. However, being able to maintain code through lots of comments and easy-to-read code is hugely important.... especially if you are one of those guys who have to maintain someone else's code!
So, my vote is the longer version (with a comment explaining what you are doing too!)