This question already has answers here:
When should one use dynamic keyword in c# 4.0?
(7 answers)
What's the difference between dynamic (C# 4) and var?
(14 answers)
Closed 6 years ago.
dynamic d = "hello";
Console.WriteLine (d.ToUpper()); // HELLO
Console.WriteLine (d.Foo()); // Compiles OK but gives runtime error
I'm reading a book an stumbled in this section, in the third line it only throws error during runtime but it will compile even though Foo method doesn't exist.
Why not check it in compile time rather than in runtime?
Edit:
What is the significance, and when can I use this concept?
With dynamic, you are instructing the compiler to ignore it and let the runtime handle it. This is super helpful when dealing with COM and other interfaces that the compiler doesn't know about.
If you want implicit types use var instead. The compiler will infer the type and keep it strongly typed.
The dynamic-keyword causes this behaviour which is intended. When making a variable dynamic you can do everything with it making it not compile-time-safe. So by making it dynamic you completely bypass the compiletime-types - that´s why you should take care when using it.
Checking the members at runtime is the whole point of dynamic though - why should it exist otherwise?
I assume you intentionally wanted the var-keyword which gives you compiletime-safety. Have a look at this point for the difference on both. As to the when to use the keyword have a look at this post.
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 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.
This question already has answers here:
C# variance annotation of a type parameter, constrained to be value type
(2 answers)
Closed 9 years ago.
Consider this interface:
interface Test<out T> where T : struct { }
It compiles without errors or warnings.
As discussed in this question, and mentioned in the Covariance and Contravariance FAQ:
Variance is supported only if a type parameter is a reference type.
So why does the above interface compile? It would make sense to fail (or at least warn) on the "out" keyword. I guess the question boils down to - is there any case where using out keyword in the above example makes any difference?
Update: Here's an example misleading behavior that may slip through for the unaware developer who looks at the Interface above:
typeof(IDummy).IsAssignableFrom(typeof(MyStruct)); // should return true
typeof(ITest<IDummy>).IsAssignableFrom(typeof(ITest<MyStruct>)); // returns false
If the coder isn't aware of variance not working for value types, they would expect the second line to return true - because of the out keyword - but it never will. This is exactly the bug that prompted me to ask this question...
Another example of code that would compile but produce unexpected results:
ITest<MyStruct> foo = ...;
var casted = (ITest<IDummy>)foo;
I would expect this to work (not knowing about the limitation of covariance to reference types) but it causes a System.InvalidCastException.
is there any case where using out keyword in the above example makes any difference?
Nope. You're allowed to specify out in the declaration, you just won't ever be able to actually leverage it when dealing with a specific instance of that type.
Nothing about this program doesn't work properly, so you're essentially asking for a feature request of the compiler prohibiting this behavior as it is a likely indication of a mistake on the part of the developer. The response to that request is (just like virtually any other feature request) that Microsoft either didn't consider this as an option, or if they did, determined that it wasn't worth the time and effort to actively prohibit this behavior.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C#: Difference between ' += anEvent' and ' += new EventHandler(anEvent)'
In C# .NET 3.5, the compiler doesn't care if I do this (assume ButtonClickHandler is a function):
button.OnButtonClicked += ButtonClickHandler;
or:
button.OnButtonClicked += new ButtonClickHandlerDelegate( ButtonClickHandler );
Are these functionally the same? I read the stackoverflow question below, but I'm not sure if it applies to this scenario as well:
The difference between implicit and explicit delegate creation (with and without generics)
Yes, the first is simply syntactic sugar for the latter. The compiler simply infers the type of the delegate and constructs it for you. The exact same IL will be emitted by the compiler.
The first, shorter and cleaner syntax (delegate inference - which I recommend you use for readability), was added in C#2 - that is why some designers (also Microsoft's) tend to use the long and more verbose syntax of newing the delegate.
Actually, I think this is a duplicate of this prior question.
In C# 4 this will produce identical code, so yes they are functionally the same.
In the first (shorter) form the compiler infers the delegate type from the method signature, which saves you the work having to do it explicitly.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there an actual difference in the 2 different ways of attaching event handlers in C#?
I've been seeing a lot of code that looks like this:
foo.Drop += new DragEventHandler(fooHandler);
But in the past, I've always done this:
foo.Drop += fooHandler;
Is there a difference between these two syntaxes? If so, is there any advantage to doing it the long way?
The second is shorthand for the first; they will compile to indentical IL.
However, the second syntax is new to C# 2.0; C# 1 only supports the first.
They will both result in the same IL.
So, in answer to your question, no - there is no benefit of using the longer version.
No difference , since .Net 2 and you can use what is called Method Group Conversion which allow you to Register the method name directly to the event without making a delegate Object
They are the same, but in the second example, the compiler uses Method Group conversion to infer the delegate type for you. Syntactic sugar...
This question already has answers here:
Difference between wiring events with and without "new"
(6 answers)
Closed 1 year ago.
What is the difference between this:
this.btnOk.Click += new System.EventHandler(this.btnOK_Click);
and this?
this.btnOk.Click += this.btnOK_Click;
They both work. The former is what Visual Studio defaults to when you use the snippets. But it seems like it only ads extra verbiage, or am I missing something?
No difference. Omitting the delegate instantiation is just syntax candy; the C# compiler will generate the delegate instantiation for you under the hood.
In C# 3.0 and later this is no difference. Before C# 3.0 EventHandlers were required due to compiler limitations, but with the advent of C# 3.0, the second form is preferred unless you want to be very explicit.
I believe that C# since 3.0 has implicitly added the delegate handler. However, it can help to be more explicit, especially when there are multiple possible delegate types.
"+= Delegate_Name" is a syntax sugar. Compiler will create new wrapper for you.