Generics method using interface in c#


Implement an Interface with Generic Methods

namespace Win.Data
{
    // Created Interface for field of table 
    public interface IFieldTable
    {
        string Id { getset; }
        DateTime TimeStamp { getset; }
        string User { getset; }
        string View { getset; }
        string Name { getset; }
        //string QData { get; set; }
    }
 
    // FieldString class inhirated from IFieldTable 
    public class FieldString : IFieldTable
    {
        public string Id { getset; }
        public DateTime TimeStamp { getset; }
        public string User { getset; }
        public string View { getset; }
        public string Name { getset; }
        public string Data { getset; }
    }
 
    // FieldInt class inhirated from IFieldTable
    public class FieldInt : IFieldTable
    {
        public string Id { getset; }
        public DateTime TimeStamp { getset; }
        public string User { getset; }
        public string View { getset; }
        public string Name { getset; }
        public int Data { getset; }
    }
 
    // FieldBool class not inhirated from IFieldTable
    public class FieldBool
    {
        public string Id { getset; }
        public DateTime TimeStamp { getset; }
        public string User { getset; }
        public string View { getset; }
        public string Name { getset; }
        public bool Data { getset; }
    }
 
    public class MyClass
    {
        // Implemented generic method for IFieldTable interface
        // new() it use here for create new object for type T
        // This Method return IList Type of T where T is class implemented 
        // from IFieldTable Interface 
        public static IList<T> GetFieldData<T>() where T : IFieldTablenew()
        {
            IList<T> lst = new List<T>();
 
            T t = new T();
            t.User = "Harshal Patel";
            t.Name = "Field_Name";
            t.View = "Form_Name";
            t.TimeStamp = DateTime.Now;
 
            switch (t.GetType().Name)
            {
                case "FieldInt":
                    (t as FieldInt).Data = 0;
                    break;
                case "FieldString":
                    (t as FieldString).Data = "Data";
                    break;
                default:
                    break;
            }
            lst.Add(t);
            return lst;
        }
         
    }
}

Now you will be call this generic method from your code like below. 
// Here method call for FieldString class
var lstString = MyClass.GetFieldData<FieldString>();
// Here method call for FieldInt class
var lstInt = MyClass.GetFieldData<FieldInt>();
// Here will get the compile time error,
//Because of FieldBool class not inherited from IFieldTable interface
var lstBool = MyClass.GetFieldData<FieldBool>();

Comments

Popular posts from this blog

Get OAuth 2.0 access token of Paypal using HttpClient in c#