Is using var in c# really that bad? [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 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.

Related

Is protobuf a good choice of the universal data model? [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 11 months ago.
Improve this question
We are trying to find a universal data model, which can be applied everywhere.
I think there is no doubt that protobuf is good in the microservice architecture as a protocol among processes of different platforms (Windows, Linux, etc.) and languages (Java, C#, C++, Python, etc.)
But how about using protobuf within the process?
To make it simple and easy to illustrate the problems, let say I am making a C# gRPC service and GUI (gRPC client).
After some study, it seems that it is not suitable from what I can see.
Stability: It looks like that protobuf is still in a changing phase. For example, removing Optional keyword in proto3, but adding it back again in proto release 3.15.
Data type: The data types in proto are not fully compatible with common data types. For example, decimal. We need to define another complex data type (What's the best way to represent System.Decimal in Protocol Buffers?) and doing the conversion.
Conversion: We need conversion before we can utilize it in the related language. You cannot add the self-defined proto decimal directly in c#.
Repeated conversion: Conversion is not one off, but back and forth. Let say we have this proto object passing through 5 functions and need to have some calculations on the decimal field at each function. That means, we will need to convert the decimal field in the proto object to C# decimal in each function, have the calculation to get the result, convert and assign the result back to the decimal field in the proto object, then pass the proto object to the next function.
GUI control binding: We cannot bind the proto field (for those without an matched type in C#). Even we can specify the conversion to do so in the control somehow, (Indeed, I am not sure if we can/it is good to do so) in simple control, like textbox. It may not be easy for complicated control like datagridview because there may be different built-in editors for different native data types. If we use proto data types, that means we need to write customized editors for them. And also, we may need to define other behaviors, like how to sort them.
Using the auto-generated proto class within the process seems not a good idea to me as the reasons listed above. The above case only focus on C# service and client. When it comes to different languages, the cases should be more complicated.
Although .net soap services are slow and wordy (if you look at the wsdl definition), one thing I appreciate very much is that both the service and the client are using the same object with native data types, which can be used directly without any issue. The conversion is done in the communication directly and automatically.
The way I can think of at the moment is that:
Using proto as a communication protocol only
Write a class (use native/built-in data types) for each proto message type and our own conversion logic. Doing so because I cannot find any framework/lib to do so.
After receiving the proto object, convert it directly to an object with native/built-in types before further processing. (the benefit here is that even there is a major change in proto spec, we only need to change the conversion logic only without affecting other layers).
Am I on the right track? What is common/best practice to resolve the problems listed above?
Any help is highly appreciated!!!

Why does the "out" parameter exist in C# as a language construct? [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 4 years ago.
Improve this question
Question
Why does the "out" parameter exist in C# as a language construct?
Elaboration on the question
Why does it exist in the first place? Aren't there better language features to get the same effect one can get with the "out" parameter?
Isn't it strange to make an value type behave like a reference type?
Aren't there better ways to return multiple values from a method?
Is it a historical thing, meaning with the first versions of C# there was no way to achieve the things one can achieve with the out parameter but now there are newer features and it's just kept in the language for backwards compatibility?
What I'm not asking
I'm not asking what it does
out parameter modifier (C# Reference)
I'm not asking how it is used
https://stackoverflow.com/a/8128838/33311
What is the purpose of the "out" keyword at the caller (in C#)?
I'm not asking what the difference between "ref" and "out" is
What's the difference between the 'ref' and 'out' keywords?
I read that one should avoid its use and choose other constructs
Best practice of using the "out" keyword in C#
I haven't found any duplicates while reading the similar questions.
Expected answer format
I'd love to hear something like, "Look, here is a problem you can only solve with the use of the "out" parameter language construct and here is a code example for it...".
Or, "Look, this used to be the only way to solve the following problem ...code example..., but since C# version ... the better way to solve is like this ... code example...".
No opinions please.
The C# compiler performs definite assignment checking. That requires it to know exactly when a variable is assigned. Usually not hard to figure out, an assignment is pretty easy to see back.
But there is a corner-case is when a variable is passed by reference to another method. Does the method require that variable to be assigned before the call, then modifies it, or is it only ever going to assign it? The compiler in general cannot know, the method may live in another assembly with the method body unavailable. True for any .NET Framework assembly for example.
So you have to be explicit about it, you use ref when the method requires the parameter to be assigned before the call, out when the method only ever assigns it. Great feature btw, it eliminates an entire swath of very common bugs.
One note about other incorrect answers on this question. Data flow plays an important role in pinvoke as well, the pinvoke marshaller needs to know whether the convert any data returned by an unmanaged function. It does not pay attention to out vs ref keywords, only to the [In] and [Out] attributes. More about that gritty detail in this Q+A.
One reason would be for compatibility with e.g. Win32 APIs. Some method declarations for Win32 API calls will require the use of out and/or ref if you want to call them directly from C#.
You can find some examples of such method declarations at pinvoke.net:
http://pinvoke.net/search.aspx?search=out&namespace=[All]
Why does it exist in the first place? Aren't there better language features to get the same effect one can get with the "out" parameter?
Whats "better"? Arguing based on C#7 where things are a bit easier, is this:
public static (bool Succesful, int Value) TryParse(string s) { ... }
var parseResult = TryParse(s);
if (parResult.Succesful)
DoSomething(parResult.Result);
better than?
if (int.TryParse(s, out var i))
DoSomething(i);
Hmmm....
And before native tuple suport, you'd actually have to implement a struct/class to be able to return multiple values.... yuck. True that the out solution wouldn't be as clean either, but still a better option than having to litter your code base with tons of lightweight container classes to simply have methods return multiple values.
Isn't it strange to make an value type behave like a reference type?
Why? Even if its only for backwards compatibility or for interop, its a needed language feature.
Aslo, your mixing up things here. If you want pass by reference semantics, you'd use the ref keyword. The out keyword means that the parameter is meant to be used as a return value; the fact that it needs to be passed by reference is an implementation detail.
Aren't there better ways to return multiple values from a method?
This is basically your first question rewritten.
Is it a historical thing, meaning with the first versions of C# there was no way to achieve the things one can achieve with the out parameter but now there are newer features and it's just kept in the language for backwards compatibility?
Backward compatibility is the obvious and important reason. Also, just because there are better ways to do things doesn't necessarily mean that language features should be removed. You could then make a case for many other language constructs: for loops, goto, etc.

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.

Why is there no inverse to object.ToString()? [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
It seems like a good design decision that the System.Object class, and hence all classes, in .NET provide a ToString() method which, unsurprisingly, returns a string representation of the object. Additionally in C# this method is implemented for native types so that they integrate nicely with the type system.
This often comes in handy when user interaction is required. For example, objects can directly be held in GUI widgets like lists and are "automatically" displayed as text.
What is the rationale in the language design to not provide a similarly general object.FromString(string) method?
Other questions and their answers discuss possible objections, but I find them not convincing.
The parse could fail, while a conversion to string is always possible.
Well, that does not keep Parse() methods from existing, does it? If exception handling is considered an undesirable design, one could still define a TryParse() method whose standard implementation for System.Object simply returns false, but which is overridden for concrete types where it makes sense (e.g. the types where this method exists today anyway).
Alternatively, at a minimum it would be nice to have an IParseable interface which declares a ParseMe() or TryParse() method, along the lines of ICloneable.
Comment by Tim Schmelter's "Roll your own": That works of course. But I cannot write general code for native types or, say, IPAddress if I must parse the values; instead I have to resort to type introspection or write wrappers which implement a self-defined interface, which is either maintenance-unfriendly or tedious and error-prone.
Comment by Damien: An interface can only declare non-static functions for reasons discussed here by Eric Lippert. This is a very valid objection. A static TryParse() method cannot be specified in an interface. A virtual ParseMe(string) method though needs a dummy object, which is a kludge at best and impossible at worst (with RAII). I almost suspect that this is the main reason such an interface doesn't exist. Instead there is the elaborate type conversion framework, one of the alternatives mentioned as solutions to the "static interface" oxymoron.
But even given the objections listed, the absence of a general parsing facility in the type system or language appears to me as an awkward asymmetry, given that a general ToString() method exists and is extremely useful.
Was that ever discussed during language/CLR design?
It seems like a good design decision that the System.object class, and hence all classes, in .NET provide a ToString() method
Maybe to you. It's always seemed like a really bad idea to me.
which, unsurprisingly, returns a string representation of the object.
Does it though? For the vast majority of types, ToString returns the name of the type. How is that a string representation of the object?
No, ToString was a bad design in the first place. It has no clear contract. There's no clear guidance on what its semantics should be, aside from having no side effects and producing a string.
Since ToString has no clear contract, there is practically nothing you can safely use it for except for debugger output. I mean really, think about it: when was the last time you called ToString on object in production code? I never have.
The better design therefore would have been methods static string ToString<T>(T) and static string ToString(object) on the Debug class. Those could have then produced "null" if the object is null, or done some reflection on T to determine if there is a debugger visualizer for that object, and so on.
So now let's consider the merits of your actual proposal, which is a general requirement that all objects be deserializable from string. Note that first, obviously this is not the inverse operation of ToString. The vast majority of implementations of ToString do not produce anything that you could use even in theory to reconstitute the object.
So is your proposal that ToString and FromString be inverses? That then requires that every object not just be "represented" as a string, but that it actually be round trip serializable to string.
Let's think of an example. I have an object representing a database table. Does ToString on that table now serialize the entire contents of the table? Does FromString deserialize it? Suppose the object is actually a wrapper around a connection that fetches the table on demand; what do we serialize and deserialize then? If the connection needs my password, does it put my password into the string?
Suppose I have an object that refers to another object, such that I cannot deserialize the first object without also having the second in hand. Is serialization recursive across objects? What about objects where the graph of references contains loops; how do we deal with those?
Serialization is difficult, and that's why there are entire libraries devoted to it. Making it a requirement that all types be serializable and deserializable is onerous.
Even supposing that we wanted to do so, why string of all things? Strings are a terrible serialization data type. They can't easily hold binary data, they have to be entirely present in memory at once, they can't be more than a billion characters tops, they have no structure to them, and so on. What you really want for serialization is a structured binary storage system.
But even given the objections listed, the absence of a general parsing facility in the type system or language appears to me as an awkward asymmetry, given that a general ToString() method exists and is extremely useful.
Those are two completely different things that have nothing to do with each other. One is a super hard problem best solved by libraries devoted to it, and the other is a trivial little debugging aid with no specification constraining its output.
Was that ever discussed during language/CLR design?
Was ToString ever discussed? Obviously it was; it got implemented. Was a generalized serialization library ever discussed? Obviously it was; it got implemented. I'm not sure what you're getting at here.
Why is there no inverse to object.ToString()?
Because object should hold the bare minimum functionality required by every object. Comparing equality and converting to string (for a lot of reasons) are two of them. Converting isn't. The problem is: how should it convert? Using JSON? Binary? XML? Something else? There isn't one uniform way to convert from a string. Hence, this would unnecessarily bloat the object class.
Alternatively, at a minimum it would be nice to have an IParseable interface
There is: IXmlSerializable for example, or one of the many alternatives.

Why VS uses "this" so often? [duplicate]

This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
Closed 9 years ago.
I know what "this" keyword serves for but do not udnerstand why VS uses it nearly always, like this.Invalidate. If the call is placed within the class and there is no problem with identifier, what is it good for?
It is not VS who uses it but the developers who do. If you use a tool like Resharper, it always points out where "this" is unnecessary or redundant.
I think it's mainly a question of style. Using the this reference makes it 100% clear what you intend to reference.
You say there is no problem with the identifier (in that there is no clash of names in scope), but that doesn't mean there won't be in the future.
Additional names or classes could be added to an outer scope. It's unlikely and probably wouldn't cause a problem anyway, but it helps to remove any possibility of ambiguity.
It explicitly shows that this variable or method belongs to this class. It more readable. Its not mandatory though. Its up to the developer and the team to decide whether they want to use it this way or not. It's just another code style.
If the call is placed within the class and there is no problem with identifier, what is it good for?
I assume your talking about autogenerated code, from e.g. the forms designer. It could
a) be written to analyse the code it's already emitted, decide whether the identifier is ambiguous, and then based on that, decide whether to use this. to properly qualify the name, or,
b) just use this. for all class-scoped identifiers.
It may seem redundant in many cases, but the exact same IL code will be produced whether or not you use this. in an unambiguous context, so it's not as if it's causing any harm to always include it.
Adding this, in unnecessary cases, reduces your code's complexity and makes it more readable.
Hahaha, because if you use "this." then Intellisense pops up and you have all your class members at your disposal and don't have to type so much (or make so many typos, whatever...)

Categories