<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	 xmlns:media="http://search.yahoo.com/mrss/" >

<channel>
	<title>C# &#8211; Nearshore Software Development Company &#8211; IT Outsourcing Services</title>
	<atom:link href="https://nearshore-it.eu/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>https://nearshore-it.eu</link>
	<description>We are Nearshore Software Development Company with 14years of experience in delivering a large scale IT projects in the areas of PHP, JAVA, .NET, BI and MDM.</description>
	<lastBuildDate>Wed, 21 Aug 2024 13:59:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://nearshore-it.eu/wp-content/uploads/2023/01/cropped-inetum-favicon-300x300-1-32x32.png</url>
	<title>C# &#8211; Nearshore Software Development Company &#8211; IT Outsourcing Services</title>
	<link>https://nearshore-it.eu</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>C# 11 features – check what is new!</title>
		<link>https://nearshore-it.eu/technologies/c-11-features-check-what-is-new/</link>
					<comments>https://nearshore-it.eu/technologies/c-11-features-check-what-is-new/#respond</comments>
		
		<dc:creator><![CDATA[Mateusz Leszner]]></dc:creator>
		<pubDate>Wed, 21 Sep 2022 06:12:00 +0000</pubDate>
				<category><![CDATA[Technologies]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">https://nearshore-it.eu/?p=22185</guid>

					<description><![CDATA[A new version of the C# programming language is released every year. C# version 11 will be released in November 2022 together with .NET 7. In this article, we will take a look at some of the important features of C# 11. Are you awaiting this update and wondering what features have been added? Read my mini-guide and see if they are valuable and in what way they could improve developers’ work with code.]]></description>
										<content:encoded><![CDATA[
<p></p>



<div class="table-of-contents">
    <p class="title">Go To:</p>
    <ol>
                    <li><a href="#The history of C#">1.  The history of C#</a></li>
                    <li><a href="#Upcoming-update-–-C--features-made-available-for-preview">2.  Upcoming update – C# features made available for preview</a></li>
                    <li><a href="#Generic-math-support">3.  Generic attributes</a></li>
                    <li><a href="#Generic-math-support">4.  Generic math support</a></li>
                    <li><a href="#New-lines-in-string-interpolations">5.  New lines in string interpolations</a></li>
                    <li><a href="#List-patterns">6.  List patterns</a></li>
                    <li><a href="#Raw-string-literals">7.  Raw string literals</a></li>
                    <li><a href="#Required-members">8.  Required members</a></li>
                    <li><a href="#Parameter-null-checking-–-postponed-after-preview">9.  Parameter null-checking</a></li>
                    <li><a href="#Auto-default-struct">10.  Auto-default struct</a></li>
                    <li><a href="#To sum up: developer, brace yourself for more C# 11 features!">11.  Summary</a></li>
            </ol>
</div>


<h2 class="wp-block-heading" id="The-history-of-C-">The history of C#</h2>



<ul class="wp-block-list">
<li>January 2002 – C# 1.0</li>



<li>November 2005 – C# 2.0</li>



<li>November 2007 – C# 3.0 (.NET Framework 3.0 and 3.5.)</li>



<li>November 2007 – C# 4.0</li>



<li>August 2012 – C# 5.0</li>



<li>July 2015 – C# 6.0</li>



<li>March 2017 – C# 7.0 (.NET Framework 4.7)</li>



<li>September 2019 – C# 8.0</li>



<li>November 2020 – C# 9.0 (.NET Framework 5)</li>



<li>November 2021 – C# 10.0</li>
</ul>



<h2 class="wp-block-heading" id="Upcoming-update-–-C--features-made-available-for-preview">Upcoming update – C# features made available for preview</h2>



<p>It seems that not so long ago we welcomed .NET 6 and C# 10, and already a new hand is to come in November 2022. Curious about what new features the latest version of C# will bring? </p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img fetchpriority="high" decoding="async" width="756" height="220" src="https://nearshore-it.eu/wp-content/uploads/2023/02/nearshore_2023.03.xx_graphic_1-1.png" alt="C#" class="wp-image-22193" style="width:756px;height:220px" title="C# 11 features – check what is new! 1" srcset="https://nearshore-it.eu/wp-content/uploads/2023/02/nearshore_2023.03.xx_graphic_1-1.png 756w, https://nearshore-it.eu/wp-content/uploads/2023/02/nearshore_2023.03.xx_graphic_1-1-300x87.png 300w, https://nearshore-it.eu/wp-content/uploads/2023/02/nearshore_2023.03.xx_graphic_1-1-495x144.png 495w" sizes="(max-width: 756px) 100vw, 756px" /></figure></div>


<p>Every developer can check them on their own in <strong>Visual Studio 2022 version 17.3</strong> (some of those features are available in earlier VS versions – e.g., Visual Studio 17.1). New features can also be checked in the .NET 7 SDK preview format (available to download on the .NET platform).</p>



<p><strong>Visual Studio 2022 – features for preview</strong></p>



<p>17.3</p>



<ul class="wp-block-list">
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#auto-default-struct" data-type="URL" data-id="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#auto-default-struct" target="_blank" rel="noreferrer noopener">Generic math supportauto-default structs</a></li>



<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#pattern-match-spanchar-or-readonlyspanchar-on-a-constant-string" data-type="URL" data-id="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#pattern-match-spanchar-or-readonlyspanchar-on-a-constant-string" target="_blank" rel="noreferrer noopener">Pattern match Span on a constant string</a></li>



<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#extended-nameof-scope" target="_blank" rel="noopener">Extended nameof scope</a></li>



<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#numeric-intptr-and-uintptr" target="_blank" rel="noreferrer noopener">Numeric IntPtr</a></li>



<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#utf-8-string-literals" target="_blank" rel="noreferrer noopener">UTF-8 string literals</a></li>



<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#required-members" target="_blank" rel="noreferrer noopener">Required members</a></li>
</ul>



<p>17.2</p>



<ul class="wp-block-list">
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#raw-string-literals" target="_blank" rel="noreferrer noopener">Raw string literals</a></li>



<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#improved-method-group-conversion-to-delegate" target="_blank" rel="noreferrer noopener">Improved method group conversion to delegate</a></li>



<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/warning-waves#cs8981---the-type-name-only-contains-lower-cased-ascii-characters" target="_blank" rel="noreferrer noopener">Warning wave 7</a></li>
</ul>



<p>17.1</p>



<ul class="wp-block-list">
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#generic-attributes" target="_blank" rel="noreferrer noopener">Generic attributes</a></li>



<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#newlines-in-string-interpolations" target="_blank" rel="noreferrer noopener">Newlines in string interpolation expressions</a></li>



<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#list-patterns" target="_blank" rel="noreferrer noopener">List patterns</a></li>
</ul>



<p>Source: <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11" target="_blank" rel="noreferrer noopener">Microsoft</a></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="756" height="198" src="https://nearshore-it.eu/wp-content/uploads/2023/02/nearshore_2023.03.xx_graphic_2.png" alt="C#" class="wp-image-22195" title="C# 11 features – check what is new! 2" srcset="https://nearshore-it.eu/wp-content/uploads/2023/02/nearshore_2023.03.xx_graphic_2.png 756w, https://nearshore-it.eu/wp-content/uploads/2023/02/nearshore_2023.03.xx_graphic_2-300x79.png 300w, https://nearshore-it.eu/wp-content/uploads/2023/02/nearshore_2023.03.xx_graphic_2-495x130.png 495w" sizes="(max-width: 756px) 100vw, 756px" /></figure></div>


<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p>Below you will find an overview of, in my view, the most interesting ones.&nbsp;</p>



<h2 class="wp-block-heading">Generic attributes</h2>



<p>C# version 11 has been equipped with a generic attribute feature. This allows you to create a generic class deriving a <strong>System.Attribute</strong>, which facilitates creating attributes requiring <strong>System.Type</strong> parameter. In earlier versions of C#, a developer had to construct a more complex solution of attributes with the Type parameter in the constructor. See the following listing:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public class TypeAttribute : Attribute
{
   public TypeAttribute(Type t) => ParamType = t;
   public Type ParamType { get; }
}
[TypeAttribute(typeof(string))]
public string Method() => default;
With C# 11 the same can be achieved simpler:
public class GenericAttribute&lt;T> : Attribute { }
[GenericAttribute&lt;string>()]
public string Method() => default;</pre>



<p>Removing the obligatory use of typeof(…) in attributes and replacing it with generic types eliminates the problem of ensuring that type inside typeof() meets attribute requirements. This feature was planned to be released in earlier versions of C#, but due to incompatibility with dev tools, Microsoft decided to postpone it. But now it’s time for generic attributes to show up.</p>


</style><div class="promotion-box promotion-box--image-left "><div class="tiles latest-news-once"><div class="tile"><div class="tile-image"><img decoding="async" src="https://nearshore-it.eu/wp-content/uploads/2024/06/BigCTA_MarekCzachorowski.jpg" alt="BigCTA MarekCzachorowski" title="C# 11 features – check what is new! 3"></div><div class="tile-content"><p class="entry-title client-name promotion-box__headline2">Elevate Your Application Development</p>
<p class="promotion-box__description2">Our tailored Application Development services meet your unique business needs. Consult with <strong>Marek Czachorowski</strong>, Head of Data and AI Solutions, for expert guidance.</p>
<a class="btn btn-primary booking" href="https://outlook.office365.com/book/BookameetingwithMarek@gfi.fr/" target="_blank" rel="noopener">Schedule a meeting</a></div></div></div></div>



<h2 class="wp-block-heading" id="Generic-math-support">Generic math support</h2>



<p>This label hides a few new features which make up the generic math support. There are:</p>



<ul class="wp-block-list">
<li>static virtual and static abstract members in interfaces,</li>



<li>checked user-defined operators,</li>



<li>relaxed shift operators,</li>



<li>unsigned right-shift operator.</li>
</ul>



<p>This feature allows developers to use static APIs from generic code. For example, you can implement the sum or average calculator for different numeric types with a single implementation. You can find more details on new syntax in the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface#static-abstract-and-virtual-members" target="_blank" rel="noreferrer noopener">C# documentation</a></p>



<p>Numeric types implement a new interface INumber, which contains properties T.One and T.Zero. This can be used to implement generic sum or average calculators for many numeric types, keeping the DRY principle. The sum method may be implemented as + operator too. You can find it in the following listing:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">T Sum&lt;T>(T[] values) where T : INumber&lt;T>
{
  
T result = T.Zero;
  
foreach (var value in values)
  
{
      
result += value;
  
}
  
return result;
}
 
T Avg&lt;T>(T[] values) where T : INumber&lt;T>
{
  
var sum = Sum(values);
  
var count = T.Zero;
  
for (var i = 0; i &lt; values.Length; i++)
  
{
      
count += T.One;
  
}
  
return sum / count;
}
var ints = new[] {1, 2, 3, 4, 5};
var doubles = new[] { 0.1, 0.7, 1.1, 8.3 };
 
var sumOfInts = Sum(ints);
var avgOfInts = Avg(ints);
var sumOfDoubles = Sum(doubles);
var avgOfDoubles = Avg(doubles);</pre>



<p>Generic math created other requirements in C# 11:</p>



<ul class="wp-block-list">
<li><strong>unsigned right-shift operator</strong> – using operator >>> you can force any right-shifts to unsigned right-shifts, which means that the high-order empty bit positions are always set to zero, regardless of the type of the left-hand operand</li>



<li><strong>relaxed shift operator</strong> – starting from C# 11, the second operand of shift doesn’t have to be int or implicitly convertible to int, which allows you to use that operator in generic math interfaces</li>



<li><strong>checked (and unchecked) user-defined operators</strong> – checked and unchecked arithmetic operators may be defined, and the compiler generates calls to the correct variant based on the current context</li>
</ul>



<h2 class="wp-block-heading" id="New-lines-in-string-interpolations">New lines in string interpolations</h2>



<p>String interpolation was introduced in C# 6 with Visual Studio 2015. String interpolation replaces <strong>String.Format().</strong> The format of the interpolated string is a string inside double quotes preceded by $. Inside that string, you can pass the parameters or method executions in brackets {}.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$"{&lt;interpolationExpression>[,&lt;alignment>][:&lt;formatString>]} other text in string”</pre>



<p>Now, in C# 11, string interpolation gets a small update – it allows you to contain new lines inside the formulas. Previously, some long formulas, containing LINQ queries might have been unreadable. But no more! With the next release of C#, we will be able to use new lines, and then, complex string interpolated formulas will look much better.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">var list = new[] {"Apple", "Banana", "Orange", "Grapefruit"};
var str = $"Third letters of fruits starts with B: {list
   .Where(fruit => fruit.StartsWith("B"))
   .Select(fruit => fruit[2])
   .FirstOrDefault()}";</pre>



<h2 class="wp-block-heading" id="List-patterns">List patterns</h2>



<p>Pattern matching means for example matching an object to a type in switch cases, but not only. For more general details about pattern matching see the Microsoft documentation. Pattern matching was introduced with C# 7 with the <strong>is </strong>keyword allowing you to map an object to a type and <strong>when </strong>keyword to be used in switch statements.</p>



<p>Then, C# 7.1 extended type patterns to support generic types. C# 8 have improved pattern matching by adding property patterns allowing you to match type and property. The next release of C# brought relational patterns. So since C# 9 we can use<strong> &gt;, &lt;, &gt;=, &lt;=</strong> in property matching. C# 9 enabled use of logical operators <strong>and, or, not, is null, is not null</strong> in pattern matching and <strong>var </strong>keyword for creating variables. C# 10 have extended property patterns and now it’s time for C# 11. List patterns – matching a sequence of elements. You can match a list using some items as a pattern. Discard pattern <strong>(_)</strong> is used for matching any single elements, and the range pattern <strong>(..)</strong> is used to match any sequence of zero or more elements.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">var list = new[] {
    new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, // A
    new[] {1, 2, 3, 5, 7, 10}, // B
    new[] {0, 2, 3, 8, 10, 10}, // C
    new[] {3, 4, 10}, // D
    new[] {1, 4, 10, 15, 21, 3, 10}, // E
    new[] {-1, 2, 3, 5, -1, 10} // F
};
•    Match complete list:
list.Where(x => x is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // matches list A
•    Match some elements:
list.Where(x => x is [_, 2, 3, _, _, 10]); // matches lists B, C, F
•    Match range:
list.Where(x => x is [1, 2, .., 10]); // matches lists A, B
•    Mixed match for elements and range:
list.Where(x => x is [1, _, .., 10]); // matches lists A, B, E
•    Match list starting with negative number:
list.Where(x => x is [&lt; 0, ..]); // matches list F</pre>



<h2 class="wp-block-heading" id="Raw-string-literals">Raw string literals</h2>



<p>Raw string literals could be multiline, contain quotes, and other special characters without escape sequence and they can contain string interpolations. Here you can find some examples:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">var line2 = "line2 from another variable";
 
var str1 = """
line1
{line2} - won't be replaced
line3
       line4 
       
 line6
""";
 
var str2 = $"""
line1 from second string
{line2}
line3
""";
 
var str3 = $$"""
using { in line 1}
{{line2}}
{line2} this won't be replaced
{{{line2}}} you can use it like this
""" ;</pre>



<h2 class="wp-block-heading" id="Required-members">Required members</h2>



<p>Developers gain the option to mark properties and fields using the modifier required. This lets us ensure those values are initialized in the constructor. Then you have to set attribute SetsRequiredMembers to the constructor, which should initialize the values. You can have constructors without the attribute too, and those constructors don’t have to initialize required values.</p>



<p>Required members must be initialized, but they may be initialized to null. If the type is a non-nullable reference type, the compiler issues a warning if you initialize the member to null. The compiler issues an error if the member isn’t initialized at all.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public required string RequiredString { get; set; }
[SetsRequiredMembers]
public RequiredDemo()
{
   
    RequiredString = String.Empty;
}</pre>



<h2 class="wp-block-heading" id="Parameter-null-checking-–-postponed-after-preview">Parameter null-checking – postponed after preview</h2>



<p>There was a plan to add a parameter null checking feature, but it has been postponed for now due to developers’ objections on the <a href="https://euc-word-edit.officeapps.live.com/we/(https:/github.com/dotnet/csharplang/blob/main/meetings/2022/LDM-2022-04-06.md#parameter-null-checking)." target="_blank" rel="noreferrer noopener">C# Language Design Meeting on April 6th 2022.</a> The feature was made available for preview and widely discussed. While many developers were satisfied, others raised objections of all kinds.</p>



<h2 class="wp-block-heading" id="Auto-default-struct">Auto-default struct</h2>



<p>Before the release of C# 11, programmers had to create struct constructors with parameters to ensure that all fields are initialized. But C# 11 will make it different. For now, you can create a struct with parameterless constructor, that doesn’t explicitly initialize structs’ members.</p>



<p>Then the compiler takes its role and ensures that all not yet initialized fields are initialized to their default value. The compiler adds necessary code at the beginning of the constructor body, before the fields are accessed. If this is accessed before the initialization of all fields, the struct is initialized to the default value before the constructor body executes. You can read more about struct initialization and default values on the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct#struct-initialization-and-default-values" target="_blank" rel="noreferrer noopener">Microsoft C# documentation webpage.</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public readonly struct AutoDefaultStruct
{
    public int IntegerValue { get; }
    public string StringValue { get; }
    public double DoubleValue { get; }
    public AutoDefaultStruct()
    {
        //IntegerValue = default;
        //StringValue = default;
        //DoubleValue = default;
        // doesn't have to set values for all fields, default initializations will be added at the beginning of constructor by compiler
    }
}
var structDemo = new AutoDefaultStruct(); </pre>



<h2 class="wp-block-heading">To sum up: developer, brace yourself for more C# 11 features!</h2>



<p>The above-mentioned are the most important C# 11 features that you can use in the preview version even today. Of course, the full list of changes is longer including the extended nameof scope, pattern matching for <strong>Span&lt;char></strong> and <strong>ReadOnlySpan&lt;char></strong>, aliases for<strong> IntPtr and UIntPtr</strong>, and more. You can find the technical documentation on GitHub.</p>


</style><div class="promotion-box promotion-box--image-left promotion-box--full-width-without-image"><div class="tiles latest-news-once"><div class="tile"><div class="tile-content"><p class="promotion-box__description2"><strong>Consult your project directly with a specialist</strong></p>
<a class="btn btn-primary booking" href="https://outlook.office365.com/book/BookameetingwithMarek@gfi.fr/" target="_blank" rel="noopener">Book a meeting</a></div></div></div></div>



<p><strong>Also read: </strong></p>



<ul class="wp-block-list">
<li><a href="https://nearshore-it.eu/articles/technologies/microservices-architecture-explained-is-it-still-a-revolution-or-already-standard-in-it-projects/" data-type="URL" data-id="https://nearshore-it.eu/articles/technologies/microservices-architecture-explained-is-it-still-a-revolution-or-already-standard-in-it-projects/" target="_blank" rel="noreferrer noopener">Microservices architectures – still a revolution or already standard in IT projects?</a></li>



<li><a href="https://nearshore-it.eu/articles/technologies/azure-durable-function-in-serverless-programming/" data-type="URL" data-id="https://nearshore-it.eu/articles/technologies/azure-durable-function-in-serverless-programming/" target="_blank" rel="noreferrer noopener">Azure Durable Function in serverless programming</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://nearshore-it.eu/technologies/c-11-features-check-what-is-new/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
