Attributes get a feature long-overdue in C# 11

  Рет қаралды 65,679

Nick Chapsas

Nick Chapsas

2 жыл бұрын

Check out my courses: dometrain.com
Come to NDC Oslo: bit.ly/ndcoslo2022nick1
Become a Patreon and get source code access: / nickchapsas
Hello everybody I'm Nick and in this video I will show you how C# 11 adds a missing feature for Attributes. The feature is called Generics on Attributes and It was honeslty the only thing about attributes that I was so confused about since every other aspect of the language supports generics. It finally solves a workaround where we had to pass down a type and do some magic under the hood.
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: bit.ly/ChapsasGitHub
Follow me on Twitter: bit.ly/ChapsasTwitter
Connect on LinkedIn: bit.ly/ChapsasLinkedIn
Keep coding merch: keepcoding.shop
#csharp #dotnet

Пікірлер: 101
@danfg7215
@danfg7215 2 жыл бұрын
I'm completely lost, so much I still have to learn about C#, what a complex and expressive language.
@jammehcow
@jammehcow 2 жыл бұрын
Much needed feature. The constraints you get with this clears up a lot if that dependence on runtime checks.
@albe1620
@albe1620 2 жыл бұрын
Can you explain what runtime checks do you mean? Because in the video I see only a small syntax benefit.
@krccmsitp2884
@krccmsitp2884 2 жыл бұрын
@@albe1620 You can constrain generic type parameters (base class, interface etc.) at compile time, so you don't need to verify the type at runtime.
@chrise202
@chrise202 2 жыл бұрын
What I want from filters for 10 years now, is being able to pass in delegates, and not only constants eg: [Filter(x => x.Age > 20)] Everything else around attributes is like waves in a bucket.
@metaltyphoon
@metaltyphoon 2 жыл бұрын
That looks a lot like validation to me.
@gileee
@gileee 2 жыл бұрын
@@metaltyphoon You might also want to do authorization like this tho.
@metaltyphoon
@metaltyphoon 2 жыл бұрын
@@gileee wouldn’t this be done via Policies? Even Microsoft examples shows Authorization being done with Policies
@gileee
@gileee 2 жыл бұрын
@@metaltyphoon Sure if you want every feature being implemented with different methodologies. I like all my code to be similar and clean. Also, I just don't like writing Policies, I much prefer writing functions.
@metaltyphoon
@metaltyphoon 2 жыл бұрын
@@gileee i guess. To each their own. I rather follow conventions set by the framework where authorization is done by the authorization middleware instead of traversing all the way to mvc / endpoint to then apply a policy.
@jebwatson
@jebwatson 2 жыл бұрын
Sounds like it's mostly about the type constraints but with the bonus of cleaner syntax. I like it!
@amgos
@amgos 2 жыл бұрын
Much needed feature! Great video as always, it's clear and concise without any fluff.
@thegenxgamerguy6562
@thegenxgamerguy6562 2 жыл бұрын
I use attributes to facilitate DI container registration. Having to use typeof(...) was terribad. Now we can finally do it properly: [Implementation] Yes.
@rogeriobarretto
@rogeriobarretto 2 жыл бұрын
Amazing news for c# 11. This version is mind blowing! Will be something close from 1.1 to 2.0. Very good to see the lang evolving for better
@oggatog3698
@oggatog3698 2 жыл бұрын
I've been asking for this for years! 💗
@LeeRoyAshworth
@LeeRoyAshworth 2 жыл бұрын
Look forward to using this in my libraries, 👍. Thanks for the explanation of the use-case.
@HealthyDev
@HealthyDev 2 жыл бұрын
Nice, I can think of several designs over the years that really would have benefited from this. Nice walkthrough.
@antonmartyniuk
@antonmartyniuk 2 жыл бұрын
I missed using generics in the attributes a lot. Finally they did it! From the video title I guessed the nice little feature
@MarioFromMario
@MarioFromMario 2 жыл бұрын
Dude I'm so excited for this. I've been wanting generic attributes for a long time.
@andersborum9267
@andersborum9267 2 жыл бұрын
A much needed feature indeed; it's not the typeof(attribute) thing that's the issue here, rather it's the missing constraints coming from generics itself.
@VladyslavHorbachov
@VladyslavHorbachov 2 жыл бұрын
I'm already know where to use it. I did a custom data grid, that takes a DTO and based on it a grid creates a columns collection with filters and so on. And it will be much easier to specify some additional information using a new Attributes
@sunefred
@sunefred 2 жыл бұрын
I was waiting for the "required property" video, but this is nice too!
@JohnWSaundersIII
@JohnWSaundersIII 2 жыл бұрын
About time. Can't wait to use it.
@UzairAli001
@UzairAli001 2 жыл бұрын
This feature is really awesome, I always wanted to put constraints on Attribute and now it's possible.
@Toffe
@Toffe 2 жыл бұрын
Love this bite sized videos, could watch it on the go.
@iSoldat
@iSoldat 2 жыл бұрын
I like it, unfortunately, I'm working with a code base (at the moment) that is pure spaghetti and the push back I receive when I say they've created their own code/tech debt is "if it isn't broke, don't fix it." With the speed of change in the industry, those words grind my gears.
@davidheale6435
@davidheale6435 2 жыл бұрын
Seriously, about time. I was really upset when this got pushed off. As soon as it's out of preview, I definitely will be using this.
@nickchapsas
@nickchapsas 2 жыл бұрын
Same. I have so many usecases for this
@umutcelenli2219
@umutcelenli2219 2 жыл бұрын
Finally... Was sick of the typeof requirement in such cases.
@johncerpa3782
@johncerpa3782 2 жыл бұрын
Great video!
@disturbutive
@disturbutive 2 жыл бұрын
Just reading name of video I guessed what it about. Happy that it is it, really useful stuff
2 жыл бұрын
see you in oslo!
@billy65bob
@billy65bob 2 жыл бұрын
Interesting, I didn't know there was a specific attribute for using DI on filters. Best usecase I have so far, is localisation; I made a 'LocalisedString' attribute that currently takes the ResourceManager's type as input, and the key to look up from it, and then I have some 'ToDescription' methods to look for these and deal with them. I don't know how well it'll work, since these ResourceManagers don't implement any interfaces, but it was the first time I ever wanted generics on attributes.
@fakhrulhilal
@fakhrulhilal 2 жыл бұрын
Definitely the feature that I've been waiting since versions ago.
@swedishprogrammer
@swedishprogrammer 2 жыл бұрын
Love this change 🥳
@nader1999ful
@nader1999ful 2 жыл бұрын
Definitely a great quality of life feature! However I don’t believe i will use it, here is why: In most of my cases I need to send specific params per endpoint to the filter constructor. As you mentioned in the video, I can’t init the filter in the controllers level and use DI in the same time. To by pass this issue - I activate the filter on all of my controllers (in startup.cs) And then decorate each endpoint with another attribute which acts as a parameter holder for the main filter
@dcernach
@dcernach 2 жыл бұрын
Wow, for me it used to be A MUCH needed feature... now it's real !!! 🥰
@ColinM9991
@ColinM9991 2 жыл бұрын
Really good feature. I don't think I'll reap immediate benefits, as I don't have a use case now, but there have been many times in the past where I'd have loved to have had generic attributes, particularly with JSON and contract definitions on domain libraries.
@Andrew90046zero
@Andrew90046zero 2 жыл бұрын
I've never really used attributes in the way you are showing in this video. And what I mean by that is, I've never made an attribute class that has like other functions in them like "CreateInstance". Like how/where would that function be called? Where do instances of attribute classes get instantiated? Is there a video of yours that covers this?
@ghostaccount9865
@ghostaccount9865 2 жыл бұрын
Hey nick, I really like your videos, but I always find myself really behind in C# knowledge. Can you recommend something to boost that knowledge to the next level ?
@queenstownswords
@queenstownswords 2 жыл бұрын
Hello Nick. Will you make the Oslo workshop available in some manner after the conference?
@thesandboxgamingvideos
@thesandboxgamingvideos 27 күн бұрын
we need this for class methods without any third party library.
@fifty6737
@fifty6737 2 жыл бұрын
i hope attributes constructor dependency injection will be a thing, since in the example they dealing with the service provider and and registering services i can see why it's a bad idea to implement that inside something that is considered as a metadata for reflection / source generators, but i hope they come up with something to address that
@sergiuvancu291
@sergiuvancu291 Жыл бұрын
Hi Nick. Great materials you have on this channel. I've recently discovered it. On this material I have a question. When you added the filter, you added it as Scoped, specifying the controller is also scoped. From what I know by default the controllers are added as transient and I didn't see in the presented code any reference to making the controller scoped. Could you please explain briefly? Thanks
@nickchapsas
@nickchapsas Жыл бұрын
Controllers are scoped by default
@JoonhwanLee
@JoonhwanLee 2 жыл бұрын
Nick, did you know you can create file in a directory at once in Rider? BTW very catchy feature it is!
@AnotherFancyUser
@AnotherFancyUser 2 жыл бұрын
Hey Nick how are you doing? By any chance do you have videos about how to make c# tech assessments? what questions to ask?
@Rajeshsingh-ws5th
@Rajeshsingh-ws5th 2 жыл бұрын
thats good. as these filters run automatically in execution pipeline, can't we make such custom filter and decorate in business layer methods?
@gdargdar91
@gdargdar91 2 жыл бұрын
Your updates are ready to be installed.
@user-zg2ec3nn8b
@user-zg2ec3nn8b 2 жыл бұрын
Hey! What font do you use in your IDE?
@dlandi
@dlandi Жыл бұрын
Yes, the typeOf() thing is an incredile pain.
@Taneth
@Taneth 2 жыл бұрын
Speaking of typeof, adding `typeof(this)` as a language construct would be useful for such things as dependency properties and routed events. It wouldn't even need an instance, because it's referring to the class that contains the expression.
@sinan720
@sinan720 2 жыл бұрын
You can already do "this.GetType()"
@Taneth
@Taneth 2 жыл бұрын
@@sinan720 That requires an instance. I'm talking about a language construct.
@Taneth
@Taneth 2 жыл бұрын
To clarify: dependency properties and routed events are declared statically. Attached properties are often even defined in static classes. Boilerplate for these items require a reference to the class type that contains it. GetType is an instance method that is executed at runtime and pulls from reflection; it is not available here. On the other hand, typeof is evaluated at compile time and is even available to attributes. So, typeof(this) would be a shortcut to typeof(TheClassThatContainsThisLine)
@Taneth
@Taneth 2 жыл бұрын
@@DanKaschel I'm talking about giving the keyword a different meaning in a different context. Like how 'using' has two meanings based on context. Just a syntactic shortcut. Nothing to do with a child class.
@renatogolia211
@renatogolia211 2 жыл бұрын
I wish they added also support for delegates in attribute constructors. For example, I would use it when customizing AutoFixture at test level.
@nickchapsas
@nickchapsas 2 жыл бұрын
It would be so convinient but I can see how it's really tricky to implement
@adrianlyons2444
@adrianlyons2444 2 жыл бұрын
are the generic arguments available in source generators as well?
@BruceRRay
@BruceRRay Жыл бұрын
Will this be available in VB? (I'm working in a large legacy codebase where this would be fantastic to use!)
@danrayson
@danrayson Жыл бұрын
I'd say the thing that's STILL missing is that this isn't just in the language by default, you have to be in a controller.
@WillEhrendreich
@WillEhrendreich 2 жыл бұрын
You know, this is nice, but I'm with Immo Landwerth in saying that c#'s best feature is being able to call in to F#.... =)
@Killputin777
@Killputin777 2 жыл бұрын
cooooool!
@iamjimgroth
@iamjimgroth Жыл бұрын
Protip: Do not lose focus for a single second while watching these videos. 😁
@camilosijindioy877
@camilosijindioy877 25 күн бұрын
how can I apply this concept to a console application in .NET 4.8?
@danijelzg001
@danijelzg001 2 жыл бұрын
StrongInject/Jab will be much better with generic attributes 🙂
@nickchapsas
@nickchapsas 2 жыл бұрын
I am so looking forward to see this used in source generators in general
@dextergandini
@dextergandini Жыл бұрын
It will make xunit attributes way better
@mjfanankit
@mjfanankit 2 жыл бұрын
Thumbs up if you too checked the playback speed. Anyway awesome content...
@CrippleX89
@CrippleX89 2 жыл бұрын
xUnit! Are you watching? Things like the TestCollectionOrderer attribute could really do with this instead of providing the assembly name and fully qualified type name. PS if they can't, that'd be a real big shame. I've only just started using xUnit after I got fed up with MSTest so I don't know the ins and outs of xUnit yet.
@sealsharp
@sealsharp 2 жыл бұрын
Generic Attributes, yesssss!
@futurexjam2
@futurexjam2 2 жыл бұрын
Those filter idea, I suppose, comes from Java world and in Java unfortunately there is type erasure issue :)) Eventually they have to indicate Class.class and here there is typeof(Class) here. Moreover AspectJ is good aspect resolver, however Java hurts me so much by type erasure issue after .net stack :))
@alexclark6777
@alexclark6777 2 жыл бұрын
A great QoL enhancement. I hope it actually makes it into the 11 release; I got excited at the thought of static abstract interface members a while back and they're still dangling that carrot in preview mode. :( Still, definitely better for it to be properly tested/QAd before it makes it into the language!
@nickchapsas
@nickchapsas 2 жыл бұрын
It looks like we are getting both this time but I'll keep my fingers crossed just in case 🤞
@SunSailor
@SunSailor 2 жыл бұрын
Not exactly a game changer, but wow is that welcome! Can't wait for this feature to arive in Unity!
@maxsteffey6521
@maxsteffey6521 2 жыл бұрын
😂 Unity is still on Mono lmfao
@maxsteffey6521
@maxsteffey6521 2 жыл бұрын
they’re also on c# 9 and you can’t even do init props
@daniaalnadir
@daniaalnadir 2 жыл бұрын
Smashing video but still confused on what you couldn’t do before that you can now. Yes it’s cleaner but that’s the only thing I see
@nickchapsas
@nickchapsas 2 жыл бұрын
You couldn't have generic type constraints in compile type so for example if you wanted to only accept a type that implements an interface, you'd have to check at compile time and throw an error. Now the code won't even compile leading to safer code
@DickBakerSql
@DickBakerSql 2 жыл бұрын
why so complicated/difficult that it was dropped in C# v10 ?
@CricketThomas
@CricketThomas 2 жыл бұрын
Microsoft should be funneling this guy money.
@megaman27528
@megaman27528 2 жыл бұрын
You can create a new class that inherits from TypeFilterAttribute. So you can use it explicitly without typeof or generics. Your example looks contrived.
@nickchapsas
@nickchapsas 2 жыл бұрын
Inheritance on attributes. Yeah no thanks. What a convoluted solution too. You need one implementation per type. I'll pass. Also, the video would be exactly the same with any other attribute that accepts a Type. It looks like you're (intentionally) missing the point
@megaman27528
@megaman27528 2 жыл бұрын
​@@nickchapsas My comment is just that you don't have to wait for c# 11 to write pretty attributes. You've already spent a bunch of lines of code writing a filter. What is the problem to add 5 more lines for the corresponding attribute.
@portlyoldman
@portlyoldman 2 жыл бұрын
My employer is me 🥺
@mightybobka
@mightybobka 2 жыл бұрын
Attributes are evil.
@nickchapsas
@nickchapsas 2 жыл бұрын
Inheritance is evil
@nickchapsas
@nickchapsas 2 жыл бұрын
@@MiningForPies I don't think they are. As long as there is a non-attribute alternative or and they are built in a unit testable way, I think they are fine to use.
@mightybobka
@mightybobka 2 жыл бұрын
@@nickchapsas Inheritance is a part of OOP. You can just use language with any other paradigm, like procedural programming languages, there you will find none of inheritance.
@nickchapsas
@nickchapsas 2 жыл бұрын
@@mightybobka I can just choose to not use inheritance instead. It’s like saying that if I want to use a specific functional element in my language then I should just write a functional language instead. It doesn’t work that way in real life. You can pick and choose what works for you within the language you like
@dimalisovyk5277
@dimalisovyk5277 2 жыл бұрын
Looks cool. But more like a cosmetic change. Would be nice to have a way to register filters and ioc in startup, so that you can just use [MyFilter] and it will hadle DI like with the costructor params
@nickchapsas
@nickchapsas 2 жыл бұрын
It’s not just cosmetic but functionality as well. You can now have compile time constraints on the type that you’re passing. You couldn’t do that before
@crazyfox55
@crazyfox55 2 жыл бұрын
@@nickchapsas Do you have a good example use case? Besides updating the current attributes, are their new attributes that are now possible?
@modernkennnern
@modernkennnern 2 жыл бұрын
@@crazyfox55 generics do not add functionality - not really - but they make it a lot easier to have cleaner, more readable, better performing code.
@realtimberstalker
@realtimberstalker 2 жыл бұрын
@@crazyfox55 Say you have classes that inherit from IAttributeTarget that are the only types allowed in the attribute. You no longer have to explicitly check it and throw a runtime error when a type that doesn’t inherit that interface is passed, or when null is passed as well. The program will simply not compile, so you don’t need to add the checks anymore and its much easier to catch.
@nitrous1001
@nitrous1001 2 жыл бұрын
System.Text.Json and Newtonsoft.Json needs this badly
@MarioFromMario
@MarioFromMario 2 жыл бұрын
Dude I'm so excited for this. I've been wanting generic attributes for a long time.
Why I won’t need constructors anymore in C# 11
9:39
Nick Chapsas
Рет қаралды 134 М.
Don't throw exceptions in C#. Do this instead
18:13
Nick Chapsas
Рет қаралды 248 М.
How many pencils can hold me up?
00:40
A4
Рет қаралды 18 МЛН
Sigma Girl Education #sigma #viral #comedy
00:16
CRAZY GREAPA
Рет қаралды 82 МЛН
어른의 힘으로만 할 수 있는 버블티 마시는법
00:15
진영민yeongmin
Рет қаралды 9 МЛН
格斗裁判暴力执法!#fighting #shorts
00:15
武林之巅
Рет қаралды 90 МЛН
Getting Started with Event Sourcing in .NET
37:07
Nick Chapsas
Рет қаралды 42 М.
What is Span in C# and why you should be using it
15:15
Nick Chapsas
Рет қаралды 247 М.
What are record types in C# and how they ACTUALLY work
15:36
Nick Chapsas
Рет қаралды 116 М.
8 await async mistakes that you SHOULD avoid in .NET
21:13
Nick Chapsas
Рет қаралды 307 М.
Python 3.12 Generic Types Explained
18:27
ArjanCodes
Рет қаралды 56 М.
The Only .NET Scheduler You Should Be Using!
16:38
Nick Chapsas
Рет қаралды 43 М.
Every single feature of C# in 10 minutes
9:50
Train To Code
Рет қаралды 83 М.
Every New Feature Added in C# 12
14:19
Nick Chapsas
Рет қаралды 146 М.
How many pencils can hold me up?
00:40
A4
Рет қаралды 18 МЛН