Dynamic Vs Var in C#

Sdílet
Vložit
  • čas přidán 19. 06. 2024
  • Newsletter signup (with exclusive discounts): signup.iamtimcorey.com/ (your email will be kept safe and you will not be spammed).
    Facebook Page: / iamtimcorey
    Want to see a full C# application built from scratch?
    Check out this course: iamtimcorey.com/courses/cshar...
    There is a lot of confusion around what the dynamic and var types are and when to use them. This video clears that up. Whether you need to know it for a job interview or just to use them properly, this video will show you what they are, why they exist, and when to use them.
    0:00 - Intro
    0:40 - basic difference explained
    3:51 - dynamic auto type conversion and why not to use it
    7:07 - examples of how dynamic may fail you at development and fail your application
    15:05 - method return type
    17:01 - why and when: dynamic
    19:02 - why and when: var
    24:57 - var as anonymous object and summary

Komentáře • 199

  • @nyuin4384
    @nyuin4384 Před 4 lety +7

    dark mode, clear voice, amazing explanations. thank you tim corey!

  • @lukenukem8028
    @lukenukem8028 Před 4 lety +10

    I've never even heard of the dynamic keyword until this video.

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety +5

      Glad you learned something new.

    • @lukenukem8028
      @lukenukem8028 Před 4 lety +2

      In the space of C# coding, I'm learning everyday I code.
      I seeing that there is endless potential.
      I even go back to old code in my active library and optimize in different ways, usually opening up opportunities to use that code better.
      Even now, I am transferring from my Control Console (full cmd) processing code into my main library. I love my Control Console. It's my 5th and I finally got it right. Goal was to just use the cmd perfectly, and it is. Then make possible my own cmds.
      I learned about Tuples and that opened up everything for me. Then again more recently with learning about nested functions, only thanks to an MSDN example about something else I was looking up.
      It's literally impossible to stop learning when one is a programmer.

  • @robbiexiong3508
    @robbiexiong3508 Před 6 lety +1

    Ty so much for the explanations. So much easier to understand with audio and code vs just trying to follow some online written example on how to use each keyword. Totally makes sense to me now.

    • @IAmTimCorey
      @IAmTimCorey  Před 6 lety

      I'm glad it cleared things up for you.

  • @subashbarik
    @subashbarik Před 2 lety +3

    Thanks a lot Tim , it really clarified my doubts and usage of Dynamic vs Var. Really helpful.

  • @alinapostol2230
    @alinapostol2230 Před 3 lety +1

    Great video! Now I clearly understand the difference between 'var' and 'dynamic'. Thank you!

  • @ambroselangat5067
    @ambroselangat5067 Před 6 lety +1

    Thanks Tim. Your presentation are really resourceful for those interested in knowing it all. Please keep it up!

  • @AmandeepSingh-xk4yv
    @AmandeepSingh-xk4yv Před 3 lety +4

    The most well thought out and useful videos on development with C#! Love the content!

  • @torrvic1156
    @torrvic1156 Před 4 měsíci

    Thank you so much for great and deep explanations of basic things, Mr. Corey! It is absolutely essential to understand those to make something way more complex.

  • @throxe
    @throxe Před 3 lety +2

    Thank you very much for the effort you put into your videos, the quality, depth and ease of grasping the concepts taught is top notch. You are a great teacher indeed.

  • @carlosmarte23
    @carlosmarte23 Před 7 lety +1

    Thank you for the explanation, I'm learning C# and I had a lot of doubts about the difference in this two keywords, and now I know exactly how to use them, thanks for yours tutorials!

  • @psalterynbass
    @psalterynbass Před 5 lety +1

    good video. I didn't have a reason to use dynamic. Now I see where it could be helpful.

  • @RameshYadav-ik5zl
    @RameshYadav-ik5zl Před 2 lety

    Thank you for covering this in simple and crisp video.

  • @RalfsBalodis
    @RalfsBalodis Před 3 lety +8

    0:40 - basic difference explained
    3:51 - dynamic auto type conversion and why not to use it
    7:07 - examples of how dynamic may fail you at development and fail your application
    15:05 - method return type
    17:01 - why and when: dynamic
    19:02 - why and when: var
    24:57 - var as anonymous object and summary

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety +3

      Thanks! I added it to the description.

  • @ernstpeterlegrand
    @ernstpeterlegrand Před 4 lety

    Hi Tim, thanks for the reply. I slowly get all the pieces together.

  • @bonchodikov6248
    @bonchodikov6248 Před 4 lety

    I loved the way how you explained the difference between var and dynamic. Would be great if you have a similar video for dynamic and object as well. Thanks again, respect :)

  • @stevenchilders4535
    @stevenchilders4535 Před 5 lety +2

    As I have come to expect from you, this is another great video. I was not even aware of the dynamic type before seeing this video but completely understand how it is different from var. I am new to programming (knowing only C# at this point) but tend to agree with you on mixing var and explicitly stating the type for simple variables. All the best!

  •  Před 7 lety +1

    Thanks Tim for the video, it's very useful!

  • @zlatkozeco7951
    @zlatkozeco7951 Před 3 lety +2

    Thanks a lot for your videos!!!
    You deserve the thumb up even before I watch your videos 😊

  • @ScilexGuitar
    @ScilexGuitar Před 3 lety +2

    Great video! I've not heard aboyt Dynamic before, and that might be a good thing. But good to learn about it now and its consequences

  • @PanikGrafik
    @PanikGrafik Před 3 lety +3

    I've been developing for several years and have never ran into dynamic before. Great video!

  • @amrextracoding
    @amrextracoding Před měsícem +1

    Very helpful video. thank you so much for deep explanation.

  • @makaveli106965
    @makaveli106965 Před rokem

    Great tutorial, thank you Tim!

  • @michaelschneider603
    @michaelschneider603 Před 2 lety +4

    If for nothing else, I think the dynamic keyword is useful as an educational tool to compare and understand the differences of static and dynamic typing, side by side in the same language. Otherwise, whenever one wants to discuss the differences between the two typing approaches, one has to compare different languages where they are applied, e.g. Java vs JavaScript or Python, which may easily lead to some sort of apples and oranges comparison - not to mention heated debates between the proponents of those languages.

  • @Kamil0289
    @Kamil0289 Před 2 lety

    Nice tutorial, learned much. Thanks Tim :)

  • @user-pp6tv9jh6g
    @user-pp6tv9jh6g Před 3 lety +2

    thank you Tim!

  • @simon-white
    @simon-white Před 4 lety +1

    Agree with your preferences on this. Our code is compiled because it's meant to be human readable and therefore unambiguous - explicit declaration facilitates this. Also as you've noted before, it makes you question if the types you're using are actually appropriate: critical thinking can only be a good thing.

  • @willac4261
    @willac4261 Před 3 lety

    Thanks a lot for this information!

  • @udhayavanan4788
    @udhayavanan4788 Před 3 lety

    Thanks. Worth watching 👍 keep Post ❤️

  • @afonsomarinho101
    @afonsomarinho101 Před měsícem

    Very helpful video and clear explanation, just wish you had included the 'object' type as well

  • @hamzarashid7579
    @hamzarashid7579 Před 3 lety +1

    Thank you for this tutorial very well explained
    Keep it up and I sub your channel

  • @hvbsalmarm
    @hvbsalmarm Před 6 lety +5

    Hi Tim. Thanks for your videos. I am an experienced developer with several languages under my belt, but mostly C++. I have very recently decided to bring C# into my repertoire. Near the end of this video you talked about using var vs the actual type and said that you preferred to use the actual type most of the time. The reason that you gave for people wanting to use var all the time was because variable names must be descriptive and so the type is easy to determine from the name. I don't know if that is the main reason for most people in that camp, but it's a bit bogus.
    Like you I use both. I however prefer using var more often rather than less. It seems that var in C# is the same animal as auto in C++. Here are a few reasons that I prefer to use it:
    1. Using var forces you to instantiate you object variables. After all these years I still forget sometimes to add the 'new ...'. If the type were var then this problem is caught easily by the compiler and you won't be subjected to weird behaviour or crashes from this. For this reason I would definitely use it even for your Person class.
    2. Using var forces you to initialize all your variables, including basic types. This is very helpful in avoiding weird errors due to unexpected values. There is no harm in casting your initializer value to make it's type explicit.
    3. In a foreach or similar construct the data type of the container or even the container's content could change after further development. Using a var to refer to it means that in this scenario your code will be less likely to break in subtle ways such as you now pointing to the wrong type because you had forgotten to change the type in some of the loops that you use it. The only places you might need to fix are where the interface of the object has changed slightly and that's usually a compile time error.
    Benefits as I see it:
    - Whenever you have to allocate an object you are forced to type in the data type so you know what it is just by looking at it so readability is satisfied.
    - You can not go on without initializing it so both instantiation and initialization are satisfied.
    - Code maintenance is made a bit easier.
    That said, sometimes it is just easier to use a basic type, especially in very local scope.

    • @IAmTimCorey
      @IAmTimCorey  Před 6 lety +2

      Very well reasoned arguments. The biggest reason I see for not using var is because it makes reading the code easier for a new developer. I try to write my code in such a way that the new intern can maintain what I wrote. By specifying the type, there is no confusion as to what I meant. For instance, is a number a double or an int? It might not be entirely clear by the declaration. A rookie might put an integer value into a variable that is a double (which would work) because they assume it is an int. That will give them unexpected results later when they expect a whole number and get back a double.
      As for your arguments, I don't disagree with anything you said. I personally like using var. However, there are quite a few things I do to limit myself in order to make my code more accessible.

    • @hvbsalmarm
      @hvbsalmarm Před 6 lety

      Yes, I agree that it is less compelling to use var for the basic types. My reasoning would require type casting to make the type visible. However, when transferring the contents of a variable into say a temp variable for whatever nefarious reasons you may have, I would use var specifically because that way again you would not have to worry if you subtly changed the original's datatype.
      As for extremely new developer's I do agree that var should be learned later on. Get them familiar with the types themselves before they learn shortcuts, but definitely do eventually teach how to properly use things like var and why it's important. That said, when I am hiring developers I won't hire someone that does not have enough experience or talent. I am willing for us to put some time in on a new guy to bring them up to speed, but neither my other developers or I have the bandwidth to bring a rookie that far along. Junior programmers are one thing, but we can't teach a person from scratch.

  • @rubeushagrid4131
    @rubeushagrid4131 Před 2 lety +2

    Very good content. 👍🏻

  • @Dotnetexplorer
    @Dotnetexplorer Před 3 lety +2

    Very usefull really i got

  • @arturoordonez-hernandez1534

    We can say that C#'s var keyword is analogous to C++'s auto keyword? One good use case I can think of for var is if we have a type name that's hard to type out because it requires chaining quite a few nested namespaces and then a class name or something. Dynamic is best for working on a system requiring communication with different systems? At that point, one could even just return a JSON object (if possible) and parse that using C#'s Newtonsoft.JSON library to a custom defined C# class instance (or an anonymous var). The only other use I can think of for dynamic is that it's a bit tricky to pull individual properties from an object type, and dynamic is a bit easier to work with in that regard.

  • @JuiceBan
    @JuiceBan Před 6 lety +2

    Hi Tim! I'm just curious, do you plan to cover Reflection and Serialization themes in some of your videos in the near future?
    P.S.: Thank you very much for the amazing channel. I really love your way of presenting the information. You are a really great Teacher.

    • @IAmTimCorey
      @IAmTimCorey  Před 6 lety

      They aren't high on my list but they are on the list. I'll make a note that there is a bit more interest in them. The more interest there is in a topic, the higher it goes on the list (unless I override the list for something I think is important).

    • @JuiceBan
      @JuiceBan Před 6 lety

      Thanks for the answer! I got it.

  • @josephmills1104
    @josephmills1104 Před 3 lety +1

    I think (with limited knowledge and experience) that using var seems to be the most clear and concise way of initializing a variable in C#. With a good name and a peek to the right of the assignment statement you should know exactly what you're dealing with.

  • @michaeltkachenko7313
    @michaeltkachenko7313 Před 2 lety

    Well, I agree with Microsoft code style for using var, it should be obvious what type you are using in case of choosing var, and if the type is not straightforwardly indicated, then var is not the best option.

  • @klightspeed
    @klightspeed Před 5 lety +2

    I pretty much have only used dynamic when e.g. enumerating the values in something like a JObject or JArray where the type is not known beforehand. Note also that you can't call extension methods (e.g. linq methods) on dynamic types, since they are resolved to static methods at compile time. Instead you need to directly call those static methods on the object.

  • @sajjadmohammed7452
    @sajjadmohammed7452 Před 6 lety

    Thank you for sharing your infos with us. Your tutorials is very useful and explanation is awesome. May I ask what software used to record this tutorial?

    • @IAmTimCorey
      @IAmTimCorey  Před 6 lety

      I use Camtasia to record the video and then I export the video to Audacity for noise removal and amplification (I normalize the audio to a set level - it is usually better to record a bit quieter and raise the volume vs. recording at the higher volume (less background noise gets picked up). I then put the produced audio into Camtasia and produce the videos.
      Camtasia isn't free or especially cheap but it is the best screen recording software I have found for the PC. Audacity is free, which is nice. I used to be able to do it all in Camtasia but the latest update messed up the noise removal algorithm so I sound under water if I use it. It is still really useful software.
      Does that answer your question?

  • @EnsYlmaz51
    @EnsYlmaz51 Před 3 lety

    awesome video

  • @AzizjanAyupov_leo
    @AzizjanAyupov_leo Před 3 lety +2

    I am your fan!

  • @joku2765
    @joku2765 Před 3 lety

    What do think about the class DynamicObject? When should it be used?

  • @randyriegel8553
    @randyriegel8553 Před 4 lety +2

    I've probably only used dynamic a few times on certain edge cases from API's. I always use 'var' for objects instead of typing "HttpClient client = new HttpClient();" it's easy to read "var client = new HttpClient();". Lots of times I use int, string, double, etc... in front of just common variable names.

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety +4

      The key is to be consistent and understandable.

  • @davemarblehead3334
    @davemarblehead3334 Před 2 lety

    What about algorithms. The shape of a collection an the type of it elements are often depend prior results. At Rosetta Code there are many examples where strongly type languages are difficult to understand. Often the implications of the task in a strongly typed languages do not solve the problem as stated.

  • @mutayyab01
    @mutayyab01 Před rokem +2

    Can you tell the difference between asp.net core & asp.net & asp.net mvc a Totorial on that 🥺❤️

  • @Shinika01
    @Shinika01 Před 7 lety

    Hello Tim.
    Your content is Really Awesome. You explain pretty well your subjects, and you cover technical points that we don't see that often in lessons. Thank you for that !
    That said, I can't watch many of your videos. Because you talk too slow. It is surely a great advantage for some people that have troubble with english (and i do have some when writting in english, i am from belgium), but seriously, some videos could be 1/4 to 1/3 shorter if you would talk at a normal speed.
    Wich is pretty annoying for me! I would love to follow more lessons from you, but i really can't handle the mistery on every words ^^
    That said, you're great and you do a great job!
    BTW, We have a Tournament Tracker in C# MVVM that we are doing this week! So i might give a shot to your lessons for some advices now that my Repositories and Models are in place!
    The video i watched 3 times is the basics ASP MVC video you made ;) thank you so much for it!

    • @IAmTimCorey
      @IAmTimCorey  Před 7 lety +1

      Yeah, I know I talk slow. A big part of that has nothing to do with the audience. I have a really hard time talking, thinking, and typing at the same time. If I just type and think (without talking), I can go about 50% faster, maybe twice as fast. I've tried going faster but doing so is HARD. It ends up making a 1 hour video take about 5 hours to produce since I have to cut out so much. I could speed up the videos during post-production but, like you said, that would hinder my (large) international audience.
      Fortunately, there is a solution. CZcams has a feature where you can speed up a video. Just set my speed to 1.2 or so (1.5 if you are feeling adventurous) and enjoy. I hope that helps.

  • @tgsoon2002
    @tgsoon2002 Před 7 lety

    This is interesting. I never heard of dynamic before, can you let me know which versions of C# does dynamic was introduced?

    • @IAmTimCorey
      @IAmTimCorey  Před 7 lety +1

      It was introduced with C# 4.0 (Visual Studio 2010).

  • @carstenberggreen7509
    @carstenberggreen7509 Před 2 lety

    Interesting with Dynamic ... feels like old ActionScript's way of handling code issues runtime. As a C# developer (comming from 6502/680x0 assembler, Pascal and C/C++) I really dont like a compiled language to use "dynamic types" in my code. Its nice its there, but I dont think I will use it much. Var on the otherhand, I use all the time. I love the fact that I can write readable methods where I dont clutter the meaning with long irellevant variable types/models/classes. I prefere naming of variables to be good.

  • @zuhairabdulla5002
    @zuhairabdulla5002 Před 3 lety +2

    dynamic can be very helpful in rapid prototyping. instead of defining dto you can just use dynamic "if you are calling an api for example"

  • @ernstpeterlegrand
    @ernstpeterlegrand Před 4 lety

    Maybe one suggestion although it might come in coming videos. you mention all kind of things that you probably never run into. For me this dynamic thing will probably not happen (soon). It would be nice to have somehow an overview of general appoach. So not the special things. I am not sure yet how that should be arranged in a video though. I might come back to that at some stage as I make notes during your videos with some "take aways".

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety +1

      Basically, dynamic should be rarely used. The key is to know the difference in the terms. Var and Dynamic are totally different concepts. Var can be used a LOT but there is limited use cases for Dynamic.

  • @b0570nk4
    @b0570nk4 Před 5 lety +3

    Another case when you should not use the var keyword is in case of relying on polymorphism - like IMyInterface instance = new MyConcretion();...

  • @ernstpeterlegrand
    @ernstpeterlegrand Před 4 lety

    Thanks again. Just one question, when would you use Anonymous objects?

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety

      There are a number of situations. The most common is when you want to create a quick object to send to a method that is expecting a generic object (but not specifying the type). For instance, Dapper's parameter can be any type of object. I use an anonymous class for that quite a bit. Also, performing a LINQ query and getting the results is another time.

  • @akshayrajgollahalli
    @akshayrajgollahalli Před 3 lety +1

    Can you talk about 'using' keyword in one of your upcoming videos? Thanks.

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety +2

      I can add it to the suggestion list.

  • @KouroushMetal
    @KouroushMetal Před 5 lety

    I use mostly var but one things that come to me often, when set the result of var into an object. if u change the type of class, the visual studio don't run any error. but if u strongly type item, it run the error.

    • @IAmTimCorey
      @IAmTimCorey  Před 5 lety +2

      Yep, that will bite you but I agree that var is nice and easy.

  • @lukenukem8028
    @lukenukem8028 Před 4 lety

    Just one question about JavaScript since you now mentioned it.
    You can set a var type. { var i : int; } So, does setting that var type lock it to that type?

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety +2

      In JavaScript? Var is always changeable (type included). You would want to use let or const for locked in types (or as close a JS gets - you can still manipulate them). In C#, var is always strongly typed so the type can never change.

  • @sagarviradiya
    @sagarviradiya Před 4 lety +3

    can you please have video for static vs readonly?

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety +2

      I will add it to the list. Thanks for the suggestion.

  • @chefbennyj
    @chefbennyj Před 4 lety +1

    This actually might fix an issue I was having, where I needed to have a void parameter which was a list of T, but I wanted to send in different list types without having to have a second parameter for each list of T. I could possible use a List and send in what ever object type I want. Right??
    EDIT: no it looks like you can't do that with dynamic. You can't use List, it is just dynamic.

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety

      I'm not sure why T doesn't help you. The T in List can change depending on what you need.

    • @chefbennyj
      @chefbennyj Před 4 lety

      @@IAmTimCorey wow, cool thanks for the message. It is true I could use list T, however I was hoping to pass two different list of T from an API response (List or List) into a function. Both BaseItem and SessionInfo contain some of the same properties, which I was hoping to use generically. My hope was to try and limit the amount of parameters being passed to the function. Not have List sessionInfos = null, List baseItems = null. Resharper yells at me if I try and pass to many arguments. I think it violates a coding principal. Most likely "single responsibility"... I didn't want to repeat code, but inorder to keep it all readable and not odd (it's in GitHub so someone might read it one day...) I decided to split up the function and repeat the code, once for the BaseItem response and again for SessionInfo.

  • @mrcoffee7283
    @mrcoffee7283 Před 2 lety +1

    For me is var a good choice cuz I don’t have to repeat myself. DRY is an important rule. Variable names should always self-explanation, no matter if you var or other types.

  • @maheshvaleti4366
    @maheshvaleti4366 Před 2 lety

    Good

  • @findotnet
    @findotnet Před 2 lety +1

    Dynamic essentially bypasses static type checking

  • @wdolek
    @wdolek Před 6 lety

    We are using `dynamic` when working with types generated at run-time (from edmx). I advice anyone - do not use `dynamic` if you really don't need to. Even for our case, it's possible to trickle things by either reflection and generics or generating classes at compile time, adding some wrappers for run-time generated types. But dynamic is the most straightforward thing we can do... unfortunately.
    Anyway, here is reference for `var` and `dynamic`:
    docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/dynamic
    docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var
    + docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables
    ... I wouldn't really expect anyone to mix these things together. I consider `var` as syntax sugar which is resolved by compiler so programmer can type less :)

    • @IAmTimCorey
      @IAmTimCorey  Před 6 lety

      Yep, they are totally different things. The fact that they do get mixed up is why I created the video. Thanks for the personal experience.

  • @cr113
    @cr113 Před 5 lety

    My friend just saw a video which I think he said was made by some of the Microsoft C# design team. He said they were recommending to use var all the time. If the trend is to use var all the time does that kinda make C# obsolete? Wouldn't it be better to use a language that was designed from the ground up to use dynamic typing? Is that why Python is becoming so popular?

    • @IAmTimCorey
      @IAmTimCorey  Před 5 lety +1

      No, that's one of the things I touched on in this video. Var in C# does not mean "any type you want whenever you want". It is just shorthand. It determines the actual type when you create the variable (so "var test = "Tim"" would mean that test is a string type). Var is not dynamic typing. There is the dynamic keyword, which is dynamic, but that is only used in limited situations. C# is strongly-typed and always will be.

    • @cr113
      @cr113 Před 5 lety +1

      @@IAmTimCorey Yup, I should've payed attention. I felt pretty dumb when I found that out. :) Also I noticed that it won't let you use var as a parameter, I'm assuming because the compiler has no idea what type can get passed in.

  • @asdasddas100
    @asdasddas100 Před 7 lety +1

    Have you ever used the dynamic keyword in production?

    • @IAmTimCorey
      @IAmTimCorey  Před 7 lety +2

      Not often, but yes. I used it a couple times for talking to COM assemblies but that was just a small application. Another time I used it when I was writing a really funky library where I didn't know the output type but wanted something more than object. That was one of those "don't try this at home" projects. It did the job, but it really was off the beaten path of "normal" programs. Off the top of my head, those are the times I can think of. I probably used it a few more times (I've written hundreds of programs professionally) but it really is rare. In the case of the second example, now I could use either generics or I could return a JSON string. Either would probably be a better option now. Back then, though, dynamic was probably the best choice.

  • @vinuhosanagar1
    @vinuhosanagar1 Před 7 lety +1

    Thank you sir. What do you expect from a 2 year experienced dot net developer into WPF if you were the one who is interviewing? It helps me to make preparation for the interview.

    • @IAmTimCorey
      @IAmTimCorey  Před 7 lety +6

      The first thing I want to see is some type of provable experience. 2 years isn't a ton, but it is significant enough that you should have something you can talk about. I'd ask you to tell me about the projects you worked on and I would want to know more than what they did. I'd want to know what your part was and how you accomplished it. I'd also want to see code that you have written. You probably cannot/should not show off code from a previous employer (at least without permission) but a side project or two would do. When an employer posts the number of years experience, that is just a way to quantify skill. When they interview, they are less concerned about the years and more concerned about what you did in those years. I'd have an application or a part of an application on hand to show off (maybe print off a couple of pages of relevant code and have the full project on a USB drive). Show that you know OOP (at least make use of class instances, but showing off interfaces, inheritance, and extension methods would be good), name things well, and that you know how to write readable code (don't make it a dense mess). The next thing I'd look for is how you explain your code. Do you understand what it is doing or did you just copy it from the Internet and hope it worked? Do you know why you should use one technique over another? For instance, if you have an if/else if/else block in your code, I would ask why you didn't use a switch statement. You should know the benefits of one over the other in a given situation.

    • @vinuhosanagar1
      @vinuhosanagar1 Před 7 lety +2

      Thank you for detailed explanation sir...

    • @torrvic1156
      @torrvic1156 Před 4 měsíci

      @@IAmTimCoreythank you! That was very useful for me also.

  • @joystanrolan495
    @joystanrolan495 Před 3 lety +3

    When we override dynamics does it erase the old copy in memory?

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety +5

      It depends on what you mean. It creates a new location in memory for the new dynamic object. That disconnects the old object from use, which marks it to be ready for garbage collection. It stays in memory until the garbage collector (GC) cleans it up. This doesn't happen until the memory is needed (memory pressure builds, the GC runs - I'm GREATLY simplifying here). That means it may be gone from memory right away or it might take a few minutes. Either way, though, your application no longer has access to the old dynamic object.

    • @joystanrolan495
      @joystanrolan495 Před 3 lety +1

      @@IAmTimCorey so I understand they are mutable in nature. Thank you 👍

  • @kaustavchakraborty3244

    dynamic can be very useful in generics if used with proper intent.

  • @Cmppayne26542
    @Cmppayne26542 Před 6 lety +1

    Microsoft coding standards wants people to use var instead of explicit typing for most variables docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions. But I get what you mean on explicit typing, sometimes its better to just always use it, I like explicit typing as visual studio will suggest names based off the type where it does not with var.

    • @IAmTimCorey
      @IAmTimCorey  Před 6 lety +4

      Yep, and this is where I will deviate from Microsoft a bit (there is a big group in MS that is anti-var as well). One of the dangers of being a programmer with a lot of experience is that you start to forget that anyone has less knowledge than you. You start saying things like "everybody knows that..." That is a problem. It makes it hard for new developers to join the team. That barrier actually makes it more difficult on the senior developers because they are relied on so much more because no one else is good enough to help them out. It is a problem of their own making. I see var is a part of this problem. One of the common arguments for var is that "you should know what they type is". Sigh. But what if you don't? Should you stop being a programmer? No! That just means you don't have as much experience as the developer who wrote the software. Do you know how you get experience? By doing the job. So the easier we make it for junior developers, the faster they become senior developers. Sure, in the grand scheme of things, var is not a big deal but it is one more bump we put in the road and in the end, it hurts all of us. Sorry, a bit of a rant there, but I am passionate about helping newer developers become better developers.

    • @Cmppayne26542
      @Cmppayne26542 Před 6 lety +1

      IAmTimCorey While I get what you mean, how often does new developers come into a project with that little of experience? I have self taught myself in about 3 months and can do MVVM and Asynchronous Programming but I am just not sure when I can be considered knowledgeable enough to actually apply to jobs. I mean when I hear people struggle on finding the type returned from a var confusing it just makes me wonder how exactly advanced I am considered for a new developer... especially considering that Visual Studio will tell you the type of the object if you place your mouse over it.

    • @IAmTimCorey
      @IAmTimCorey  Před 6 lety +2

      The issue isn't that they don't know how var works or how to find the actual type. The issue is that they haven't used C# enough to know what type would be used in every situation without slowing down to think about it. For example, just by looking at the code (on paper), they wouldn't be able tell why this code wouldn't work:
      checkingAccountBalance *= 2.5;
      Even worse, they might make a change to the code like so and it would work:
      checkingAccountBalance *= 2;
      And they wouldn't know why. Above they would see that checkingAccountBalance is a var type, which wouldn't help. They would need to have it open in Visual Studio to see that checkingAccountBalance is a decimal (because money should always be stored in type decimal, not double) and 2.5 is a double (2.5M would be a decimal).
      Another example might be that they start using var too. They like how you don't need to specify types, just put data into it. They want to do the above example so they write the following code:
      var checkingAccountBalance = 150.05;
      See the problem? They just created a double, not a decimal. They won't know that until they mouse over it (if they do). They might actually launch the application into production with that little flaw.
      It usually isn't the big stuff that trips up newer developers. It is the small stuff that is easily overlooked. That is why I do everything I can to eliminate situations that are common small-problem areas.

  • @mmuneebajaz
    @mmuneebajaz Před 6 lety

    HI , sorry this is not related to video !!
    can we access specific method that are subscribed to delegate?
    like m1,m2,m3 are assigned to delegate but i only want to call m2

    • @IAmTimCorey
      @IAmTimCorey  Před 6 lety +1

      Each instance of the delegate would be callable, so it depends on your design. You would have to have some way of indicating which delegate you wanted to call. Bottom line is that yes, there is a way but it is a bit more complicated and it would involve a bit of code to support the delegate call.

    • @mmuneebajaz
      @mmuneebajaz Před 6 lety

      sorry for bugging you but got one more question :
      var person = new { FirstName = "FN", LastName = "LN"};
      this is gonna create a new Type ? is there any way to create methods in that class too , it only allows to make fields

    • @IAmTimCorey
      @IAmTimCorey  Před 6 lety +2

      Anonymous types hold read-only properties so no you can't. You can play around with delegates, etc. but that smells of a design problem. By the way, here is the documentation for anonymous types, where it talks about the limitations: docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types

    • @mmuneebajaz
      @mmuneebajaz Před 6 lety

      ok !! thankyou very much sir

  • @user-iu1cg7hg3f
    @user-iu1cg7hg3f Před 5 lety +1

    What's the difference between dynamic and Object except after the dynamic you can call anything in write time.

    • @IAmTimCorey
      @IAmTimCorey  Před 5 lety +3

      They are treated differently by the compiler. For instance, you cannot say person.FirstName if person is an object because C# does not know about the FirstName property. However, if person was dynamic, this would work (at least until runtime - if the FirstName property really does not exist, it will cause an exception). The accepted answer on this question might better explain it: stackoverflow.com/questions/5523031/dynamic-keyword-vs-object-data-type

    • @user-iu1cg7hg3f
      @user-iu1cg7hg3f Před 5 lety

      ​@@IAmTimCorey I think I kinda understand this. need to do more reading. A lot of thanks.

  • @codingwithgyver1637
    @codingwithgyver1637 Před 3 lety

    seems dynamic requires more work than var due to resolving its method name in loaded assembly. If this is tru, it is not really recommended to use dynamic if your app has a part of critical-operations

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety +1

      I cover that in this video but yes, avoid dynamic if you can. If you cannot, it is a great option to have available.

  • @hamzarashid7579
    @hamzarashid7579 Před 3 lety

    Please explain the Dynamic and Object keywords.

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety +3

      I explained Dynamic in this video. Object is the parent to all other objects. Think of object as the lowest common denominator. The thing that (practically) everything has in common (which is basically ToString and GetHashCode).

  • @anilaxsus6376
    @anilaxsus6376 Před 5 lety

    is it possible to reference a class in a project that is deployed on a separate computer?

    • @IAmTimCorey
      @IAmTimCorey  Před 5 lety +2

      Technically yes, but in practice, no. We keep the dlls close to the exe so that the application doesn't break when the network has a glitch.

    • @anilaxsus6376
      @anilaxsus6376 Před 5 lety

      @@IAmTimCorey Thanks, by the way can you tell me what words to type in the search box so that I can watch tutorials about implementing this cross computer type of reference please.

    • @IAmTimCorey
      @IAmTimCorey  Před 5 lety +2

      Not really, sorry. You will have to do a lot of digging. Essentially you would need to get pretty deep in the build process definition and modifying that.

    • @anilaxsus6376
      @anilaxsus6376 Před 5 lety

      @@IAmTimCorey Alright, Thanks

    • @torrvic1156
      @torrvic1156 Před 4 měsíci

      Maybe you need a sort of microservices with SAGA pattern? Who knows…

  • @boyettt
    @boyettt Před 2 lety +1

    does the dynamic skip the compile time?

    • @IAmTimCorey
      @IAmTimCorey  Před 2 lety +1

      It is not strongly-typed at compile time if that is what you mean.

  • @Joe-ho6fo
    @Joe-ho6fo Před 3 lety

    I use car in line queries and for each,almost never otherwise. Now that I understand dynamics I’ll never use them.

  • @munkhn73
    @munkhn73 Před 4 lety +1

    I thought ‘var’ was lazy man’s choice of type declaration. But using it on anonymous object is kinda makes sense. Lately seems like MS too, wants programmers to avoid using ‘var’, cuz VS 2019 silently yells at the ‘var’ declarations.

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety +3

      var is really useful and it cuts down on typing sometimes. The objects always tell you what they are when you hover over them, so that isn't an issue. The issue is more when you read code without mousing over everything if you are a newer developer. However, the reason var was created (at least a big part of it) was because of LINQ statements and anonymous objects. As for the warning about var, that is a setting you get to choose. You can have it yell about var or about variables that don't use var. It is up to you.

  • @depepon
    @depepon Před 7 lety

    Sue Storm

    • @IAmTimCorey
      @IAmTimCorey  Před 7 lety +1

      Yeah, not sure how often people get that. One of my Easter Eggs, if you could call it that. It is an easy name and more interesting than John Doe. I taught a class once in college where, for one 3-hour session, I used nothing but Lord of the Rings names for sample names. That was a challenge.

    • @depepon
      @depepon Před 7 lety +1

      hahaha funny! love your content man, Greetings from Argentina. Keep it up!

  • @Err0rCraft
    @Err0rCraft Před 3 lety +5

    6:48 Python in a nutshell lol

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety +1

      :)

    • @RagingWhoremoans
      @RagingWhoremoans Před 3 lety

      It's been nearly 2 weeks since I started learning C#, and I'm already starting to miss Python.

  • @TheBausahab
    @TheBausahab Před 3 lety

    @6:00 to 6:10
    he he he.. OK got it sir...

  • @mis0025033
    @mis0025033 Před 2 lety +2

    I simply use "var" when I don't figure out the type of the target object.🤣

    • @IAmTimCorey
      @IAmTimCorey  Před 2 lety +3

      That works. Then you can mouse over it and see the type.

  • @kylegivler8372
    @kylegivler8372 Před 3 lety

    I use both var and the full name of the type, seemingly randomly.

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety +1

      Consistency helps with reducing bugs.

    • @michaelschneider603
      @michaelschneider603 Před 2 lety

      Consistency also helps with getting along with your colleagues. :-)

  • @lukenukem8028
    @lukenukem8028 Před 4 lety +1

    That's interesting.
    dynamic is like writing JavaScript. LoL I've always hated JS for it's looseness.
    The benefit, and perhaps intended usage of dynamic, is that you can write a Library that assumes members of a host Application.
    It is like extending abstract classes, but without IDE help. It's even more abstract than abstract. LoL
    So it would require you to have a type that has a member of name.
    And it would be annoying to debug if you don't have the source, like, table flipping annoying.

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety +1

      Yeah, there are only specific cases where dynamic is the right choice. It is valuable to have, especially when working with 3rd party systems, so that you can integrate but it isn't something to be using daily.

  • @thfreakinacage
    @thfreakinacage Před 4 lety +3

    I have to disagree with the "var" guys. Using "string" is MORE self-documenting friendly as it makes it blindingly obvious what the type is. Their argument supports non-var guys. And their point of "well you can mouse over the variable", yeah, but I don't want to! That means moving my hand off my keyboard and to my mouse, move around the screen, and wait for the tooltip. Instead, I'd rather just move my eye a tiny amount and save quite a bit of time once you do it a lot.

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety +3

      Yep, there is definitely a strong case for not using var.

    • @thfreakinacage
      @thfreakinacage Před 4 lety

      @@IAmTimCorey I genuinely was not expecting you yourself to reply here! Awesome. Well, while I'm here I want to say a huge thanks for this content. I used to work a C# ASP job before, but it's been a few years and I've been a front end/reactjs guy since, but recently I've been applying for C# jobs again and these videos have been awesome refresher courses for me. Thanks again and keep up the great work! :D

    • @thfreakinacage
      @thfreakinacage Před 3 lety

      @Soy Orbison I don't know, I've been a contractor for the last few years and when every 6 months you dive into a brand new code base that's completely unfamiliar and you need to learn how it's set up very quickly, having those explicit declarations helps a lot.

  • @mattizzle81
    @mattizzle81 Před 4 lety

    So using dynamic on *everything* turns your C# into Python, and using it comes at great cost. Why is Python so great again? ;)

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety +3

      It definitely has its place in the world but it is also very different.

    • @mattizzle81
      @mattizzle81 Před 3 lety

      @Soy Orbison To be fair I have seen the benefits of Python in certain situations.
      It is a much more "exploratory" way of programming, good for quick scripts that use OpenCV or Pytorch for ML, but otherwise I agree it just feels messy.

  • @wuketuke6601
    @wuketuke6601 Před 11 měsíci

    I used to write var when i had some long tulpes, until i realised that thats a horrible idea haha (im just creating structs now)

    • @IAmTimCorey
      @IAmTimCorey  Před 11 měsíci +1

      I’m glad the video was helpful.

  • @strandloper
    @strandloper Před 6 lety +2

    I think you've made a mistake in this video by comparing dynamic and var as if they are different data types, which I think may confuse beginners. You describe var as a static data type that assumes the type it is assigned, but in reality var is not a data type at all, but a keyword or shorthand that means "I know the compiler knows what data type this is so I'm not going to explicitly write out the data type here." Besides that it's a good video.

    • @IAmTimCorey
      @IAmTimCorey  Před 6 lety +2

      I see what you are saying. The reason I did the comparison in this video, though, is because beginners (and not-so-beginners) were thinking the two were the same. They were making the comparison. I probably should have been clearer when I said var is a type. The variable that is assigned to var is a static type. I do believe I emphasized that it becomes a string or an int.

    • @strandloper
      @strandloper Před 6 lety +1

      You did say that; the only thing really unclear is that the assignment of the static type to a var happens at compile time, not at run time. Whether beginners need to worry about that is debatable.

  • @juang_
    @juang_ Před rokem +1

    Python be like:

    • @wuketuke6601
      @wuketuke6601 Před 11 měsíci +1

      I absolutely despise python for specifically this reason

  • @petrusion2827
    @petrusion2827 Před 4 lety

    (After 8 minutes of watching) Oh so this dynamic thing is a way to turn C# into Python? Hard pass!
    (Some time later) You can make dynamic methods? That must be hell to work with. I'm a just a student, but I bet this keyword is prohibited in most programming jobs.

    • @IAmTimCorey
      @IAmTimCorey  Před 4 lety

      No, it just needs to be used in the correct context. Most good things in software development have a way you can use them poorly. The key is to use the power you have responsibly. In the past year, I have used dynamic probably a dozen times. Each time, it was the best solution for the situation.

    • @SebGruch
      @SebGruch Před 4 lety

      @@IAmTimCorey Yep - on the other hand, in the years since this keyword was introduced I'd never even felt the temptation to use it ;-) Just matter of different problems and domains we all happen to work in, I guess.
      Or I'm so bound to my interfaces that I can't even start thinking about other solution ;-)