How to use the keyword 'with' on an interface without knowing the underlying record type?

Viewed 252

In C#, is there a way of using the with keyword on an interface, without knowing the type (or base type) of the object?

I'm imagining something like the DoSomething method in the following pseudo-code (which is not valid c#). The code DoSomething would be expected to act on all records that implement ISomeRecord.

The DoSomething2 method would compile, but work only in records of type SomeRecord and not of records of types other than SomeRecord.

public interface ISomeRecord
{
  bool SomeProp { get; }
}

public record SomeRecord : ISomeRecord 
{ 
  public bool SomeProp { get; init; } 
}

public class SomeUtil
{
  public ISomeRecord DoSomething(ISomeRecord rec)
  {
    return ( rec as record ) with { SomeProp = false };
  }
  public ISomeRecord DoSomething2(ISomeRecord rec)
  {
    return ( rec as SomeRecord ) with { SomeProp = false };
  }
  public ISomeRecord DoSomething3<T>(T rec) where T : struct, ISomeRecord
  {
    return rec with { SomeProp = false };
  }
}

As an aside, in C# 10 (in preview at moment of writing) I notice that DoSomething3 compiles. C# 10 introduces record structs and record classes. The latter is the default. It appears what I'm after is possible for record struct objects, but not for record class objects. In other words, in the example,DoSomething3 can't be called with a SomeRecord as an argument unless SomeRecord is changed to a record struct.

I don't see a way to do the same with a record class which is what I need in my use case.

0 Answers
Related