c# Variable uses [closed] - c#

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 8 years ago.
Improve this question
I using c# winforms and wanted to know how it's better to write and why.
if(txtName.Text == "John")
;
or
String name = txtName.Text
if (name == "John")
;
Edit: Thanks guys you helped me a lot!!!

The second version is pointless - it is longer, less readable and introduces one extra variable (though a good compiler would get rid of it, assuming it is not used elsewhere).
Of the two choices, this one is better:
if(txtName.Text == "John")
Though I would go with a third:
if(txtName.Text.Equals("John", StringComparison.InvariantCultureIgnoreCase)
You may want the StringComparison option to be a different enumeration value, depending on how you want the comparison to occur.

For simplicity sake I would go with:
if(txtName.Text.Equals("John"))

Maybe I'm wrong, but others are answering to some complex scenario which isn't the case of one suggested by OP.
What's better?
In fact, it's the same. There's a single difference: first approach, you're storing control's text in a variable and later you check if it's equal to John. Second approach does the same thing, but it gets control's text accessing its string value directly by calling Text property.
When to use a variable and when to access to the property directly? It's just an assumption, because this will depend on each particular use case, but in common terms, call Text property directly if you're accessing its object (the text) just for checking it in a moment of time, otherwise, you'd want to store it in some variable if:
If you want to do some concatenation with Text without affecting the text held by this (if you concatenate it to the Text, you're going to modify it in your app user interface too!).
You're in a multi-threaded environment and you want to get Text in its current state because it can change since user interface is available to the user and it can change its value during some operation.
You just like variables!. If you find using variables clarifies your code better and adds meaning, why not? Nowadays' computers, even mobile phones, have a lot of memory and one, two or three variables wouldn't change anything (maybe 1KB more? wohoo!).
That's all.

Read Best Practices for Using Strings in the .NET Framework.
if (String.Equals(txtName.Text, "John", StringComparison.OrdinalIgnoreCase)) {
// ...Code.
}

For string comparison i would suggest:
string.compare(strA, strB, stringComparisonMethod)
For accessing the text it doesn't matter, the second way is more friendly but both will do the same

I think the later is better because you will be using a less variable i.e. name . Except that I don't see any difference (the styling is obviously upto yourself)

If you're using the value in other parts of your code, I'd go with defining a variable. Otherwise, use the shorter version.
In C# you don't have to use .Equals to compare strings (in response to a comment). == does the same thing.

if(txtName.Text == "John")
This is more conventional and efficient way of these you have shown.
String name = txtName.Text
if (name == "John")
;
Declaring extra variable "name" will increase the code size with any benefit except increasing the program memory. Once I tried and found declaring extra variable and assigning text to it and later accessing this variable instead of text property txtName.Text makes it less efficient then accessing through property.

Related

Is it really worth it? [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 5 years ago.
Improve this question
I'm working on a project that was made by another developer, and I've been assigned the job to add extra functionality, although this question isn't about one application, it's about a language.
In C#, I find myself running across this probably around 50 times a day, I need to grab a value from a method and store it to a variable, or I need to store a variable, or even if I just need to hard code a variable to something.
Do I go with my head or my heart? My head says store it in a variable incase I need to use it more than once in the future, but then my heart says lets be lazy and just add it to the if check, instead of calling the variable, let me give you an example...
Example 1:
var name = SomeClass.GetName();
if (name.Contains("something"))
{
// do something
}
Example 2:
if (SomeClass.GetName().Contains("something"))
{
// do something
}
I guess what I am asking is, does it have any sort of advantage? Or does it not really matter?
Am I using memory by storing these? especially if I'm storing hundreds across a solution in all different types of methods?
Is it worth just using it inside the if directly for an advantage, or should I just have a variable just in case? Can anyone explain the difference? If there is any that is.
I'm talking about if I only ever use the variable once, so don't worry about the "having to change in multiple locations" issue, although if anyone does want to go into that aswell, I would appreciate it.
I think there will not be any notable advantages in performance wise as well as in memory-wise. But when we look into the following scenarios storing return values have some advantages.
The calling method(SomeClass.GetName() in this case) may return null
Consider that the SomeClass.GetName() may return null subject to some conditions, then null.Contains() will definitely throw NullReferenceException [This will be same in both examples that you listed] in such case you can do something like the following:
var name = SomeClass.GetName();
if (name!= null && name.Contains("something"))
{
// do something
}
Need to use the return value more than one time:
Here you are using the return value only for checking the .Contains("something"), consider that you wanted to use the return value later in the calling method, then it's always better to store the value in a local variable instead for calling the method repeatedly. If it's only for checking contains then change the return type to boolean and finish the job within the method
Ask yourself this question about this line of code:
var name = SomeClass.GetName();
How expensive is GetName() method? Is it going over the internet and downloading a file from somewhere and it takes seconds to minutes to download the file? Or is it doing some crazy computation that takes a few seconds to minutes. Or is it getting data from the database? These answers will help you decide if you should store it in a variable and then reuse the variable.
The next question even if the above answers were "Na! It is pretty quick and does nothing fancy" is to ask yourself this: "How many places in the current class are you making this call? 1? 10? 100? If your boss comes one day and says, "You know that method GetName(), well we are not going to use it anymore. We will use another method named GetName2()". How long will it take? Well imagine if you need to make the changes in 100 different places.
So my point is simple: It all depends.

Change string to be const [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 7 years ago.
Improve this question
Someone told me to place my entire application strings in const instead of inline.
Why is that?
Does it improve compilation time? run time? or just code standard?
example
instead of writing:
selectSingleNode.InnerText == "SomeString"
write
selectSingleNode.InnerText == SOME_CONST
You would do this purely for maintainability and readability. Using a named constant instead of a string literal will have no performance impact whatsoever.
Maintainability
If you have multiple places in the code that require the same string literal, having them all use the same named constant makes your code a lot more maintainable. If you ever decide you need to change the value of the string literal, there is only one place you need to make the change.
Readability
Even if your string literal is used in a single place, providing a named constant may make your code more readable.
For instance, in the following sample, which version do you feel conveys the intent more clearly?
// string literals
int startIdx = someString.IndexOf("[");
int endIdx = someString.IndexOf("]");
// vs. named constants
int startIdx = someString.IndexOf(TAG_START);
int endIdx = someString.IndexOf(TAG_END);
A properly chosen name for a constant can make the code's intent clearer. But the key here is that you have to pick a good name. Too often, I'll see things like:
private const string ASTERISK = "*"; // very poor name
That is a very poorly chosen constant name that doesn't help readability one bit. The problem is that it simply states the contents of the string literal, when instead, it should be communicating what the string literal is used for.
I've seen some tests where developers have tested execution time and IL generated between using const and non-const strings. It's true there is the slightest of performance gain from using const (though insignificant unless you're working for nasa or Wall Street) the real benefits are:
You are ensuring your values are immutable.
You are defining literals in one location instead of writing them inline. If you need to change a value in the future it should be easier.
This isn't exhaustive and I'm anxious to see what others post as well. Hope this at least helps.

Is using var in c# really that bad? [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
So I'm creating a connection library for a colleague of mine to save him time on his current project. My colleague will use this library in his c# application to connect to a rest api. Within the library I created Handlers for each request(GET / POST / PUT / DEL). When his application talks to my library i will return the response like this:
return client.PostAsync(url, content).Result;
This returns a dynamic object from the rest api.
Today he used my library and couldn't get it to work in combination with his application for some reason. I told him to use a var and that it would work like this:
var x = API.CreateTraject(parameter1,parameter2);
He refused to use var and ended up spending about 40 min figuring out how to get it to work without it. Then he blamed me for returning a dynamic object and that he will never use var because explicit is better so he told me.
Im normaly working as mobile developer (IOS / Android) where i use var all the time.
Now my question is:
Is it really so bad to use var? Should I convert the response in my library so he can explicitly type it in his application? In my opinion I would rather use var and save some time then spend 40 min trying go make it explicit.
Is it really so bad to use var? Should I convert the response in my library so he can explicitly type it in his application? In my opinion I would rather use var and save some time then spend 40 min trying go make it explicit.
var, in C#, is merely a compiler "trick". There is no dynamic typing involved, and the compiled code is exactly the same. When you hover your mouse over the variable, the IDE will tell you the "real" type that gets used.
Whether he uses var or your actual return type shouldn't matter at all in terms of how you create your library.
If your library is returning dynamic unnecessarily, that may be a different issue, and one which the user may have valid complaints. Unlike var (which is merely a compile time trick), dynamic does change the behavior significantly.
Alternatively, if you're returning anonymous types from your library, you may want to consider making an actual class for your values. Anonymous types are really only intended to be used within a local scope, and shouldn't be part of any public API.
There is nothing illegal with using var, it just lets the compiler figure out what data type the object should be.
The only danger is that you, the programmer, don't know what it is until you mouse over. This can lead to problems where you thought it was one thing, but it turned out to be something else.
It is okay to use var, it's not illegal or anything.
But I think if you know the type of variable, declare the variable with the type. This will make your code easier to read.
It's not bad to use implicit typing, it's just a matter of style. I personally use it a lot simply because it makes all my variable declarations take up the same amount of space, regardless of type.
However, using dynamic definitely can be bad, especially when it's used excessively. It means that type safety checks that can be performed compile-time need to be deferred until run time. Occasionally that's useful, but it can have performance impacts. Unless you really need to return a dynamic, I'd strongly recommend returning a specific type from your API method.
For what it's worth, if your coworker is so opposed to implicit typing he could've just used this:
dynamic x = API.CreateTraject(parameter1,parameter2);
var has nothing to do with dynamic. var is about type inference.
Your methods should not return dynamic to begin with. In any case create Generic Methods and let the consumer (your Colleague) decide what type of object the method will return.

Number of Parameter Passed to 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 9 years ago.
Improve this question
I want to know how many parameters can be passed to function, I mean what is good programming practice, regarding passing the parameters to function?
Code Complete suggests a maximum of 7. This is because of The Magical Number Seven, Plus or Minus Two:
...the number of objects an average human can hold in working memory is 7 ± 2; this is frequently referred to as Miller's Law.
Here's an excerpt from Code Complete 2nd Edition:
Limit the number of a routine’s parameters to about seven
Seven is a magic number for people’s comprehension. Psychological research has found that people generally cannot keep track of more than about seven chunks of information at once (Miller 1956). This discovery has been applied to an enormous number of disciplines, and it seems safe to conjecture that most people can’t keep track of more than about seven routine parameters at once.
The fewer the better, but only if it still makes sense. I've never heard of a standard number of params to be passed, but I have heard of ways to keep them down better.
For example, don't do this:
public void DoSomething(string name, int age, int weight, ...) { }
but rather:
public void DoSomething(Person person) { }
but hopefully that goes without saying. But also, I would recommend not creating a weird class just to trim down the parameter count.
IMHO 5 at MAX.
6 is too much for me and 7 overwhelming!
According to Clean Code - maximum 3
If you have many things you would like to pass to a function you may want to look at some other means of transferring that data as opposed to simple parameter passing. For example in certain cases it may be better to generate an XML file and then pass values related to getting data around that XML file. If you are running a web app it may be simply passing data through sessions or post rather than get or function calls that will simplify your life.
Also you may want to store some of that information as member variables.
I would recommend no more than 4. You don't want your lines to get much longer than 30 characters long unless you are generating some massive string, but even then it becomes really unreadable and gross (although necessary especially for javascript).
It's good programming practice to write programs so that they are easy to read. Personally I try not to write functions which have more parameters than can be displayed on one line on the screen. Usually that is no more than five or six parameters at most.
some ARM compilers pass three or less parameters using registers and any more than three are stacked. The stacked type call is slower than the call using registers so in this case you should use three or less parameters, for speed.
Depending on the architecture, more than 1-3 will cause passing on the stack. This is slower than passing via registers. From a performance standpoint, it is best to pass either a pointer to a wrapper class or a pointer to a struct. This ensures that only one value is passed in and saves some writes/reads to memory.
If you don't know how many parameters you are going to pass to a function use param for sending variable arguments to a method.

Always using custom data types [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 5 years ago.
Improve this question
I'm wondering whether it's insane to (almost) always use custom data types in C# rather than relying on built in types such as System.Int32 and System.String.
For instance, to represent a persons First name, the idea is to use a data type called PersonFirstName rather than System.String (of course, the PersonFirstName data type would have to contain a System.String). Another example is to have a PersonID class which represents the database identifier for the person, rather than to have a System.Int32.
There would be some benefits here:
Today, if a function takes an int as parameter, it's easy to pass in an ID of a Company object rather than the ID of an Person object, because both are of types int. If the function took a CompanyID, I would get a compilation error if I tried to pass in a PersonID.
If I want to change the database column data type from int to uniqueidentifier for a Person, I would only have to make the change in the PersonID class. Today, I would have to make changes in all places which takes an Int and is supposed to represent a company.
It may be easier to implement validation in the right places. " " may never be a correct first name, which PersonFirstName can take care of.
Yes, I would have to write more constructors. I could implement implicit overloading in these to make them easy to work with though.
Is this madness?
Yes, utter madness - to sum up your idea, and to Paraphrase Blackadder
It's mad! It's mad. It's madder than Mad Jack McMad, the winner of this year's Mr Madman competition
I don't think that's madness. I think using business logic objects with strongly typed objects is a very good thing
No, you're not getting any real benefit of that. For some things it makes sense, perhaps an Email class or maybe, maybe an ID class. However, having a "PersonID" or "ClientID" class seems to go far. You could have a "typedef" or alias or whatever but I would not go too far with this in most circumstances. You can go overboard very quickly and end up with a lot of work for no benefit.
Yes... It is ! You will lose more than you gain.
Yes, madness AND OVERKILL...
It sounds like a maintenance nightmare to me. what would the CompanyID constructor take? An integer? Sooner or later - you are going to have to use native types whether you like it or not.
So what I see here at first glance is a question within a question. Basically:
How do I mitigate complexity and change in my code base?
I would say that you need to look at the problem you are trying to solve and first see what the best solution is going to be. If you are dealing with something that is potentially going to be pervasive throughout your code base then you might want to see if you are violating SOLID design principles. Chances are that if you have one type that is being used in A LOT of different places your design is way too coupled, and you have a poor separation of concerns.
On the other hand, if you know that this type is going to be used in a lot of places, and it also happens to be very volatile (changes is certain), then the approach you mention above is probably the right way to go.
Ask yourself "What problem am I trying to solve?" and then choose a solution based on that answer. Don't start with the answer.
As extracted from Code Complete by Steve McConnell:
The object-oriented design would ask, "Should an ID be treated as an object?" Depending on the project's coding standards, a "Yes" answer might mean that the programming has to write a constructor, comment it all; and place it under configuration control. Most programmers would decide, "No, it isn't worth creating a whole class just for an ID. I'll just use ints.
Note what just happened. A useful design alternative, that of simply hiding the ID's data type, was not even considered...
For me, this passage is a great answer to your question. I'm all for it.

Categories