C# Equivalent for TS Union Type

Does anyone know if there’s a simple way to have something similar to a typescript union type in C#?

As an example, I have this block of code which has two nearly identical paths that could be massively simplified if I could have something like: formModel: FormPreviewModel | FormPreviewIcoModel.

if (reportRequest.ReportModality == ReportModality.ILO)
{
	FormPreviewModel formModel;
	if (reportSubmission.FormModel != null) 
	{
		formModel = JsonConvert.DeserializeObject<FormPreviewModel>(reportSubmission.FormModel);
	}
	else
	{
		formModel = formConversionHelper.ConvertToFormPreviewModel(reportSubmission);
		reportSubmission.FormModel = JsonConvert.SerializeObject(formModel);
		await _crudService.Update(reportSubmission);
	}
	
	// Add radiologist name to preview
	if (string.IsNullOrEmpty(formModel.RadiologistName))
		formModel.RadiologistName = $"{radiologist.FirstName[..1]} {radiologist.LastName}";

	var actionResult = CreatePreviewFromModel(formModel);

	return actionResult;
}
else
{
	FormPreviewIcoModel formModel;
	if (reportSubmission.FormModel != null) 
	{
		formModel = JsonConvert.DeserializeObject<FormPreviewIcoModel>(reportSubmission.FormModel);
	}
	else
	{
		formModel = formConversionHelper.ConvertToFormPreviewIcoModel(reportSubmission);
		reportSubmission.FormModel = JsonConvert.SerializeObject(formModel);
		await _crudService.Update(reportSubmission);
	}
	
	// Add radiologist name to preview
	if (string.IsNullOrEmpty(formModel.RadiologistName))
		formModel.RadiologistName = $"{radiologist.FirstName[..1]} {radiologist.LastName}";

	var actionResult = CreatePreviewFromModel(formModel);

	return actionResult;
}

There is no union types in C#, the way to get what you want done the easiest would be to make both of those classes share a base class with all of the shared properties and then you can declare the model as the base class. This would enable you to do something like this.

BaseFormPreviewModel formModel;
if (reportRequest.ReportModality == ReportModality.ILO)
{
	formModel = JsonConvert.DeserializeObject<FormPreviewModel>(reportSubmission.FormModel);
}
else
{
	formModel = JsonConvert.DeserializeObject<FormPreviewIcoModel>(reportSubmission.FormModel);
}

// Rest of the logic goes here
1 Like