Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, March 9, 2026

C# - a callable with custom data

Have you ever wondered if a C# delegate can contain a custom field or property?

No, it can't, classes that are delegates are closed for extensions - one would say.

In other words, C# can't mimick JavaScript, where you can attach anything to a function - this pattern is useful when implementing some functional patterns like memoization.

A side note - TypeScript is flexible enough, you can have a type that describes an object that is callable and yet contains some data:

type Callable = {
    description: string;
    (a: string): string;
}

But let's go back to C#. Is it really not possible? Well, not directly. However, there's a clever way of forcing an object of any shape to be implicitely convertible to a function type. And this implicit conversion would take place when the object would be passed to an auxiliary function, as an argument!

public class Program
{
	/// <summary>
	/// Auxiliary executor
	/// </summary>
	static string Executor(Func<string, string> logic, string input)
	{
		return logic(input); 
	}

	static void Main(string[] args)
	{
		Callable c = new Callable()
		{
			Description = "custom description"
		};

		string result = Executor(c, "FooBar");
		Console.WriteLine(result);
	}
}

public class Callable
{
	public string Description { get; set; }

	/// <summary>
	/// Internal implementation details of the "callable" interface
	/// </summary>
	private string Invoke(string param) => $"Argument: {param}, this.Description: {Description}";

	/// <summary>
	/// Public implicit conversion
	/// </summary>
	public static implicit operator Func<string, string>(Callable c) => c.Invoke;
}

Monday, March 17, 2025

A fairy tale of misusing the C# typesystem

Once upon a time in a kingdom far far away someone wrote a code that required two string arguments:

    public class Worker
    {
        public void DoWork( string name, string surname )
        {
            Console.WriteLine( $"{name} {surname}" );
        }
    }

All the people used the code for years without any issues:

    new Worker().DoWork( "john", "doe" );

Then, someone in a hurry did something bad which should never happen. Arguments were swapped in a call:

    new Worker().DoWork( "doe", "john" );

Consequences were severe.

The culprit was tried and expelled from the kingdom. The king called for his best wizards and asked them to do something so that it never ever happens in the future.

One of the wizards suggested that introducing types would make it clear of what real intentions of arguments are:

    public class Name
    {
        public Name( string value )
        {
            this.Value = value;
        }

        public string Value { get; set; }

        public override string ToString()
        {
            return this.Value;
        }
    }

    public class Surname
    {
        public Surname( string value )
        {
            this.Value = value;
        }

        public string Value { get; set; }
        public override string ToString()
        {
            return this.Value;
        }
    }


    public class Worker
    {
        public void DoWork( Name name, Surname surname )
        {
            Console.WriteLine( $"{name} {surname}" );
        }
    }

Initially people complained a bit but then started to get used to the new calling convention:

    new Worker().DoWork( new Name( "john" ), new Surname( "doe" ) );

The problems were gone. Everyone was happy.

Years passed, some wizards were gone, new wizards came to the kingdom. One of new wizards reviewed the code and came up with an idea.

- Why this convention is that awkward, why wrap strings in auxiliary types? - thought the wizard.

And he came up with an idea to add implicit conversion operators:

    public class Name
    {
        public Name( string value )
        {
            this.Value = value;
        }

        public string Value { get; set; }

        public override string ToString()
        {
            return this.Value;
        }

        public static implicit operator Name( string value )
        {
            return new Name( value );
        }
    }

    public class Surname
    {
        public Surname( string value )
        {
            this.Value = value;
        }

        public string Value { get; set; }
        public override string ToString()
        {
            return this.Value;
        }

        public static implicit operator Surname( string value )
        {
            return new Surname( value );
        }
    }
 

The new wizard was very proud of himself. He barely told anyone of his conversion operators so everyone else was still using the well established convention:

   new Worker().DoWork( new Name( "john" ), new Surname( "doe" ) );

But, since the conversion was now implicit, the wizard was able to make his own code shorter:

   new Worker().DoWork( "john", "doe" );

Years passed, new people arrived and then, someone in a hurry did something bad which should never happen. Arguments were swapped in a call:

    new Worker().DoWork( "doe", "john" );

Consequences were severe.

Was the culprit tried and expelled from the kingdom, same as last time?

Not really, the Wizard Council blamed the new wizard, the one who introduced both implicit conversion operators.

He was tried and expelled from the kingdom. His changes were reverted forever and everyone lived happily ever after.


This is based on a (almost) true story.

Friday, October 25, 2024

Using Task.WhenAny to time bound a task

Just for a future reference - suppose a task should not take longer than ... but there's still a need to finish it. It's just the caller that cannot wait longer
One of use cases involves a REST service where you provide the server part. There's a client that should get an answer in max X seconds, regardless of whether the actual task finishes or not. You want a timer that runs together with the task and in case any of the two finishes first, you want to know which one was it.
Let's stage actors first:
public class TaskExperiments
{
	public async Task<string> DelayWithEcho( int ms, string echo, string id )
	{
		await Task.Delay( ms );
		Console.WriteLine( echo );

		return id;
	}
}
This one above is supposed to be a factory of tasks. A task is given a time and an id so that when it finishes, I know the id.
Now, the runner:
var e = new TaskExperiments();

var t1 = e.DelayWithEcho( 5000, "Task1 after 5000ms - time constraint", "i1" );
var t2 = e.DelayWithEcho( 3000, "Task2 after 3000ms - actual task",     "i2" ); 

var t  = await Task.WhenAny( t1, t2 );
var id = await t;

Console.WriteLine( $"Finished one of the two : {id}" );
As you can see, Task.WhenAny is used and then the result task is awaited once again to get the id.
Running this gives:
Task2 after 3000ms - actual task
Finished one of the two : i2
Task1 after 5000ms - time constraint
Now change the second to last longer:
...
var t2 = e.DelayWithEcho( 7000, "Task2 po 7000ms - actual task",     "i2" ); 
...
and the result is
Task1 after 5000ms - time constraint
Finished one of the two : i1
Task2 after 7000ms - actual task

Wednesday, April 3, 2024

Take just a single visible character?

Fairly simple requirement - get a first letter of profile description and present it together with a link. You get the idea, if I have two profiles, Foo and Bar, I want two links with F and B respectively.
The first version of the code (not even mentioned here) was just something like: if string has at least one character, take uppercase of the first character.
This seemingly simple approach completely ignores Emojis which are handled in C# strings as two consecutive chars. The second version of the code was then:
public static string ToShortDescription( this string source )
{
	var description = source?.Trim();

	if ( !string.IsNullOrWhiteSpace( description ) && description.Length >= 1 )
	{
		if ( char.IsSurrogatePair( description, 0 ) )
		{
			return description.Substring( 0, 2 ).ToUpper();
		}
		else
		{
			return description.Substring( 0, 1 ).ToUpper();
		}
	}

	return "?";
}
This is better, much better. It's not just the first character of the string, it's the substring that has the length of 2. This simple approach correctly handles many two-char Emojis, like the male mage Emoji, 🧙, encoded as &#x1F9D9;.
Unfortunately, it's just the beginning of the story. It turns out some Emojis are combined from other Emojis. Let's take the mage emoji. Its female version, 🧙‍♀️, is encoded as male mage Emoji followed by additional characters to indicate female version (&#x1F9D9;&#x200D;&#x2640;&#xFE0F;). The special character used to glue together emojis is the Zero-Width-Joiner (ZWJ).
Take a C# string that starts with the female mage emoji. This time it's not the 2 characters that should be taken from it, now it's 5! The two-char Emoji, the ZWJ, and another two-char Emoji!
Let this sink in - in order to have a single visible character on the screen, we need to take 5 first characters of the C# string!
And as you can expect, the above version of code correctly discovers the first surrogate but fails to discover the ZWJ.
There's even a discussion on SO on how to detect this.
My current approach is
public static string ToShortDescription( this string source, bool autoUpper = true )
{
	var description = source?.Trim();

	if ( !string.IsNullOrWhiteSpace( description ) && description.Length >= 1 )
	{
		// należy brać kolejne znaki na następujących zasadach
		// * jeśli zwykły znak - bierze się i koniec
		// * jeśli zjw - bierze się i nie koniec
		// * jeśli surrogatepair bierze się dwa i nie koniec
		char[] sourceChars = source.ToCharArray();
		List<char> destChars = new List<char>();

		var index = 0;
		bool takeAgain;
		bool zjw;

		do
		{
			takeAgain = false;

			// czy jest jeden i jeszcze jeden za nim (dwuznaki)
			if ( index < sourceChars.Length - 1 )
			{
				// surogat
				if ( char.IsSurrogatePair( sourceChars[index], sourceChars[index + 1] ) )
				{
					destChars.AddRange( new[] { sourceChars[index], sourceChars[index + 1] } );

					index    += 2;
					takeAgain = true;
				}
			}

			if ( index < sourceChars.Length - 2 )
			{
				// zjw - skleja dwa emoji
				if ( sourceChars[index] == (char)8205 )
				{
					destChars.AddRange( new[] { sourceChars[index], sourceChars[index + 1], sourceChars[index + 2] } );

					index    += 3;
					takeAgain = true;
				}

			}


		} while ( takeAgain && index < sourceChars.Length );

		// weź jeszcze jeden jeśli jeszcze nie ma nic lub zjw
		if ( !takeAgain && 
			 index <= sourceChars.Length-1 &&
			 destChars.Count == 0 
			)
		{
			destChars.Add( sourceChars[index] );
		}

		string _result = new string( destChars.ToArray() );

		return autoUpper ? _result.ToUpper() : _result;

		/*
		if ( char.IsSurrogatePair( description, 0 ) )
		{
			return description.Substring( 0, 2 ).ToUpper();
		}
		else
		{
			return description.Substring( 0, 1 ).ToUpper();
		}
		*/
	}

	return "?";
}
This passes some important unit tests. Namely, it correctly handles the England Emoji flag emoji, the 🏴󠁧󠁢󠁥󠁮󠁧󠁿 (&#x1F3F4;&#xE0067;&#xE0062;&#xE0065;&#xE006E;&#xE0067;&#xE007F;), which still is a single visible sign but in this extreme case it's the first 14 characters of the C# string! I believe there's still a room for improvement (and possibly other strange cases that I still miss).

Thursday, January 25, 2024

Never, ever make your Random static

Years ago it was popular to advocate for sharing the instance of the Random class. There are numerous sources, including blogs, the stack, etc. Ocasionally, someone dared to write that it could not be the best idea. But still, looking for information, people stumle across this decade-old recommendation.
That was the case of one of our apps. In one critical place, a shared instance of random was used

public static Random _rnd = new Random();

...
..._rnd.Next()...
This worked. For years. Until one day, it failed miserably.
You see, the random has two internal variables it overwrites each time Next is called so that it can advance to the next random value. If your app is just winning a lottery ticket in its concurrent execution, the two values can end up being overwritten with the same value.
And guess what, random starts to return 0 each time Next is called! For us, it was the case of an internal stress test, where a heavy traffic was directed onto the application but it can happen just anytime.
There are numerous solutions. First, starting from .NET6 there's the Random.Shared static property, marked as thread-safe. In older frameworks, one of alternative approaches should be used, e.g. this

Monday, January 15, 2024

An interesting edge case in C# yield state machines

Among many useful LINQ methods, there's no functional ForEach. People often implement it on their own, an extension method is just a few lines of code.
Someone did that in one of our projects, too:
public static void ForEach1<T>( this IEnumerable<T> enumeration, Action<T> action )
{
	foreach ( T item in enumeration )
	{
		action( item );
	}
}
This works great. Someone else, however, noticed that while this works great, it doesn't allow further chaining, since the method returns void
This someone else modified the code slightly:
public static IEnumerable<T> ForEach2<T>( this IEnumerable<T> enumeration, Action<T> action )
{
	foreach ( T item in enumeration )
	{
		action( item );
		yield return item;
	}
}
This doesn't work great. Frankly, it doesn't work at all. Surprising but true. Take this:
internal class Program
{
	static void Main( string[] args )
	{
		Test1();
		Test2();

		Console.ReadLine();
	}

	static void Test1()
	{
		var array = new int[] { 1,2,3 };

		var list = new List<int>();

		array.ForEach1( e => list.Add( e ) );

		Console.WriteLine( list.Count() );
	}
	static void Test2()
	{
		var array = new int[] { 1,2,3 };

		var list = new List<int>();

		array.ForEach2( e => list.Add( e ) );

		Console.WriteLine( list.Count() );
	}
}

public static class EnumerableExtensions
{
	public static void ForEach1<T>( this IEnumerable<T> enumeration, Action<T> action )
	{
		foreach ( T item in enumeration )
		{
			action( item );
		}
	}

	public static IEnumerable<T> ForEach2<T>( this IEnumerable<T> enumeration, Action<T> action )
	{
		foreach ( T item in enumeration )
		{
			action( item );
			yield return item;
		}
	}
}
While this is expected to produce 3 for both tests, it produces 3 and 0. The upgraded version doesn't work as expected.
The reason for this is a kind-of-a-limitation of the state machine generated by the yield sugar. The machine doesn't execute any code until the very result is enumerated. This means that changing
array.ForEach2( e => list.Add( e ) );
to
array.ForEach2( e => list.Add( e ) ).ToList();
would "fix it". What a poor foreach, though, that requires an extra terminator (the ToList) and doesn't work otherwise.
Luckily, a simpler fix exists, just forget the state machine at all for this specific case:
public static IEnumerable<T> ForEach2<T>( this IEnumerable<T> enumeration, Action<T> action )
{
	foreach ( T item in enumeration )
	{
		action( item );
	}

	return enumeration;
}

Thursday, June 1, 2023

C# Puzzle No.25 (intermediate)

Let's have list of references to objects of a custom type that have a state. Let's loop through the list and alter the internal state of each object on the list.

Will the change of the internal state be preserved after the loop ends?

A first answer should of course be yes.

Take a look at this then:

var elements =
    Enumerable.Range(0, 10)
        .Select( i => new Foo() { Bar = i });

foreach ( var e in elements )
{
    // yields 0,1,2,3,4,5,6,7,8,9 which is correct
    Console.WriteLine( e.Bar );
}

foreach ( var e in elements )
{
    e.Bar += 10;

    // yields 10, 11, ...., 19
    Console.WriteLine( e.Bar ); 
}

foreach ( var e in elements )
{
    // yields 0,1,2,3,4,5,6,7,8,9 which doesn't seem correct 
    // (original values restored)!
    Console.WriteLine( e.Bar );
    
    // expected: 10, 11, ..., 19!
}


public class Foo
{
    public int Bar { get; set; }
}

First we create a list of elements. Then we loop it to check if it's correct. Then we loop it to alter the internal state of objects.

Then we loop again and, oddly, it seems like original values are restored.

Not that obvious to spot what's wrong here, a similar issue was caught on production code. The goal is to find a simplest fix.

Wednesday, November 22, 2017

Useful caching pattern

One of the SO answers contains an interesting caching pattern, proposed by user Keith
static string GetCachedData(string key, DateTimeOffset offset)
{
    Lazy<string> lazyObject = new Lazy<string>(() => SomeHeavyAndExpensiveCalculationThatReturnsAString());

    var available = MemoryCache.Default.AddOrGetExisting(key, lazyObject, offset); 

    if (available == null)
       return lazyObject.Value;
    else
       return ((Lazy<string>)available).Value;
}
It relies on the MemoryCache::AddOrGetExisting returning null on the very first call that adds the item to the cache but returning the cached item in case it already exists in the cache. A clever trick worth of remembering.

Thursday, November 21, 2013

X509Certificate2 certificate conversions

X509 certificates are useful for many common tasks. Some time ago I’ve blogged on how to create certificates programatically and how to sign and verify XML data in an interoperable way.

There are some common tasks about certificates. Let’s begin.

To access a system store and enumerate it:

X509Store store = new X509Store( StoreName.My, StoreLocation.CurrentUser );
store.Open( OpenFlags.ReadOnly );
 
foreach ( var cert in store.Certificates )
{
    Console.WriteLine( cert.ToString() );
}

To access a file system store (*.pfx) and enumerate certificates:

X509Certificate2Collection store = new X509Certificate2Collection();
store.Import( @"c:\filename.pfx", "password", X509KeyStorageFlags.DefaultKeySet );
 
foreach ( var cert in store.OfType<X509Certificate2>() )
{
    Console.WriteLine( cert.ToString() );
}

To load a single certificate from a file system store (*.pfx):

X509Certificate2 cert = 
  new X509Certificate2( @"c:\filename.pfx", "password", X509KeyStorageFlags.MachineKeySet );
Console.WriteLine( cert.ToString() );

To export a X509Certificate2 object to a file store (*.pfx) (with private key and protected with a password):

X509Certificate2 cert = ...;
File.WriteAllBytes( "cert.pfx", cert.Export( X509ContentType.Pkcs12, "foo" ) );

To export only a public key of the X509Certificate2 to a file (*.cer):

X509Certificate2 cert = ...;
File.WriteAllText( "cert.cer", Convert.ToBase64String( cert.Export( X509ContentType.Cert ) ) );

And last but not least, if you have a certificate in Base64 form (for example from ADFS2 federation metadata), just create a blank text file with *.cer extension, copy the base64 certificate, save. The file can be used from within the Windows shell.

(a side note here: although most web sources claim that base64 encoded certificates in text form need the ----BEGIN CERTIFICATE----- preamble and -----END CERTIFICATE----- at the end, this is not necessary).

For example, a first googled certificate from here stored in a cert.cer text file

and double clicked from the OS shell opens up as

Friday, May 11, 2012

An easy way to become a PowerShell programmer

I admit – I barely use PowerShell. I am not an administrator and most things I do involve compiled code rather than scripting.

However, from time to time there is something to be done at production servers like “connect to Sql Server, do this, this and that” or “find all files in a specified folder and perform a regex replace”.

From my perspective, such tasks are easily handled in a high-level programming language but there’s a caveat – what I can do is I can compile my code and give the executable file to my colleague who is an administrator. He has to trust that the executable contains only the code to perform the required task.

An alternative approach involves writing shell scripts, old good vbs/js scripts or PowerShell scripts. An advantage of a script is that it can be easily examined against any unwanted code. A distadvantage of a script is that every few weeks/months I need to write one, I start from the same basic tutorials just to refresh my memory on what’s the syntax, how to define variables, how to create object instances, invoke methods etc.

Until now.

I just stumbled upon a simple way to easily embed C# code to PowerShell scripts. This involves the Add-Type cmdlet which is supposed to define types in a PowerShell session. What I wasn’t aware of is that the cmdlet is capable of creating types from C# strings.

#test.ps1
$code = @"
    using System;
    public class Foo
    {
        public void Bar( int x )
        {
            Console.WriteLine( x );
            Console.ReadLine();
        }
    }    
"@
 
Add-Type -TypeDefinition $code
 
$foo = New-Object Foo
$foo.Bar( 5 )

As always, to run the script I have to bypass the signing requirement, from the command line:

powershell.exe -ExecutionPolicy bypass -File ./test.ps1 

or from within the PowerShell console:

Set-ExecutionPolicy unrestricted
./test.ps1

An example of referring to Windows.Forms:

#test2.ps1
$code = @"
    public class TestForm : System.Windows.Forms.Form
    {
        
    }
"@
 
Add-Type -TypeDefinition $code -ReferencedAssemblies "System.Windows.Forms"
 
$form = New-Object TestForm
$form.ShowDialog();

Great. Now I can finally be a PowerShell programmer :)

Thursday, June 19, 2008

C# Lambda Expressions Can Contain Method Bodies

I know a lot of people who love and use the lambda expression syntax provided in C# 3.0 as a shortcut for explicit delegate definitions.

Suprisingly however, quite few of them actually know that lambda expression can not only have a suprisingly variable => expression form like:

x => x < 5

but can also contain method bodies as expressions like



x => { Console.WriteLine( x ); return x < 5; }

Monday, June 16, 2008

C# 3.0 Mixins with Interfaces, Extension Methods Wrapper Classes and Implicit Conversion Operators

Mixin is a programming language technique in which you extend classes with methods and properties by so called mixins. In C++ mixins are easily achieved using multiple inheritance, while in C# or Java you have to find out how to work around the single inheritance.

There is a long discussion on the matter and people are proposing ways to build mixins in C#. What they usually focus on is extending classes with additional methods (here or here) while, in fact, mixins is not only about methods but also about other class members. In his blog, Colin Mackay has pointed three possible ways to actually build mixin extensions which can hold data.

What I'd like to point out is that there is yet another possibility based on inheritance but this time you inherit from extended classes rather than making them inherit from a base class. In case of structures which are sealed, you just create wrapper classes.

Let's start with the mixin declaration:

interface IMixin
{
    int TheProperty { get; set; }
}
 
static class IMixinExtension
{
    public static void Extension1( this IMixin Mixin )
    {
        Console.WriteLine( "Value of mixin property: " + Mixin.TheProperty.ToString() );
    }
}

The interface describes mixin structure while the extension method adds a logic for it. Now we are ready to augment classes.



class StringMixin : IMixin
 {
     string _string;
     public StringMixin( string String )
     {
         this._string = String;
     }
 
     #region IMixin
     public int TheProperty { get; set; }
     #endregion
 
     #region Conversion
     public static implicit operator string( StringMixin Mixin )
     {
         return Mixin._string;
     }
 
     public static implicit operator StringMixin( string String )
     {
         return new StringMixin( String );
     }
     #endregion
 
     #region Delegated methods
     public override string ToString()
     {
         return _string.ToString();
     }
 
     public string ToLower()
     {
         return _string.ToLower();
     }
 
     // etc...
     #endregion
 }

As you can see it's not quite ellegant because there's no default delegation so I cannot delegate methods from System.string to the _string member of the class, however from the client's point of view, StringMixin is just a string with additional properties:



class StringClient
{
    public static void ExpectsString( string String )
    {
        Console.WriteLine( String );
    }
}
 
class Program
{
    static void Main( string[] args )
    {
        StringMixin mixin = "The string";
 
        StringClient.ExpectsString( mixin );
    }
}

On the other hand, extended class behaves just as mixin is supposed to behave: it has been augmented with additional members but base members are still there:



class Program
{
    static void Main( string[] args )
    {
        StringMixin mixin = "The string";
 
        // it's still a string
        Console.WriteLine( mixin.ToLower() );
        // but augmented with properties
        Console.WriteLine( mixin.TheProperty.ToString() );
        // and methods
        mixin.Extension1();
    }
}

Note that since the original class is wrapped, the wrapper can contain any additional data  so the "dataless mixins" issue is gone.


The drawback is obvious : you need extra wrapper class for each class you'd like to augment with a mixin. Note that in case of reference types there's no need to wrap - instead of wrapping the class you can just inherit from it.

Thursday, June 12, 2008

C# Puzzle No.2 (level: intermediate)

Following code snippet is commonly used in C/C++ to exchange values of two integer values with no help of any additional variable.

int x, y;
 
x ^= y ^= x ^= y;

This surprisingly does not work in C#. Can you explain why?

C# Puzzle No.1 (level: beginner)

Would you like to see a collection which magically creates an item as soon as you ask for it? Well, here it is. The collection is asked to return a value for a key, and volia, you will be informed that the item exists in the collection.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main( string[] args )
        {
            NameValueCollection Collection = new NameValueCollection();
 
            Console.WriteLine( 
                "Does NameValueCollection magically create items? " +
                Collection["foo"] != null ? " Yes, it does!" : "No, it doesn't." 
                );
        }
    }
}

Can you spot the problem in the code?