How To Create Generics in C#, Including New Features

แชร์
ฝัง
  • เผยแพร่เมื่อ 21 ม.ค. 2024
  • Ever since Microsoft introduced generics into the language, they have been used almost everywhere. Even if you don't understand how they work, using generics is rather easy.
    In this video, we are going to look at why generics are important and then how to create them. We will look at the different types of generics, how to limit generics, and how to implement some of the more recent generic types, such as generic interfaces and numeric generics.
    Full Training Courses: IAmTimCorey.com
    Source Code: leadmagnets.app/?Resource=Cre...
    Mailing List: signup.iamtimcorey.com/

ความคิดเห็น • 95

  • @biokode
    @biokode 6 หลายเดือนก่อน +6

    It would be so interesting to see a "real world" scenario with interfaces of generic types being implemented, love this stuff

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน +1

      Watch any of my videos where I do data access to SQL. I use generics when working with Dapper to make things cleaner.

  • @leppyr64
    @leppyr64 6 หลายเดือนก่อน +2

    Fantastic timing. I'm just trying to break down an existing Generic class to figure out how and why it's being used.

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน +1

      Excellent!

  • @astralpowers
    @astralpowers 6 หลายเดือนก่อน +1

    I love the trick in generics where you use constraint the type to the current class e.g. `BaseClass where T : BaseClass`. It looked weird at first, even now it is still weird, but is very useful so that the base class can get the type of the derived class. This mechanism is used in heavily in generic maths.

    • @runtimmytimer
      @runtimmytimer 6 หลายเดือนก่อน +1

      It is useful. I used this in a data access layer with some LINQ. The constraint allows you to access properties of the base class in LINQ which can be very powerful.

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      Thanks for sharing!

    • @jackbunbury6417
      @jackbunbury6417 6 หลายเดือนก่อน

      How can I learn more on this pattern? Does MS use it in any of its LINQ libraries? My Googling didn't turn up an examples. Can you point to a place to learn more?

    • @astralpowers
      @astralpowers 6 หลายเดือนก่อน +1

      @@jackbunbury6417 the dark side to Roslyn is the pathway to many coding styles some consider to be unnatural

  • @vibes992000
    @vibes992000 6 หลายเดือนก่อน

    Your last few mins of video were excellent, I somehow forgot the importance of `where`. Thanks a lot.

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      You are welcome!

  • @efimov90
    @efimov90 6 หลายเดือนก่อน +1

    IAmTimCorey, this is very great video covering all the basics of generics. Unfortunately, I didn't learn anything new. I will definitely recommend it to my friends who don't understand this topic yet. Can you please make a video with more advanced things like and maybe Monad-like classes with embeded logic and conversion?

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @runtimmytimer
    @runtimmytimer 6 หลายเดือนก่อน +6

    To date my experience, I was so happy when generics were added to c#. I came from c++ and it was frustrating not having a template equivalent.

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      Great!

    • @markleistner1924
      @markleistner1924 6 หลายเดือนก่อน

      For sure. All the boxing and unboxing from object that used to be required.
      Still my favorite feature all these years later, if only so I don’t have to deal with boxing.

  • @andergarcia1115
    @andergarcia1115 6 หลายเดือนก่อน +1

    Your knowledge is truly inspiring. The amount i gained from your video is incredible.

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      Thank you!

  • @trudyreiser8075
    @trudyreiser8075 หลายเดือนก่อน

    Very helpful! Thanks for doing what you do🙌🏻

    • @IAmTimCorey
      @IAmTimCorey  หลายเดือนก่อน

      You are welcome.

  • @austinmudadi9178
    @austinmudadi9178 5 หลายเดือนก่อน +1

    Tim, the best as always. This is a masterpiece!

    • @IAmTimCorey
      @IAmTimCorey  5 หลายเดือนก่อน

      Thank you.

  • @michaelglockenmeier906
    @michaelglockenmeier906 5 หลายเดือนก่อน

    always a pleasure watching your videos while doing some cardio training like right now :-)

  • @andywalter7426
    @andywalter7426 5 หลายเดือนก่อน

    I actually had one case where I started out with interfaces but had to change to using generics that implemented the interface. The reason was sometimes whoever uses it needs to know the full type with all methods, not just what the interface used and worked out great.

  • @SagharMax
    @SagharMax 6 หลายเดือนก่อน

    It was a complete explanation of using Generics in C#. Thank you so much.

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      You are welcome.

    • @mbpoblet
      @mbpoblet 4 หลายเดือนก่อน

      Not _completely_ complete... he didn't get into covariance and contravariance...

  • @bturner484
    @bturner484 6 หลายเดือนก่อน

    This really helps! I appreciate your channel

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      I'm so glad!

  • @mohammedbadran7840
    @mohammedbadran7840 6 หลายเดือนก่อน

    Thanks a lot for your efforts , great topic

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      You are welcome.

  • @user-kt7nd6pg1p3
    @user-kt7nd6pg1p3 6 หลายเดือนก่อน +1

    Thanks for your effort! :) Best Regards

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      You are welcome.

  • @vincenzoriwu2998
    @vincenzoriwu2998 6 หลายเดือนก่อน

    Great Content Tim !

  • @begumyaprak755
    @begumyaprak755 5 หลายเดือนก่อน

    Perfect explanation, thanks!

    • @IAmTimCorey
      @IAmTimCorey  5 หลายเดือนก่อน +1

      You are welcome.

  • @acerreteq703
    @acerreteq703 4 หลายเดือนก่อน

    Hi Tim, thank you very much. Good explanations but i´m missing a lot of stuff. How to declare a method that returns a value of ? How to deal with type conversion inside a method if e.g. math operations lead to "can´t implicit convert from int to or vice versa. Definitely needs a part 2. 🖖

  • @bdowns
    @bdowns 3 หลายเดือนก่อน

    Thanks Mr. Corey

    • @IAmTimCorey
      @IAmTimCorey  3 หลายเดือนก่อน

      You are welcome.

  • @hmihaela2310
    @hmihaela2310 2 หลายเดือนก่อน

    Extraordinary explanation!!

    • @IAmTimCorey
      @IAmTimCorey  2 หลายเดือนก่อน

      Thank you!

  • @BertONeill
    @BertONeill 4 หลายเดือนก่อน

    Excellent tutorial

    • @IAmTimCorey
      @IAmTimCorey  4 หลายเดือนก่อน

      Thank you!

  • @cemkaya4448
    @cemkaya4448 5 หลายเดือนก่อน

    Thanks for the video, great content as always! I tried it out for the efficiency problem of different types in list and got slightly different results than expected. Here are the times in milliseconds for adding elements:
    List elapsed time: 36
    List elapsed time: 33
    I didn't see as big a difference between the two lists as you did. Could Visual Studio Code or operation system be causing this difference?

    • @IAmTimCorey
      @IAmTimCorey  5 หลายเดือนก่อน +1

      I would check your code. There might be something different. You will always get different numbers from someone else because it is based upon the PC hardware. However, I don't believe they will be that close to each other. Not unless something else is different.

    • @cemkaya4448
      @cemkaya4448 5 หลายเดือนก่อน

      @@IAmTimCorey
      List numbers = [1, 2, 3, 4];
      List objects = ["Tim", 4, 3.6];
      // Count for objects.
      Stopwatch sw = new();
      sw.Start();
      for (int i = 0; i < 1_000_000; i++)
      {
      objects.Add(i);
      }
      sw.Stop();
      WriteLine($"List elapsed time: {sw.ElapsedMilliseconds}");
      // Count for numbers.
      Stopwatch sw1 = new();
      sw1.Start();
      for (int i = 0; i < 1_000_000; i++)
      {
      numbers.Add(i);
      }
      sw1.Stop();
      WriteLine($"List elapsed time: {sw1.ElapsedMilliseconds}");
      That's the code snippet, thanks. I might be missing something here. The current results are still showing a smaller difference than expected:
      ---------------------------------------------
      List elapsed time: 40
      List elapsed time: 36
      --------------------------------------------
      If I use the stopwatch instance (sw) for the list of integers as you demonstrated, the difference actually increases in favor of the List.
      By the way, I'm using VS Code in M1 Mac Pro. If there is another way, I can share the picture of it.

    • @cemkaya4448
      @cemkaya4448 5 หลายเดือนก่อน

      Interesting! After running the test a few more times, I'm seeing some variability in the results:
      ---------------------------------------------
      List elapsed time: 36
      List elapsed time: 18
      --------------------------------------------
      Looks like not consistent result. Anyway never mind me, Tim. I'm a person just trying to understand the logic. Thank you!

  • @Dimitris.Christoforidis
    @Dimitris.Christoforidis 5 หลายเดือนก่อน

    Thank you Tim once again!! Very powerful videos, knowledge is the key in development! My question is can i pass Generics inside a controller for aspnet core?

    • @IAmTimCorey
      @IAmTimCorey  5 หลายเดือนก่อน +1

      You can use generics anywhere in C#. Now if you are asking if you can use a generic as an input parameter on a controller (something passed in from the user), I believe you technically can, but it can get messy in a hurry. I would recommend against it unless you have a really good reason.

  • @gani7485
    @gani7485 6 หลายเดือนก่อน

    Thanks its easy easy to understand.
    How can I limit different types for both T and U?
    Sampleclass where T:new()
    here How can I say U:int

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน +1

      public class SampleClass
      where T : new()
      where U : int
      {
      ...
      }

  • @laci-ht9cm
    @laci-ht9cm 6 หลายเดือนก่อน

    Hi Tim Corey!
    I am a new subscriber to your channel, thanks to this video about Generics. Sorry if this question is repetitive, but I was unable to find how can I configurate Visual Strudio 2022 to colorize the code like this. Do you have a video for it?

    • @IAmTimCorey
      @IAmTimCorey  5 หลายเดือนก่อน

      Here is a video on how to turn on colorized braces: th-cam.com/video/O1GUbjacjKQ/w-d-xo.htmlsi=J4HQhYP2sWZPejuD

  • @catalinmarianmursa7892
    @catalinmarianmursa7892 6 หลายเดือนก่อน

    Thank you!

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      You are welcome.

  • @abhigupta3193
    @abhigupta3193 5 หลายเดือนก่อน

    thanks, I learn lots of things for generics

    • @IAmTimCorey
      @IAmTimCorey  5 หลายเดือนก่อน

      I am glad it was helpful.

  • @Sanabalis
    @Sanabalis 6 หลายเดือนก่อน

    PersonRecord + PersonRecord might sometime produce MarriageRecord, or even ChildRecord (derived from PersonRecord), but most often they just produce an instance of PeopleRecord.

  • @RiderInHell
    @RiderInHell 6 หลายเดือนก่อน

    Aside from what you mentioned about object type being more expensive than the generic T type, it might be worth mentioning that while the object type allows you to shove everything and anything into a list the generic T type allows only one.
    I know you mentioned this but it might not have been explicit to someone that's never dealt with generics before.

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      Thanks for sharing.

  • @ArgoRobots
    @ArgoRobots 6 หลายเดือนก่อน

    Can you make a video explaining how to make custom XML comment tags for C# IntelliSense? When I hover my mouse over functions built into C#, some of the text (like "true", "false", etc.) is a different color. How do I do that?

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @bsdrago
    @bsdrago 6 หลายเดือนก่อน

    Hey, great vdeo. But Id like to ask: Im using UNityENgine and my tests are the opposite: Both (int and objects) are slower in my computer and objects take less time than int (test in video in 9:00). Do you have any ideia why? Thnaks for this awesome video.

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน +1

      My guess is that there is some type of mismatch in your comparison. If you are converting an object to an int, that will take a non-zero amount of time. If you compare that to a method where you are not doing that conversion, the one where you are doing the conversion will be longer if the two are otherwise the same.

    • @bsdrago
      @bsdrago 6 หลายเดือนก่อน

      @@IAmTimCorey The code is the same as the video, but I put it inside unity's Start() event. I'll still understand why the result is so different. Thanks.

  • @ademineshat
    @ademineshat 6 หลายเดือนก่อน

    Thanks. Is there any .net maui content coming in the future?

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      Not in the near future (next few months). I would like to, but it is going to take some doing to get deep into it. Covering mobile in general takes a LOT of content, since it is such a complicated subject. It is high on my priority list, though.

    • @kylekeenan3485
      @kylekeenan3485 6 หลายเดือนก่อน

      Oh lovely that would be great!

  • @jeffsherman9638
    @jeffsherman9638 6 หลายเดือนก่อน

    Would you say that the most common usage of generics would be if multiple types need to be used?

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน +2

      The most common use of generics is in list-types (List, IEnumerable, etc.) and those are mostly single types. Beyond that, I'm not sure I see a standout. For instance, when I do my data access with Dapper, I do one method with two types, one with one.

    • @jeffsherman9638
      @jeffsherman9638 6 หลายเดือนก่อน

      @@IAmTimCorey I guess I don’t see any advantage if it’s still declared as a single data type

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน +2

      Sorry, I think we might be talking about different things. I am talking about having one generic type as opposed to two . If you are asking if people typically put more than one type (such as PersonModel, UserModel, and EmployeeModel) into then yes, kind of. Once you declare such as List, you can only use that type for T. However, you can also have a List separately that you use. The benefit of being generic is that you can reuse the same code for working with Lists, but work with any type in a type-safe manner. Does that better answer your question?

    • @jeffsherman9638
      @jeffsherman9638 6 หลายเดือนก่อน

      @@IAmTimCorey I think so. I just need to see more use cases and to see if it is a popular option in software development

  • @hjoseph777
    @hjoseph777 หลายเดือนก่อน

    Hey Tim, can you explain the concept high otherwise it is straight coding.

    • @IAmTimCorey
      @IAmTimCorey  หลายเดือนก่อน

      I'm not sure what you are asking for. Are you asking for a high-level explanation?

  • @harrygarala4119
    @harrygarala4119 6 หลายเดือนก่อน

    I love the trick in generics

  • @jerrybodensky9679
    @jerrybodensky9679 6 หลายเดือนก่อน

    I listened to the video while I was doing the dishes.
    When I heard about "meth operations", my first thought was: How can something like that be legal in C#?
    Just kidding....
    An usefull concept explained clearly!
    Thanks!

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน +1

      😂 Haven't you heard of the Breaking Bad C# channel? Although, that does sound like a good concept: breaking bad C# habits and code patterns one video at a time.

  • @MyReviews_karkan
    @MyReviews_karkan 4 หลายเดือนก่อน

    Could you please have chapters in your videos? Sometimes I want to skip. A subject that I know, but then find out there is no chapter. Thank you

    • @IAmTimCorey
      @IAmTimCorey  4 หลายเดือนก่อน

      That comes down to time. I don't have the time to add them in, and right now neither does my team. So, we rely on people in the community to help us out with those.

  • @jeffreyelkins3183
    @jeffreyelkins3183 6 หลายเดือนก่อน

    I prefer my list of Coffee not T

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      👍🏻

  • @MrMichalXXL
    @MrMichalXXL หลายเดือนก่อน

    You can'tbe serious that as an example you give type checker string with string parameter...I know it's only an example but cmon

    • @IAmTimCorey
      @IAmTimCorey  หลายเดือนก่อน

      First, you just answered your own statement - this is a demo. The point isn't to give you a code snippet that you would drop into your code. The point is to give you a clear demo that doesn't add confusion to the viewer. Building demos that will effectively communicate is nothing like building production code. If I built production code, it would obscure the lesson enough that it would not be understood. That's when you see demos where you have dozens of prerequisites in order to understand even a simple topic. The key is to eliminate as many assumptions and prerequisites as possible.
      Second, the point wasn't to create a method that checked the type. The point was to visually show off that different types could be used with our generic and that they would be treated like that type inside of the method. That was the purpose of using a type checker.
      Third, did you watch the whole video? I demonstrated a generic method (that's what you are talking about here) that displayed the type it was storing so that the user could see the types were different. Then I demonstrated a generic class where we built a better list (one that reported what went into it when something was added). Then we demonstrated a generic class with restrictions on the type of generic being passed in so that we could add numbers even if we didn't know what type of numeric type it was. At the end of the video, I also gave additional uses for generics (Lists, logging, etc.)

  • @waynehawkins654
    @waynehawkins654 6 หลายเดือนก่อน +1

    Nice video but you lost me a bit. Be good you dig deeper into this topic.

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน +1

      Have you practiced it? Sometimes it clicks when you do it yourself.