β Cast is not valid when casting interface to comcrete impl
this is my concrete imp:
public class TempFile : IBrowserFile
{
public TempFile(string uuid, string name, long size, string contentType)
{
Uuid = uuid;
Name = name;
Size = size;
ContentType = contentType;
}
public TempFile()
{
}
public string Uuid { get; set; } = "";
public string ContentType { get; set; } = "";
public string Name { get; set; } = "";
public long Size { get; set; }
public DateTimeOffset LastModified => throw new NotImplementedException();
public Stream OpenReadStream(long maxAllowedSize = 512000, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
}
=========================
this is where im trying to cast ibrowserFile as TempFile and getting invalid Cast.
private async Task UploadFileAsync(IBrowserFile file)
{
if (file == null)
return;
if (EditModel == null)
{
throw new Exception("No edit model");
}
if (EditModel.Id == 0)
{
var result = await this.EmployeeComptesDepensesService.UploadTemporaryAttachmentFileAsync(file);
if (!result.ApiCallSuccess)
{
this.serverResponseValidator?.DisplayErrors(result.ServerErrors, result.ApiCallResultErrorMessage);
}
else
{
try
{
TempFile tf = (TempFile)file;
tf.Uuid = result.ResultModel?.Result!;
EditModel.TempFiles.Add(tf);
} catch (Exception ex) {
this.serverResponseValidator?.DisplayErrors(null, $"cast error {ex.Message}"); } } } What's going on???
} catch (Exception ex) {
this.serverResponseValidator?.DisplayErrors(null, $"cast error {ex.Message}"); } } } What's going on???
8 Replies
$code
To post C# code type the following:
```cs
// code here
```
Get an example by typing
$codegif
in chat
If your code is too long, post it to: https://paste.mod.gg/While you know a cat is an animal, how do you know that an animal is a cat?
Hazel | γΈγγγ
REPL Result: Failure
Exception: InvalidCastException
Compile: 653.168ms | Execution: 53.051ms | React with β to remove this embed.
This doesn't work because an animal is not a cat, even though a cat is an animal.
hmm i thought i could cast both directions and it would just fill the minimum fields that are part of the animal interface
nope, u would have to write such a mapping urself
it could be done with implementing custom casts, but in this case it feels like a
ToTempFile()
method or similar has better semantics/intention is clearerWas this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.