Search code examples
c#.net-coreinheritance

How to declare a function parameter to accept all derived types of a generic abstract type?


these are base type

[DataContract]
public abstract class InputModelBase<T>where T : InputModelParametersBase
{
    [DataMember]
    public string Token { get; set; }
    [DataMember]
    public bool Trace { get; set; }
    [DataMember(Name = "parameters")]
    public T Parameters { get; set; }
}

public class InputModelParametersBase: IInputModelParameters
{
  public string staticToken { get; set; }
  public bool trace { get; set; }
}

public interface IInputModelParameters
{
  public string staticToken { get; set; }
  public bool trace { get; set; }
}

these derived types:

public class SearchInput: InputModelBase<SearchParameters>
{
}

public class SearchParameters: InputModelParametersBase
{
  [DataMember]
  public string Query { get; set; }
}

what i need is create a function that accept all derived types from InputModelBase i tried this but it doesn't work

public void someFunction(InputModelBase<InputModelParametersBase> oInputParams)
{
}

calling someFunction throw exception

var oSearchInput = new SearchInput();
someFunction(oSearchInput);

Severity Code Description Project File Line Suppression State Error CS1503 Argument 1: cannot convert from 'SearchInput' to 'InputModelBase'

how to declare someFunction to make it accept all derived types of InputModelBase?


Solution

  • Make your Method as a generic method as following

    public void someFunction<T>(InputModelBase<T> oInputParams) where T : InputModelParametersBase
    {
    }