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...)
Related
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.
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.
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.
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
A question was raised in a discussion I had around whether an interface method should return a Custom object vs a primitive type.
e.g.
public interface IFoo
{
bool SomeMethod();
}
vs
public interface IFoo
{
MyFooObj SomeMethod();
}
Where MyFooObj is:
public class MyFooObj
{
bool SomeProp{get;set;}
}
The argument being that you can easily add properties to the object in the future without needing to change the interface contract.
I am unsure what the standard guidelines on this are?
IMHO Changing the MyFooObj is the same as changing/adding methods to the IFoo Interface - so no I don't think it's a good idea add just another abstraction - remember YAGNI
My standard response is - YAGNI.
You can always change things if it turns out that way, in particular if you control the full source of the application and how the interface is used.
Wrapping a boolean just in order to forecast the future is only adding complication and additional layers of abstraction when they are not currently needed.
If you are using DDD and specific modelling techniques in your codebase, is can make sense to have such aliases to booleans, if they are meaningful in your domain (but I can't see this being the case for a single boolean value).
I don't see the point of encapsulating primitive types in a custom object.
If you change the definition of this custom object, then you actually change the contract because the function doesn't return the same thing.
I think it's again an over-engineered "pattern".
There are no general guidelines regarding this.
As you pointed out, if you have semantics around the return type that you think strongly believe may change or may need to be updated in the future it may be better to return the complex type.
But the reality is that in most circumstances it is better to keep things simple and return the primitive type.
That depends somewhat on what you like. My opinion, that in your sample case, I would stick with the simple bool in the interface definition for those reasons:
it is the simplest to read possibility
no one looks for methods that aren't available
IMHO, an object makes sense only when a certain amount of complexity/grouping is required as a result.
If its not required to begin with you should not wrap it changing what is returned inside the object is simply the same as changing the interface which breaks rule number one of programming with interfaces.
Its right up there with designing for extension, YAGNI (you ain't gonna need it).
As a side note I got told off for stuff like this early in my career.
If you ever need to return something more than a boolean, it is extremely likely that you are going to modify other parts of the interface as well. Do not make things more complex than they need to be: simplicity is prerequisite of reliability.
In addition to the other answers, adding a new field to a custom class is technically still a potential breaking change to the interface's consumers. Link
Just thought I'd mention that if MyFooObj is in an assembly which is strong named, you update it, its version gets updated - old clients will immediately break (e.g. InvalidCastException) due to a version mismatch (it won't attempt a partial bind due to strong nameness) unless they recompile with the new version. You've still changed the interface contract. So best to keep things simple, return the primative type and declare your change of contract more explicitly.
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.