Tag Archives: C#

Recursive Polymorphic Deserialization with System.Text.Json

,

Goal: Deserialize a nested JSON structure, where the objects instantiated are not instances of the given abstract base type but rather are of the appropriate derived types.

In other words, if the specified destination type is AbstractBaseTpe, which should be returned is not an instance of that class but rather an instance of ChildTypeA or ChildTypeB or GrandchildType1, etc., as appropriate. This polymorphic deserialization behavior should hold true at the root level (that is, for the type directly returned by JsonSerializer.Deserialize<AbstractBaseType>(…)), as well as recursively for nested properties (that is, anytime the destination property is of type AbstractBaseType, the object instantiated for the property should be of the appropriate derived type, like ChildTypeA, etc.).

Hopefully, one day support for something along these lines will be built into System.Text.Json. However, for now, when we need it, we have craft our own solution (or borrow one from someone else).

In my case, the other day I needed a simple solution for polymorphic deserialization. Performance wasn’t critical. Just something simple that worked.

Continue reading

Always Identical Outputs? Switch Statement vs. Switch Expression

, ,

Are these two statements identical in what they return?

public object Switcher(bool flag) 
{
  switch (flag) {
    case true:
      return 1;
    case false:
     return 10.5;
  }
}
public object Switcher(bool flag) 
{
  return flag switch {
    true => 1,
    false => 10.5
  };
}

No.

TestResult –
Switch Statement
Result –
Switch Expression
Assert.Equal(1, x.Switcher(true));PassFail – Error Message:
Assert.Equal() Failure
Expected: 1 (System.Int32)
Actual: 1 (System.Double)
Assert.Equal(10.5, x.Switcher(false));PassPass

Scratching your head trying to find the difference? The logic in both looks identical. Arguably, it is.

Continue reading

SQL for C# Developers

, ,

You’re a developer. You know how to write code that interacts with databases. Using tools like Entity Framework and LINQ, you can push and pull data to and from data sources. But how comfortable are you directly talking to a relational database in its native dialect—SQL? Maybe you can cobble together a basic SELECT statement—but when you do, do you feel like a traveler in a strange land where you barely know the language?


Continue reading

Understanding Cancellation Callbacks

, , , ,

In the ideal world, all .Net asynchronous methods support cancellation tokens: When invoking a method, simply pass it a cancellation token. Then, at the appropriate time, cancel the token and the asynchronous operation terminates.

Alas! We don’t live in the ideal world. Not every method we might asynchronously invoke works with cancellation tokens. When faced with an asynchronous operation we want to be able to cancel that doesn’t support cancellation tokens, one option is to implement our own cancellation logic by registering a callback with the token. When the token is cancelled, callbacks registered with it are executed.

Introducing callback into the picture raises questions around if/when, where and how those callbacks are executed. For example:

  • Will the callback be invoked via the synchronization context that was current when it was registered?
  • If multiple callbacks are registered, are they run synchronously or in parallel?
  • If a callback raises an exception, can that exception be caught?

In the case of .Net’s Task Parallel Library and its CancellationToken and CancellationTokenSource, the answers to these questions revolve around when cancellation occurs and how it is triggered.
Continue reading

Passing a String Where It Isn’t Expected:
Exploring the Implicit Conversion Alternative

, ,

Let’s say you maintain a class whose constructor expects a configuration object:

class MyDbConnection {
  public MyDbConnection(MyDbConfiguration config) { … }
}
...
var config = new MyDbConfiguration { Server = "SuperFastDbServer", User = "jsmith", Password = … };
var connection = new MyDbConnection(config);

Along the way, developers asked for a simple, textual way to set configuration options. To accommodate this, you gave the configuration class a constructor that accepts a settings string as its argument:

var connection = new MyDbConnection(new MyDbConfiguration("server=SuperFastDbServer;user=jsmith;password=…"));

Now, you’ve received a request to further streamline usage by allowing the configuration string to be passed directly to the main class, bypassing the need to reference the settings class:

var connection = new MyDbConnection("server=SuperFastDbServer;user=jsmith;password=…");

Since the goal is to construct instances of the main class by passing a string, it seems the way to implement this request is to give the main class a constructor that accepts a string as its argument.

Surprisingly, adding a constructor isn’t the only way to achieve the desired effect! In fact, it’s possible to satisfy this request without any modifications to the main class. Likely, you’ve already used the functionality that makes this possible—though perhaps without realizing you could use it with classes and structs you create.

However, there is a philosophical question about the appropriateness of applying this technique in this scenario. We’ll touch on this question later. Even if you decide against using the technique in this case, knowing about it hopefully will come in handy down the road when you encounter other, unquestionably appropriate situations where it can be used. Continue reading

Make It Easier for the DBA: Give SQL Connections the Application’s Name!

, , , , ,

Imagine you’re a database administrator tracing query activity on a server. You’d want all the clues you can get to help you figure out what’s going on. One clue is the name of the client program associated with each database session. This name, passed from client to Microsoft SQL Server when a connection is established, can be used by the DBA to differentiate between multiple applications running on a single client and to focus on (or filter out) activity from the same application across multiple clients.

Does your application pass a meaningful program name to the database server?

Continue reading

NetMsmqIntegrationBinding — No Data Being Passed

, ,

Recently, I encountered a strange problem with a simple WCF NetMsmqIntegrationBinding service. The data objects passed into my service contained no data! When a message was received, the service would create an instance of the appropriate DataContract class but then would not populate the just-constructed object with the data contained in the WCF message (i.e. the data object’s fields were all left at their default values—null, 0, empty string, etc.). Continue reading

C# Boolean Expressions With and Without Short-Circuiting

For years I’ve used the && and || operators in C# Boolean expressions (e.g. if (age > 60 && gender == male) { /* do something */ }). Today, I was surprised to learn that & and | can also be used to compare bool values (this is in addition to their traditional use as bitwise AND and OR operators).

What’s the difference between the two pairs of operators? && and || use short-circuit evaluation while & and | do not. Continue reading