• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Dotnet Stuff

  • Home
  • Articles
  • Tutorials
  • Forums
  • Career Advice
  • Jobs
  • .NET FAQs
  • News
  • Privacy Policy

What is string interpolation in C#

Interpolating expression values into literal strings is possible with the technique known as string interpolation. String interpolation feature was introduced in C# 6. A string is considered as an interpolated string if it contains the interpolation expression.

Using string interpolation in C# is the subject of this article. String is identified as an interpolated string in C# by the special character $.

Variable expansion, variable interpolation, and variable substitution are other terms for this technique. String literals containing one or more placeholders that are replaced by corresponding values are evaluated in this process.

Python, Perl, PHP, Ruby, Java, Scala, and many other programming languages support string interpolation.

The reason for utilizing an interpolated string is that it is easier to do the string concatenation without having to format it.

Previously, we were using formatted strings instead of interpolation.

Let’s look at an example of a formatted string and an interpolated string.

string fistName = “Rajeev”;

string lastName = “Kumar”;

Using the string formatting option we can write,

Console.WriteLine(“Hello {0} {1}”, fistName, lastName);

C# String Interpolation

But by using the string interpolation feature we can write as below,

Console.WriteLine($”Hello {fistName} {lastName}”);

Both the above instructions will produce the same output as given below,

Hello Rajeev Kumar

The interpolated string starts with $” and enclose variable names in curly braces “{ }”.

The interpolated string has a three part syntax. They are, Interpolation Expression, Alignment, and FormatString.

Interpolation Expression

We have seen in the above example which is enclosed by curly braces “{ }”.

The alignment will define the minimum no of characters in the string and align the result of that interpolation expression result accordingly.

Alignment

Alignment parameter will take integer value either positive or negative, if it’s positive then it will align text to the left else align text to the right.

formatString

formatString will format the string, it will support all the standard formation of the string.

Let’s see an example for the alignment parameter as below

Console.WriteLine($”{“Left Align Text”,-20}”);

Console.WriteLine($”{“Right Align Text”,20}”);

Above both instructions will produce output as below:

Left Align Text

Right Align Text

Now take a look at  an example for formatString parameter as below

decimal sampleValue = 590.1234m;

Console.WriteLine($”The above given value is {sampleValue:N2}”);

Above line will produce output as below:

The above given value is 590.12

I hope this post will give you a basic idea about the string interpolation feature in C#.

Summary

This post covered C# string Interpolation which is concatenating, formatting, and manipulating strings using C# string interpolation. As part of the string interpolation operation, we can use objects and expressions. Hope you found this article helpful.

What Is The Use Of Volatile Keyword In C#

A variable’s value must never be cached in C#  because it may change outside of the scope of the program itself. Compiler optimizations that may cause problems if the variable changes “outside of its control” will be avoided.
But in case if we need a field variable to be modified within the program by means such as the operating system, concurrently executing thread or the hardware then we can use Volatile keyword for that field.

Volatile Keyword in C #

Understanding what happens when a variable is not volatile is critical to understanding what volatile does.

Non-volatile Variable

There will always be a local copy of the variable in each thread’s cache when accessing a non-volatile variable between two threads. There will be no way for the thread 1 to see any changes made in its local cache by thread 2.

Volatile Variable in C#

Volatile Modifier ensures that one thread retrieves the most up to date value written by another thread without the use of the Lock statement.

Since variables are prone to change it’s important to note that when a variable is declared volatile, it means that threads should not store the value of the variable in their own memory, or in other words, the values of these variables should not be trusted by other threads.

When to Use Volatile Variables in C#?

Any time a variable’s value is modified by another thread, process, or outside the program, you want all threads to receive the most up-to-date copy of the variable’s value.

Semantics have been added to volatile field readings. In other words, any subsequent memory reads will be preceded by the read from the volatile variable. For weakly ordered CPUs, it will use a special instruction to flush any reads that occur after the volatile read but were speculatively started early, or the CPU could prevent them from being issued early in the first place, by preventing any speculative load occurring between the issue of an acquire and its retirement.

All memory writes to the volatile variable will be delayed until all previous memory writes have been made visible to other processors.

Only class or struct level fields can use the volatile keyword.

There is no way to make a local variable as volatile.

C# Volatile Keyword  Example

Volatile keyword can be used for fields of the following types

  • Basic primitive types such as  short, ushort, int, uint, float, char, sbyte, byte and bool.
  • IntPtr and UIntPtr.
  • Enum type with base types such as short, ushort, int,uint,byte orsbyte
  • Reference type objects
  • Pointers
  • Generic reference type parameters

We can declare a variable volatile variable by using the modifier keyword volatile for the variable. See below declarations,

private volatile int intVolatile;

static volatile bool isSuccess;

We can not mark types such as long and double as volatile since there is no guarantee that reads and writes to the fields of these types will be atomic. The Interlocked class members or the lock statement can be used to protect multi-threaded access to these kind of type fields.

Cons Of Volatile Keyword in C#

In many cases, the volatile keyword helps in thread safety, but by itself it will not solve all your concurrency problems.

You can reorder the code if you don’t use volatile variables. The compiler is free to write to the cache value of volatile variables rather than reading from the main memory. No reordering or optimization can take place when declared variables as volatile.

A variable or object marked as volatile does not mean that you don’t need to use the lock keyword in your program at all. It is not a substitute for the lock keyword. 

Using a volatile read on a multiprocessor system doesn’t guarantee that you’ll get the most recent value written to that memory location. Furthermore, a volatile write operation does not guarantee that other processors will see the value that was written.

FAQ on volatile keyword C#

What are the keywords in C#?

The compiler uses predefined, reserved identifiers known as keywords. But in case to use them as identifiers in code, we must prefix them with @.

Examples of few keywords in C# are,  namespace, class, delegate, abstract, char, const, enum etc.

What is volatile keyword used for?

Multi threaded programs benefit from this. It’s possible to change the value of a variable using the volatile keyword from different threads. Multiple threads can use a method and instance of the classes at the same time without any problem

Volatile keyword reduces concurrency issues.

Will volatile fields cause a performance problem?

There will be performance impact in certain cases. If possible, it is best to avoid using volatile keyword.

Summary

In this article we covered what is volatile keyword in C#, advantages of volatile keyword  and its uses. Hope this article helped you. Leave your feedback in the comments section below.

Get System IP Address Using C#

When it comes to networking, IP addresses are a must-have. While it may not be as critical from a C# perspective, we will look about the System as a result of this. There’s a lot of .NET namespace involved in here.

We may only needed the IP address of a local device. So check the article below to see how we can Get IP address of the system using C# or VB.NET.

Get IP Address in .NET

It’s important to know whose IP address we’re looking for in order to get the IP address we need.

Ipconfig is the command that can be used to find your IP address. To get the basic network information like host name, IP address, and gateway, you can run this command on your Command Prompt in administrator mode.

We have few System.Net classes to deal with this system IP address. Hence, first need to use the namespace System.Net.

The GetHostName() method can be used to obtain the machine name (or host name) from system. This is a part of the DNS class, as well. The IP address of the Host is now available.

The GetHostByName() method and the AddressList array are required for this. GetHostByName’s argument is “host name,” and so on.

Get Client IP Address In ASP.NET

The IP address of your client can be obtained by calling Request.UserHostAddress in ASP.NET.

We get multiple IP addresses if you use a Windows application to get your local IP address. The netid part of an IP address can be compared to any other IP address in order to find a specific IP address you know.

var addressListArray = Dns.GetHostAddresses(Dns.GetHostName()
if (addressListArray).Length > 0)
{
   ipAddress = addressListArray[0].ToString();
}

Get IP Address Using C# Winforms – Sample Code

Dns.GetHostEntry(Dns.GetHostName()).AddressList
    .Where(ips => !ips.IsIPv6LinkLocal && !ips.IsIPv6Multicast && !ips.IsIPv6SiteLocal)
    .First()
    .ToString();

Get IP Address Using VB.NET – Sample Code

Sub Main(args As String())
  Dim hosts() As systemIpAddresses = Dns.GetHostAddresses(Dns.GetHostName())
  For Each ipAddress As  systemIpAddresses  In hosts
     If ipAddress.AddressFamily = AddressFamily.InterNetwork Then
            Console.WriteLine($"IP {ipAddress} is IPv4")
     End If
  Next
End Sub

FAQ on Get System IP .NET

How to Find Client IP address in ASP.NET ?

Apart from the snippet explained above in the article for getting the system IP address, we can use the two HTTP header fields HTTP_X_FORWARDED_FOR and REMOTE_ADDR for obtaining the IP address of the client connected to internet.

HTTP_X_FORWARDED_FOR – gets the originating IP Address of the client

REMOTE_ADDR – gets IP address of the remote machine connected

    var ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
  
    if (string.IsNullOrEmpty(ipAddress))  
    { 
       ipAddress = Request.ServerVariables["REMOTE_ADDR"];  
    } 

How do I find my host name C#?

Make a console application in C# and use the below procedure to get IP address using C#

static void Main(string[] args)
{
  //find host name in C#
  string myHost= Dns.GetHostName(); 
  Console.WriteLine( myHost ); 

  //write the system IP 
  Console.WriteLine(Dns.GetHostByName(myHost).AddressList[0].ToString());  
  Console.ReadKey();
}

Summary

In this post we covered on how to get system IP address using C# or VB.NET. Hope you found this post helpful. Post your feedback in the comments sections.

C# Fixed Size Buffer

C# Fixed Array

This article covers declaring a C++ style fixed-size structure was difficult in earlier versions of C#. But with advanced versions of C# fixed size array are possible. We are not discussing here about the array length or static or dynamic array which deals with an array capacity.

In .NET normally arrays are reference types and an array declared as part of a structure doesn’t physically exist inside the struct.

Only a reference to the array is placed inside the structure, which points to the original location of the array on the heap. Lets look in detail on C# fixed size array in struct.

Fixed Size Buffer In C#

In C# 2.0, it’s now possible to declare arrays in structure as fixed-sized inside unsafe code blocks. Fixed arrays will typically be part of a structure that’s passed to a native API.

public unsafe struct CharArray

Buffers with a set size. The fixed statement in C# allows you to create a data structure buffer with a fixed size array. All that’s required is for the array type to be of short, int, long, sbyte, ushort, uint,  ulong, float, double, char, bool or byte.

When writing methods that interact with data sources from other programming languages or platforms, fixed size buffers come in handy.

C# Fixed Size Buffer Sample

Lets see how we can define fixed size array in C# to have them in struct

public unsafe struct DataStructSample
{
     public int aNumber;
     public fixed float aArray[5];
}

Benefits Of Fixed Size Buffer In C#

As in C++, the size of the built-in arrays must be maintained. The same is true for fixed size buffers in C#. This data type is similar to inline array in functionality.

Fixed size buffers in C# will someway  benefits like static code checking. Because they aren’t a standard part of C#, they’re a pain to use. As a result, it’s probably best to keep struct’s size as part of it. Either that or use a collection such as Array in C#. Fixing the buffer and then making it part of other structures with other data could be an alternative solution.

FAQ on C# Fixed Arrays

How to Declare Fixed-size array of struct type in C#?

In C# we can have fixed size buffer of the types
long, int, short, ushort, uint, ulong, bool, byte, char,sbyte, float or double.

Example,

unsafe struct FixedSizeArraySample 
{ 
   public int intNumber;
   public fixed Byte abyte[15];
   fixed float fixedArray[4]; 
}

Summary

This article covered C# Fixed Size Buffer. When writing methods that interact with data sources from other programming languages or platforms, fixed size buffers come in handy. Any attributes or modifiers allowed for regular struct members can be applied to the fixed array. Hope you found this article helpful. Share your thought on C# fixed arrays in the comment section below.

Covariance & Contravariance

C# Version History | C# Evolution and Features

C# was developed in the year 2002 with the .NET Framework 1.0 and has since continued to develop with enhanced features and performance.

C# is a general-purpose, contemporary, and object-oriented programming language. It was created by Microsoft as part of the.NET program and was authorized by the ECMA (European Computer Manufacturers Association) and the ISO (International Standards Organization).

while writing this article, C# 9.0 is the most recent version.C# 9.0 was released in September 2020 along with .NET 5 platform. If you wish to download .NET 5.0 and try out the features check it from here, download .NET 5

We are eagerly anticipating the release of the language’s newest version, too. There has not yet been an official release date announced for C# 10.0, though it is expected to launch alongside the .NET 6 in November.

Few expected core features in C# version 10 are

Required Properties to make a property required at the time of defining a class

Null Parameter Checking wherein the code automatically verifies whether the param Object is null

Global Usings to define global usings for the whole project for all common usings

File Namespaces enable defining a namespace of the class on the file level

Field Keyword permit the caller to modify the members while construction is in progress

C# Version History Table

This table shows the noteworthy features that were introduced in each new release of C#, which will help as a quick reference guide.

C# Version.NET Framework VersionVisual Studio VersionCore Features
C# 1.0.NET Framework 1.0Visual Studio 2002Initial Release. Basic Object-Oriented Programming features such as,
Classes
Structs
Properties
Events
Interfaces
Delegates
Statements
Expressions
Attributes
C# 1.2.NET Framework 1.1Visual Studio 2003Minor enhancements on C# 1.0
C# 2.0.NET Framework 2.0Visual Studio 2005Partial classes
Generics
Anonymous methods
Iterators
Nullable types
Properties with Private setters
Delegates with Method group conversions
Covariance and Contra-variance
Static classes
C# 3.0.NET Framework 3.0\3.5Visual Studio 2008Implicitly typed local variables
Auto-Implemented properties
Object Initializers
Collection initializers
Anonymous types
Extension methods
Query expressions
Lambda expressions
Expression trees
Partial Methods
C# 4.0.NET Framework 4.0Visual Studio 2010Dynamic keyword introduced
Named Parameters & optional arguments
Generic covariant and contravariant
Embedded interop types
C# 5.0.NET Framework 4.5Visual Studio 2012/2013Asynchronous members
Caller information attributes
C# 6.0.NET Framework 4.6Visual Studio 2013/2015Expression Bodied Methods
Auto-property initializer
name of Expression
Primary constructor
Await in the catch block
Exception Filter
String Interpolation
C# 7.0.NET Core 2.0Visual Studio 2017Tuples
Out variables
Discards
Pattern Matching
Local functions
Generalized async return types
Digital Separators
Binary literals
Ref returns and locals
C# 7.1.NET CoreVisual Studio 2017Default literal expression
Async main
Inferred Tuple element names
C# 7.2.NET CoreVisual Studio 2017Non-trailing named argument
Private protected access modifier
Leading underscores in numeric literals
C# 7.3.NET CoreVisual Studio 2018Using additional generic constraints
Reassigning ref local variables
Accessing fixed fields without pinning
C# 8.0.NET Core 3.0Visual Studio 2019Readonly members
Default interface methods
Pattern matching enhancements
Using declarations
Static local functions
Readonly struct members
Default interface members
Asynchronous streams
Switch expressions
Indices and ranges
Disposable ref struct
Nullable reference types
Null coalescing assignment
Unmanaged constructed types
C# 9.0.NET 5Visual Studio 2019Immutable representation of data shapes
New Record types
Init only setters
Top-level statement
Functions pointers
Module Initializers
Covariant return types.
Native Sized integers
C# 10.0 .NET 6Visual studio 2022Null Parameter Checking
Required Properties
Field Keyword
Global Usings
File Namespaces
Const interpolated strings.
Record types can seal ToString()
Allows both declaration and assignment
in the same deconstruction.
AsyncMethodBuilder attribute
C#.NET Version History & Features

Summary

In this article, we had a brief overview of the C# version history, and the features included in each version of C#. This history of C# will be useful for quick reference. Hope you find this article helpful. Leave your valuable feedback below.

C# 3d array

In C# arrays can have multiple dimensions, arrays with more than one dimension. C# can support nearly 32 dimensions for multidimensional arrays.

To declare a multidimensional array, use commas between the square brackets to delimit the array’s dimensions. Arrays can be classified according to their dimensions.

The dimension of an array can be identified by counting the commas. The number of commas in a multidimensional array equals one less than the number of dimensions.  For example [,] is a 2D array, [, ,] is a 3D array, [, , ,] is a 4D array, so on and so forth.

C# 3D Array Examples

See the examples of C# 3D Array

//3D Array C#, Three-dimensional array in C#
int[, ,]  Csharp3dArray = new int[,,] { { { 20, 25, 30 }, { 30, 35, 40 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
//C# 3d array with dimensions specified.
int[, ,] 3dArrayCsharp = new int[2,2,3] { { { 20, 25, 30 }, 
          { 30, 35, 40 } },{ { 7, 8, 9 }, { 10, 11, 12 } } };

More Examples of  C# 3d Arrays below..

C# 3d array with 1 row, 2-dimensional array [2,3]

int[, ,] 3darray1 = new int[1, 2, 3]{
{ { 4, 5,6}, { 3, 4,5} } };

C# 3d array with 2 row, 2 dimensional array [3,2]

int[, ,] 3darray2 = new int[2, 3, 2]{
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} },
{ {5, 6}, {7, 8} }
};

 

C# 3d array with 2 rows, 2-dimensional array [2,3]

int[, ,] 3darray3 = new int[2, 2, 3]{
{ { 1, 2, 3}, {4, 5, 6} },
{ { 7, 8, 9}, {10, 11, 12} }
};

C# 3d array with 3 rows of 2 diamensional array [3,3]

 

int[, ,] 3darray3 = new int[3, 3, 3]{
{ { 1, 2, 3}, {4, 5, 6}, {4, 5, 6}},
{ { 7, 8, 9}, {10, 11, 12}, {15, 16, 17}},
{ { 7, 8, 9}, {20, 21, 22},{30, 31, 32} }
};

 

The first rank gives the indication of the number of rows of the internal 2D arrays.

Summary

In this post, we explained C# 3d arrays and few examples. Hope this article was helpful for you. Please share your valuable feedback on 3d arrays in C# in the comments section

  • Go to page 1
  • Go to page 2
  • Go to page 3
  • Interim pages omitted …
  • Go to page 8
  • Go to Next Page »

Primary Sidebar

Recent Topics

  • What is the Difference Between IEnumerable and IQueryable in C#
  • How to remove Header of the XML file in C#?
  • What is DBMS?
  • What is RDBMS?
  • What is asp net framework ?
Log In
Increase Your Leadership Skills, Influence, and Power with Top Leadership courses starting at just $11.99.

Recent Posts

  • .NET Core Version History | Release History of .NET Core
  • What is string interpolation in C#
  • What Is The Use Of Volatile Keyword In C#
  • Get System IP Address Using C#
  • SQL Server Interview Question and Answers
  • C# Fixed Size Buffer
  • OWIN in ASP.NET Core| What is OWIN in .NET?
  • C# Version History | C# Evolution and Features
  • What is ASP.NET Core Module
  • C# 3d array

Recent Forum Topics

  • What is the Difference Between IEnumerable and IQueryable in C#
  • How to remove Header of the XML file in C#?
  • What is DBMS?
  • What is RDBMS?
  • What is asp net framework ?

Forums

  • .NET Framework
  • ASP.NET
  • C#
  • SQL

Recent Topics

  • What is the Difference Between IEnumerable and IQueryable in C#
  • How to remove Header of the XML file in C#?
  • What is DBMS?
  • What is RDBMS?
  • What is asp net framework ?

© Copywright 2017 Dotnetstuffs All Rights Reserved