Monday, July 29, 2024

C# new params collections C# 13

 

C# 13

C# 13 focuses on flexibility and performance, making many of your favorite features even better. Enhancing params parameters are to provide you with more flexibility. 

Let’s take a look!

Enhancing C# params

params are no longer restricted to arrays! 

When the params keyword appears before a parameter, calls to the method can provide a comma delimited list of zero or more values and those values are placed in a collection of the parameter’s type. Starting in C# 13, the params parameter type can be any of the types used with collection expressions, like List<T>, Span<T>, and IEnumerable<T>. What are the benefits of these overloads? By adding an IEnumerable<T> overload, support for LINQ is enabled. And by adding a ReadOnlySpan<T> or Span<T> overload, memory allocations can be reduced, enhancing performance. 

Just specify a different collection type as the parameter type:

void PrintList(params IEnumerable<string> list) 
    => Console.WriteLine(string.Join(", ", list));

PrintList("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

// prints "Sun, Mon, Tue, Wed, Thu, Fri, Sat"

It’s really that easy to use the collection type that best fits your needs. Programmers using your method can just pass a comma delimited list of values. They do not need to care about the underlying type.

Making params better with spans

One important aspect of performance is reducing memory use, and System.Span<T> and System.ReadonlySpan<T>are tools in reducing memory allocations. You can learn more in Memory and Span usage guidelines.

If you want to use a span, just use the params parameter type to a span type. Values passed to the params parameter are implicitly converted to that span type. If you have two method signatures that differ only by one being a span and the other being an array and the calling code uses a list of values, the span overload is selected. This means you’re running the fastest code available and makes it easier to add span to your apps.

Many of the methods of the .NET Runtime are being updated to accept params Span<T>, so your applications will run faster, even if you don’t directly use spans. This is part of our ongoing effort to make C# faster and more reliable. It’s also an example of the attention we give to ensuring various C# features work well together. Here is an example from StringBuilder.

public StringBuilder AppendJoin(string? separator, params ReadOnlySpan<string?> values)

params and interfaces

The story gets even better with params support for interfaces. If no concrete type is specified, how does the compiler know what type to use?

Just like collection expressions in C# 12, when you specify an interface as a parameter type, it’s a clear indication that you just want anything that implements that interface. Key interfaces are mapped to implementation, so we can give you the best available type that fulfills the interface. The compiler may use an existing type or create one. You should not have any dependencies on the underlying concrete collection type because we will change it if a better type is available.

The great thing about this design is that you can just use interfaces for your params types. If you pass a value of a type that implements the interface, it will be used. When a list of values or a collection expression are passed, the compiler will give you the best concrete type.

Wednesday, November 02, 2022

10 Take-aways Moving MSSQL to PostgreSQL

Background: Based on my recent project, here are the 10 takeaways of MS SQL Server to PostgreSQL migration.
  1. Save the operating cost on SQL Server license. 
  2. PGSQL is case sensitive on char comparison. MSSQL is not case-sensitive. Therefore, the where clauses need to be reviewed in Entity Frameworks (EF). However, Entity Frameworks schema mapping is not case sensitive for C# property names on column names. 
  3. PGSQL supports uuid, which is the same as UniqueIdentifier in SQL Server.
  4. PGSQL timestamp without time zone can be used in MSSQL datetime.
  5. PGSQL 'RAISE NOTICE' equals to MSSQL 'PRINT'.
  6. PGSQL support the data type record. I found this very useful in the migration scripts.  (for loop)
  7. PGSQL block supports transaction. (do $$ ... $$) 
  8. PGSQL is very strict on semi-colon (;) for the statement ending.
  9. PGSQL doesn't support table variable.You need to used temp table instead. (temp table)
  10. DBeaver is very useful universal database management tool. 

Monday, April 04, 2022

Write Better Code. Be a better programmer!

Write better code — beautiful, explicit, simple, flat, sparse, readable, obvious, unambiguous,  and exception aware code — Be a better programmer.

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Monday, November 08, 2021

Good Parts of C# Language (v1 - v10)

Background: C# 10, along with .NET 6 and Visual Studio 2022, are released in November 2021. 

Here are the good parts in C#:
  1. C#  1: Anders Hejlsberg led the design of C#
  2. C#  2: Generics, nullable, anonymous methods
  3. C#  3: LINQ, extension methods, lambda expressions
  4. C#  4: dynamic, covariance and contravariance 
  5. C#  5: async/await, caller info
  6. C#  6: string interpolation, nameof, using static
  7. C#  7: span, ref struct
  8. C#  8: async streaming, patterns, indices and range
  9. C#  9: record, covariant return types, Lambda discard parameters
  10. C# 10: null parameter checking, lobal using, file namespaces

Tuesday, October 19, 2021

4 Take-aways for .NET Dictionary

Background: .NET has four built-in dictionary/map types.

Here are some take aways. 

  1. Hashtable - Avoid use hashtable because it is weakly typed.
  2. Dictionary<T> - Hashtable strongly typed replacement. Not thread safe
  3. ConcurrentDictionary<T> - Good read speed even in the face of concurrency, but it’s a heavyweight object to create and slower to update.
  4. ImmutableDictionary<T> - No locking required to read but more allocations require to update than a dictionary.

Monday, September 20, 2021

Upgrade to ASP.NET 5.0

ASP.NET Core 5.0 Runtime (v5.0.10) - Windows Hosting Bundle Installer!

I upgraded one of my websites from .NET Core 2.1 to .NET 5. The experience was quite smooth. It took me about 1 hour to upgrade and publish it back to the web hosting vendor. 

Here are the steps:

1. Download ASP.NET Core 5.0 Runtime from the link  for dotnet-hosting-5.0.10-win.exe

2. Update Target framework to from .NET Core 2.1 to .NET 5.0.

3. HostingEnvironment is obsolete. Need to replace it with IWebHostEnvironment.

4. Replace UseMvc() with UseEndpoints(). Here are the details. 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
            // Obsolet: app.UseMvc();
            // https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                // mvc
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");

                endpoints.MapRazorPages();
            });

I used Visual Studio 2022, version 17 preview 4.0 for the upgrading. As of now, Microsoft hasn't published .NET 6, which is scheduled be published along with Visual Studio 2022 in October, 2021. Overall, the upgrade experience is very quick!

Cheers!

Monday, March 22, 2021

PowerToys for Windows 10

After playing with PowerToys for Windows 10, I'd recommend it. It will make the life much easier for the developers. For instance, PowerRename is really handy and powerful which support regular expression renaming. I also tested FancyZones. If you have many console windows open, Fancy Zones will help you manage your windows easily.

PowerToys for Windows 10 comes with the following utilities:

  • Color Picker adds a tool for HEX and RGB color identification.
  • FancyZones adds a window manager that makes it easier for users to create and use complex window layouts.
  • File Explorer Preview Panes adds SVG and Markdown previews to File Explorer.
  • Image Resizer adds a context menu to File Explorer for resizing images.
  • Keyboard Manager adds options for remapping keys and shortcuts.
  • PowerRename adds an option for users to rename files using search and replace or regular expression in File Explorer.
  • PowerToys Run adds a Spotlight-like tool that allows users to search for folders, files, applications, and other items.
  • Shortcut Guide adds a full screen overlay that allows the user to view the windows key shortcuts available in the current window.
Don't take my words. Try it yourself. Search "PowerToys" after installing PowerToys. 

Install PowerToys for Windows 10

Is High Quality Software Worth the Cost?

I can't agree more with Martin Fowler's post on "Is High Quality Software Worth the Cost?". Here is just a repost. https:/...