Bunty Choudhary
Bunty Choudhary

Reputation: 243

Expose generic property in c#

enter image description hereI need to expose my generic class property directly. SEE IN CODE BELOW

namespace ConsoleApp2
{
    public class KTEST<T>
    {
        public int PageNumber { get; set; }
        public int PageSize { get; set; }
        public T Filter { get; set; }

    }

    public class Request
    {
        public int CountryId { get; set; }
    }

    class Program
    {
        public static void Main(string[] args)
        {
            KTEST<Request> kTESTRequest = new KTEST<Request>();

            kTESTRequest.PageNumber = 1;
            kTESTRequest.PageSize = 20;

            kTESTRequest.Filter.CountryId = 1;
        }
    }
}

Now, how can I get the countryId property without use of 'Filter'. I need to use kTESTRequest.CountryId instead of kTESTRequest.Filter.CountryId

Could you please help me to out this.

Upvotes: 0

Views: 132

Answers (1)

TheGeneral
TheGeneral

Reputation: 81573

The only way to do this is with an interface

Given

public interface IMyInterface
{
    public int CountryId{ get; set; }
}

Usage

public class KTEST<T>  where T : IMyInterface
{
    public int PageNumber { get; set; }
    public int PageSize { get; set; }
    public T Filter { get; set; }
    public int CountryId => Filter.CountryId
}

Requirement

public class Request : IMyInterface
{
    public int CountryId { get; set; }
}

Upvotes: 1

Related Questions