Equality Analysis, Ref Structs, Culture Previews, Using Directives – C# Language Support in 2024.2 | The .NET Tools Blog (2024)

Essential productivity kit for .NET and game developers

Follow

  • Follow:
  • Guide Guide
  • RSS RSS

Get Tools

.NET ToolsHow-To'sReSharper PlatformRider

Our release for ReSharper and Rider 2024.2 is just around the corner, and we have lots of exciting features shipping for the new C# 13 and current C# and VB.NET! Since there are so many, we will split them into multiple blog posts. So make sure to check those posts out as well!

In this series, we will cover features around:

  • Escape Character, Extract Common Code, Params Modifier, Out Vars
  • Equality Analysis, Ref Structs, Culture Previews, Using Directives
  • Cast Expressions, Primary Constructors, Collection Expressions, List Patterns

Make sure to download the latest version of ReSharper or Rider follow along:

Download Rider 2024.2

Download ReSharper 2024.2

Enhanced Equality Analysis

Struct types have been available since the very first .NET Framework. If you’re taking advantage of them, you may have heard that it’s good practice to override Equals and GetHashCode for performance reasons, because the default runtime implementation suffers from boxing and reflection overhead. This is particularly relevant in hot paths that call equality members. Furthermore, the default implementation of GetHashCode works in a way that it takes the hash of the first non-null reference type field, which may lead to a bad distribution.

In 2024.2, we are introducing a set of new inspections to identify such performance issues where equality is checked under the hood. You can fix these issues by generating equality members, or by turning it into a record struct and letting the compiler generate implementations for you:

Equality Analysis, Ref Structs, Culture Previews, Using Directives – C# Language Support in 2024.2 | The .NET Tools Blog (3)

We have also added a new attribute [DefaultEqualityUsage] to our JetBrains Annotations NuGet package, which allows you to mark types or parameters as being used for equality checks:

public class Equality{ object N() => M(new MyPoint()); // warning object M<T>([DefaultEqualityUsage] T obj) => null; // no Equals/GetHashCode overrides public struct MyPoint;}

Copy to clipboard

As part of this feature, we also annotated the BCL with the new [DefaultEqualityUsage] attribute and discovered surprising details about some APIs. For example, you might assume that in a ConcurrentDictionary the equality is only checked for the TKey type. That is true until you use AddOrUpdate, which can also check TValue for being equal on update:

var idToData = new ConcurrentDictionary<int, Data>();// ConcurrentDictionary<TKey, TValue>.AddOrUpdate implementation// actually checks TValue for being equal on update:idToData.AddOrUpdate( key: id, // compute what to add addValueFactory: static id => default, // do the update updateValueFactory: static (id, data) => data);// no Equals/GetHashCode overridespublic struct Data{ // members}

Copy to clipboard

Last but not least, our analysis also catches suspicious non-structurally comparable types inrecord types. In the following example, twoPayloadobjects would only be considered equal if they share the samebyte[]arrayreference– this is very likely not the intended behavior. You would rather call SequenceEqual in your custom equality members:

Equality Analysis, Ref Structs, Culture Previews, Using Directives – C# Language Support in 2024.2 | The .NET Tools Blog (4)

Note that this inspection will only be checked if the record type is being used in equality-relevant APIs in your solution.

Ref Struct Interfaces

The introduction of ref struct types in C# 7.2 (Span<T> and ReadOnlySpan<T>) has enabled many new high-performance scenarios. Those benefits came with limitations in a few aspects though. They could not be boxed, could not appear as fields in reference types, could not be stored as array elements, and did not allow interface inheritance. Some limitations are by design, but some could be relaxed during language evolution. One of those relaxations is interface inheritance.

In the following example, we’ve got a generic algorithm PrintArrayLike to print all items of an object of the type IArrayLike. With C# 13, we can make our ref struct ArrayLikeSpan implement that interface. However, invoking the method on that object is still not possible yet! Can you guess why?

var obj = new ArrayLikeSpan([1, 2, 3]);PrintArrayLike(obj); // errorvoid PrintArrayLike<TArrayLike>(TArrayLike arrayLike) where TArrayLike : IArrayLike{ for (var index = 0; index < arrayLike.Length; index++) Console.WriteLine(arrayLike[index]);}public readonly ref struct ArrayLikeSpan(Span<int> span) : IArrayLike // now allowed in C# 13!{ private readonly Span<int> span = span; // can store `ref struct` inside `ref struct` public int Length => span.Length; public int this[int index] => span[index];}public interface IArrayLike{ int Length { get; } int this[int index] { get; }}

Copy to clipboard

In the method PrintArrayLike, you could theoretically add the following line, which would essentially break the “no boxing” rule:

// cannot box ref struct!var reference = (object)arrayLike;

Copy to clipboard

Therefore, the compiler requires you to make an explicit decision that the generic method can handle ref struct types and disallows boxing. This is achieved with the allows ref struct anti-constraint, which you can easily add through a quick-fix from the error:

Equality Analysis, Ref Structs, Culture Previews, Using Directives – C# Language Support in 2024.2 | The .NET Tools Blog (5)

The allows ref struct constraint will also show up in code completion with the shorthand aref:

Equality Analysis, Ref Structs, Culture Previews, Using Directives – C# Language Support in 2024.2 | The .NET Tools Blog (6)

Culture Previews

Since ReSharper 8, we’ve been helping you choose the correct formatting specifiers in code completion. However, for types like DateTime or DateOnly, we could only guess which culture will eventually be set when your code executes and how ToString renders, so we chose CultureInfo.Invariant as the default.

With 2024.2, we are adding a new tooltip that shows how a value would render in different popular cultures, including the current OS culture:

Equality Analysis, Ref Structs, Culture Previews, Using Directives – C# Language Support in 2024.2 | The .NET Tools Blog (7)

Sorting Using Directives

Are you in the team of developers that just feels good about their using directives at the top of the file to be minimal and in order? In ReSharper and Rider, we are making sure that all file modifications make use of the same internal API which ensures exactly that. You may also know, that our code cleanup profiles have an option to optimize using directives on a shortcut or save operation. Despite all this effort, files can still end up with unordered and redundant lists of imports, mainly explained by manual edits like merge operations.

In 2024.2, we are making it complete by adding a Sort ‘using’ directives context action that can be triggered independently from all other cleanup steps:

Equality Analysis, Ref Structs, Culture Previews, Using Directives – C# Language Support in 2024.2 | The .NET Tools Blog (8)

Conclusion

Give it a go with the latestReSharper 2024.2 and Rider 2024.2, and let us know if you have any questions or suggestions in the comments section below.

.NET C# Inspections ReSharper Rider VB.NET

  • Share
  • Facebook
  • Twitter
  • Linkedin

Prev post The ReSharper and the .NET tools 2024.2 Release Candidates Are Now AvailableCast Expressions, Primary Constructors, Collection Expressions, List Patterns – C# Language Support in 2024.2 Next post

Equality Analysis, Ref Structs, Culture Previews, Using Directives – C# Language Support in 2024.2 | The .NET Tools Blog (9)

Subscribe to a monthly digest curated from the .NET Tools blog:

Equality Analysis, Ref Structs, Culture Previews, Using Directives – C# Language Support in 2024.2 | The .NET Tools Blog (10)

Discover more

dotCover, dotMemory, dotPeek, and dotTrace 2024.2 Have Been Released! dotCover 2024.2, dotMemory 2024.2, dotPeek 2024.2, and dotTrace 2024.2 have been released and are ready for download!Let’s take a look at what’s new with these .NET tools.dotMemory 2024.2Improved instance search with new filtering options.The following features are now ava… Sasha Ivanova
ReSharper 2024.2: Deepened C#12 and Initial C#13 Support, New AI Capabilities, Localization, and More Hello everyone,ReSharper 2024.2 and the latest versions of other JetBrains .NET tools have just been released. This release brings support for the .NET 9 Preview SDK, new C# and C++ features, localization updates, AI Assistant enhancements, and much more.In this article, we’ll cover the high… Sasha Ivanova
Rider 2024.2: Full Line Code Completion, Reader Mode, Major Enhancements to Debugging, and More. Hello everyone,We're happy to announce the release of Rider 2024.2, which comes packed with a range of exciting features and improvements designed to elevate your .NET and game development experience. From enhanced language support to advanced AI capabilities, this update has something for every… Sasha Ivanova
Unreal Debugging Improvements in Rider 2024.2 Rider 2024.2 includes massive improvements to the native debugger, significantly improving the experience of evaluating native code while debugging. There are performance improvements, better handling of optimised code, and support for evaluating operators on smart pointers and string types. The cha… Matt Ellis
Equality Analysis, Ref Structs, Culture Previews, Using Directives – C# Language Support in 2024.2 | The .NET Tools Blog (2024)
Top Articles
Convert Inch to Mile
Inches to Miles conversion: in to mi calculator
Mickey Moniak Walk Up Song
Devin Mansen Obituary
Canya 7 Drawer Dresser
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Jazmen Jafar Linkedin
Unlocking the Enigmatic Tonicamille: A Journey from Small Town to Social Media Stardom
The Powers Below Drop Rate
Barstool Sports Gif
Fcs Teamehub
Joe Gorga Zodiac Sign
Chastity Brainwash
Unit 1 Lesson 5 Practice Problems Answer Key
Signs Of a Troubled TIPM
今月のSpotify Japanese Hip Hopベスト作品 -2024/08-|K.EG
Theycallmemissblue
Mary Kay Lipstick Conversion Chart PDF Form - FormsPal
What Happened To Anna Citron Lansky
Ostateillustrated Com Message Boards
Char-Em Isd
CANNABIS ONLINE DISPENSARY Promo Code — $100 Off 2024
Reptile Expo Fayetteville Nc
Craigslist Houses For Rent In Milan Tennessee
Surplus property Definition: 397 Samples | Law Insider
Sherburne Refuge Bulldogs
Avatar: The Way Of Water Showtimes Near Maya Pittsburg Cinemas
Arrest Gif
Impact-Messung für bessere Ergebnisse « impact investing magazin
Mdt Bus Tracker 27
Table To Formula Calculator
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
Pdx Weather Noaa
South Florida residents must earn more than $100,000 to avoid being 'rent burdened'
Kaiserhrconnect
Rock Salt Font Free by Sideshow » Font Squirrel
Fridley Tsa Precheck
Chattanooga Booking Report
All Things Algebra Unit 3 Homework 2 Answer Key
Keeper Of The Lost Cities Series - Shannon Messenger
Restored Republic May 14 2023
Wrigley Rooftops Promo Code
303-615-0055
Man Stuff Idaho
Nid Lcms
Clausen's Car Wash
Mudfin Village Wow
Guy Ritchie's The Covenant Showtimes Near Grand Theatres - Bismarck
Rovert Wrestling
60 Second Burger Run Unblocked
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 5854

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.